Search code examples
javapython-2.7jython

Jython: different behaviour with 'is' keyword


I'm writing some scripts in Python that need to work with certain Java libraries, therefore I use Jython. I noticed that after compiling, comparison of variables with is yields different results than in Python shell.

I know that is and == have different purpose in Python but shouldn't the behavior after compiling match behavior in the shell?

This is simplified function I wrote in my script:

def test(myString='AAA'):
    print myString is 'AAA'

test()

Now, when I run this with Python, the result is True, but after compiling with Jython, the result is False.

After that I've changed the is keyword to == and results were matching.

I'm curious why the result is different. I'm assuming that after compiling, Java checks reference rather than value but so should Python, right?


Solution

  • The is keyword in Python is used to test if two values refer to the same object. In your example it will only return True if and only if the strings are interned (cf https://en.wikipedia.org/wiki/String_interning). This is highly implementation specific.

    To lexicographically compare strings you should use ==.