How is the 'is' keyword implemented in Python?

43,188

Solution 1

Testing strings with is only works when the strings are interned. Unless you really know what you're doing and explicitly interned the strings you should never use is on strings.

is tests for identity, not equality. That means Python simply compares the memory address a object resides in. is basically answers the question "Do I have two names for the same object?" - overloading that would make no sense.

For example, ("a" * 100) is ("a" * 100) is False. Usually Python writes each string into a different memory location, interning mostly happens for string literals.

Solution 2

The is operator is equivalent to comparing id(x) values. For example:

>>> s1 = 'str'
>>> s2 = 'str'
>>> s1 is s2
True
>>> id(s1)
4564468760
>>> id(s2)
4564468760
>>> id(s1) == id(s2)  # equivalent to `s1 is s2`
True

id is currently implemented to use pointers as the comparison. So you can't overload is itself, and AFAIK you can't overload id either.

So, you can't. Unusual in python, but there it is.

Solution 3

The Python is keyword tests object identity. You should NOT use it to test for string equality. It may seem to work frequently because Python implementations, like those of many very high level languages, performs "interning" of strings. That is to say that string literals and values are internally kept in a hashed list and those which are identical are rendered as references to the same object. (This is possible because Python strings are immutable).

However, as with any implementation detail, you should not rely on this. If you want to test for equality use the == operator. If you truly want to test for object identity then use is --- and I'd be hard-pressed to come up with a case where you should care about string object identity. Unfortunately you can't count on whether two strings are somehow "intentionally" identical object references because of the aforementioned interning.

Solution 4

The is keyword compares objects (or, rather, compares if two references are to the same object).

Which is, I think, why there's no mechanism to provide your own implementation.

It happens to work sometimes on strings because Python stores strings 'cleverly', such that when you create two identical strings they are stored in one object.

>>> a = "string"
>>> b = "string"
>>> a is b
True
>>> c = "str"+"ing"
>>> a is c
True

You can hopefully see the reference vs data comparison in a simple 'copy' example:

>>> a = {"a":1}
>>> b = a
>>> c = a.copy()
>>> a is b
True
>>> a is c
False

Solution 5

If you are not afraid of messing up with bytecode, you can intercept and patch COMPARE_OP with 8 ("is") argument to call your hook function on objects being compared. Look at dis module documentation for start-in.

And don't forget to intercept __builtin__.id() too if someone will do id(a) == id(b) instead of a is b.

Share:
43,188
Srikanth
Author by

Srikanth

Updated on July 05, 2022

Comments

  • Srikanth
    Srikanth about 2 years

    ... the is keyword that can be used for equality in strings.

    >>> s = 'str'
    >>> s is 'str'
    True
    >>> s is 'st'
    False
    

    I tried both __is__() and __eq__() but they didn't work.

    >>> class MyString:
    ...   def __init__(self):
    ...     self.s = 'string'
    ...   def __is__(self, s):
    ...     return self.s == s
    ...
    >>>
    >>>
    >>> m = MyString()
    >>> m is 'ss'
    False
    >>> m is 'string' # <--- Expected to work
    False
    >>>
    >>> class MyString:
    ...   def __init__(self):
    ...     self.s = 'string'
    ...   def __eq__(self, s):
    ...     return self.s == s
    ...
    >>>
    >>> m = MyString()
    >>> m is 'ss'
    False
    >>> m is 'string' # <--- Expected to work, but again failed
    False
    >>>
    
  • Lie Ryan
    Lie Ryan about 14 years
    the only place in Python where you want to do identity comparison is when comparing to Singletons (e.g. None) and sentinel values that needs to be unique. Other than that, there is probably almost no reason for is.
  • Jim Dennis
    Jim Dennis about 14 years
    @Lie Ryan: I tend to agree. I only ever use it for None and for special sentinels that I've created (usually as calls to the base 'object()'). However, I don't feel comfortable asserting that there's no other valid uses for the 'is' operator; just none that I can think of. (Possibly a testament to my own ignorance).
  • Jim Dennis
    Jim Dennis about 14 years
    I've observed in the past that string interning may happen for run-time computed and input values if they're sufficiently short. 'a' * 100 is not 'a' * 100; but 'a' * 20 is "a" * 20. Meanwhile 'a'.upper() is not 'a'.upper(). Jython, IronPython, PyPy and others may intern more agressively. In short it's implementation dependent. Calling the 'intern()' function on strings will "force" a string to have the same object identity as any equivalent and previously intern()'d string, as you say. However, I don't know of a valid use case for testing string identity. (Possible performance aside).
  • alexis
    alexis about 10 years
    Interesting to know, that's a whole world of possibilities to mess with python's function that I'd never thought about. But why would this ever be a good idea?
  • Brad Johnson
    Brad Johnson over 8 years
    At my company, we have an in-house testing library containing a context decorator which freezes time by replacing datetime.datetime with an implementation that always returns a specific time from utcnow(). If you run datetime.datetime.utcnow() and attempt to pickle the returned value, it will fail because its class is inconsistent (it's pretending to be another class). In this case, overriding the way is works might be a solution.
  • hyper-neutrino
    hyper-neutrino over 7 years
    You can overload id, but not in the sense you probably meant. Just do id = <function>.
  • goteguru
    goteguru about 6 years
    ("a" * 100) is ("a" * 100) might be False in 2010, but today it's True.
  • logicOnAbstractions
    logicOnAbstractions almost 5 years
    No, it is not. Try print(id(a.T) is id(a.T)) in python and you'll see.
  • Andrew
    Andrew over 4 years
    @goteguru, not for me, in 2019, with CPython 3.5.6. I think the comment by Jim from 2010 is the real winner: It's implementation dependency. Assuming nothing.
  • goteguru
    goteguru over 4 years
    @Andrew of course it's implementation sepecific, we shouldn't use 'is' for string comparision. Maybe your cython optimiser didn't interned the string for some reason. Try "a"*20 which is smaller.
  • jameshfisher
    jameshfisher over 3 years
    @logicOnAbstractions I believe he means comparing the ids with ==, not with is. So print(id(a.T) == id(a.T)) should be equivalent to print(a is a).