3.17. OOP Object Identity

  • = assignment

  • == checks for object equality

  • is checks for object identity

>>> valid = True
>>>
>>> valid == True
True
>>> valid is True
True

3.17.1. Identity

  • id(obj) -> int

  • id() will change every time you execute script

  • id() returns an integer which is guaranteed to be unique and constant for object during its lifetime

  • Two objects with non-overlapping lifetimes may have the same id() value

  • In CPython it's also the memory address of the corresponding C object

>>> id('Watney')  
4499664048
>>>
>>> hex(id('Watney'))  
'0x10c336cb0'

3.17.2. Increment Add

>>> x = 1
>>> id(x)  
4535726776
>>>
>>> x += 1
>>> id(x)  
4535726808
>>> x = [1]
>>> id(x)  
4570905344
>>>
>>> x[0] += 1
>>> id(x)  
4570905344

3.17.3. Identity Check

  • is checks for object identity

  • is compares id() output for both objects

  • CPython: compares the memory address a object resides in

  • Testing strings with is only works when the strings are interned

  • Since Python 3.8 - Compiler produces a SyntaxWarning when identity checks (is and is not) are used with certain types of literals (e.g. str, int). These can often work by accident in CPython, but are not guaranteed by the language spec. The warning advises users to use equality tests (== and !=) instead.

>>> name = None
>>>
>>> name is None
True
>>> name is not None
False

3.17.4. Caching

>>> a = 256
>>>
>>> a == 256
True
>>>
>>> a is 256  
SyntaxWarning: "is" with a literal. Did you mean "=="?
True
>>> b = 257
>>>
>>> b == 257
True
>>>
>>> b is 257  
SyntaxWarning: "is" with a literal. Did you mean "=="?
False

3.17.5. Integer Caching

  • Values between -5 and 256 are cached from start

  • After using any integer two times it is being cached

  • Python caches also the next integer

  • Cached numbers are invalidated after a while

>>> id(256)  
4514832592
>>>
>>> id(256)  
4514832592
>>>
>>> id(256)  
4514832592
>>>
>>> id(256)  
4514832592
>>> id(257)  
4561903248
>>>
>>> id(257)  
4561904272
>>>
>>> id(257)  
4561903344
>>>
>>> id(257)  
4561903344
>>> id(-5)  
4423729200
>>>
>>> id(-5)  
4423729200
>>> id(-6)  
4463320144
>>>
>>> id(-6)  
4463321840

3.17.6. Float Caching

  • It takes a bit more hits for float to start being cached

  • Cached numbers are invalidated after a while

>>> id(1.0)  
4491972048
>>>
>>> id(1.0)  
4492804656
>>>
>>> id(1.0)  
4491972048
>>>
>>> id(1.0)  
4492804656
>>>
>>> id(1.0)  
4492811728
>>>
>>> id(1.0)  
4492817392
>>>
>>> id(1.0)  
4492811792
>>>
>>> id(1.0)  
4492817392
>>>
>>> id(1.0)  
4492817616

3.17.7. Bool Type Identity

  • Bool object is a singleton

  • It always has the same identity (during one run)

>>> id(True)  
4469679168
>>>
>>> id(True)  
4469679168
>>> id(False)  
4469679896
>>>
>>> id(False)  
4469679896

3.17.8. None Type Identity

  • NoneType object is a singleton

  • It always has the same identity (during one run)

>>> id(None)  
4469761584
>>>
>>> id(None)  
4469761584

3.17.9. String Type Identity

>>> a = 'Mark Watney'
>>> b = 'Mark Watney'
>>>
>>> a == b
True
>>> a is b
False
>>> 'Mark Watney' is 'Mark Watney'  
<...>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
True

3.17.10. String Interning

  • Caching mechanism

  • String intern pool

  • String is immutable

Each time an instance of a string is created Python will create a new object with completely new identity:

>>> id('Watney')  
4354445296
>>>
>>> id('Watney')  
4354447728

However if we create an identifier, then each time a string is created it will result with the same interned string. Value of an identifier will add to the string interning pool, from which Python returns a new objects:

>>> name = 'Watney'
>>>
>>> id('Watney')  
4354447984
>>>
>>> id('Watney')  
4354447984

However if we delete entry from string interning pool, Python will now create a new instance of a string each time:

>>> del name
>>>
>>> id('Watney')  
4354449136
>>>
>>> id('Watney')  
4354449328

3.17.11. Type Identity

>>> name = ...
>>>
>>> type(name) is int
False
>>> type(name) is float
False
>>> type(name) is complex
False
>>> type(name) is bool
False
>>> type(name) is None
False
>>> type(name) is str
False
>>> type(name) is bytes
False
>>> type(name) is list
False
>>> type(name) is tuple
False
>>> type(name) is set
False
>>> type(name) is frozenset
False
>>> type(name) is dict
False

3.17.12. Object Identity

>>> class Astronaut:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>>
>>> astro1 = Astronaut('Mark', 'Watney')
>>> astro2 = Astronaut('Mark', 'Watney')
>>>
>>> astro1 is astro2
False
>>>
>>> id(astro1)  
4421890496
>>> id(astro2)  
4421893328
>>>
>>> hex(id(astro1))  
'0x10790b1c0'
>>> hex(id(astro2))  
'0x10790bcd0'
>>>
>>> print(astro1)  
<Astronaut object at 0x107905820>
>>> print(astro2)  
<Astronaut object at 0x10790bcd0>
>>> class Astronaut:
...     pass
>>>
>>> class Cosmonaut:
...     pass
>>>
>>>
>>> Astronaut is Astronaut
True
>>>
>>> Cosmonaut is Cosmonaut
True
>>>
>>> Astronaut is Cosmonaut
False
>>>
>>> id(Astronaut)  
140570740200304
>>>
>>> id(Cosmonaut)  
140570185653984

3.17.13. Object Equality

>>> class Vehicle:
...     def __init__(self, name):
...         self.name = name
...
...     def __eq__(self, other):
...         return isinstance(self, other.__class__) \
...            and self.name == other.name
...
...
>>> class Car(Vehicle):
...     pass
...
>>> class Truck(Vehicle):
...     pass
...
...
...
>>> a = Car('Mercedes')
>>> b = Car('Mercedes')
>>> c = Truck('Mercedes')
>>> d = Vehicle('Mercedes')
>>> a == a
True
>>> a == b
True
>>> a == c
False
>>> a == d
True
>>> d == a
True
>>> d == b
True
>>> d == c
True
>>> d == d
True
>>> c == a
False
>>> c == b
False
>>> c == c
True
>>> c == d
True

3.17.14. Value Comparison

  • == checks for object equality

>>> 'Mark Watney' == 'Mark Watney'
True
>>> a = 'Mark Watney'
>>> b = 'Mark Watney'
>>>
>>> a == b
True
>>> class Astronaut:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>>
>>> astro1 = Astronaut('Mark', 'Watney')
>>> astro2 = Astronaut('Mark', 'Watney')
>>>
>>> astro1 == astro2
False

3.17.15. Compare Value vs. Identity

>>> name = 'Mark Watney'
>>> expected = 'Mark Watney'
>>>
>>> name == expected
True
>>> name is expected
False
>>> name = 'Mark Watney'
>>>
>>> name == 'Mark Watney'
True
>>>
>>> name is 'Mark Watney'  
<...>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
False

3.17.16. String Value vs Identity Problem

  • CPython optimization

  • Can be misleading

>>> a = 'Mark Watney'
>>> b = 'Mark Watney'
>>>
>>> a == b
True
>>> a is b
False
>>> a is 'Mark Watney'  
<...>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
False
>>> a = 'Mark'
>>> b = 'Mark'
>>>
>>> a == b
True
>>> a is b
True
>>> a is 'Mark'  
<...>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
True

3.17.17. Use Case - 0x01

>>> class Astronaut:
...     pass
>>>
>>> class Cosmonaut:
...     pass
>>>
>>> a = Astronaut()
>>> a.firstname = 'Mark'
>>> a.lastname = 'Watney'
>>>
>>> c = Cosmonaut()
>>> c.firstname = 'Mark'
>>> c.lastname = 'Watney'
>>>
>>> a is c
False
>>>
>>> a == c
False
>>>
>>>
>>> id(a)  
4503461584
>>>
>>> id(c)  
4503287120
>>>
>>> id(a.firstname)  
4488983024
>>>
>>> id(c.firstname)  
4488983024
>>>
>>> id(a.lastname)  
4503976496
>>>
>>> id(c.lastname)  
4503976496
>>>
>>> id(a.__dict__)  
4503717056
>>>
>>> id(c.__dict__)  
4503973504
>>>
>>> a.__dict__ is c.__dict__
False
>>>
>>> a.__dict__ == c.__dict__
True

3.17.18. Use Case - 0x02

  • Make Equal

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     def __eq__(self, other):
...         return self.firstname == other.firstname \
...            and self.lastname == other.lastname
>>>
>>>
>>> user1 = User('Mark', 'Watney')
>>> user2 = User('Mark', 'Watney')
>>>
>>> user1 == user2
True
>>> user1 is user2
False

3.17.19. Use Case - 0x03

  • Equal Problem

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     def __eq__(self, other):
...         return self.firstname == other.firstname \
...            and self.lastname == other.lastname
>>>
>>>
>>> class Admin:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>>
>>> user = User('Mark', 'Watney')
>>> admin = Admin('Mark', 'Watney')
>>>
>>> user == admin
True
>>> user is admin
False

3.17.20. Use Case - 0x04

  • Make Unequal

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     def __eq__(self, other):
...         return self.__class__ is other.__class__ \
...            and self.firstname == other.firstname \
...            and self.lastname == other.lastname
>>>
>>>
>>> class Admin:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>>
>>> user = User('Mark', 'Watney')
>>> admin = Admin('Mark', 'Watney')
>>>
>>> user == admin
False
>>> user is admin
False

3.17.21. Use Case - 0x05

>>> 
... from functools import singledispatchmethod
...
...
... class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     @singledispatchmethod
...     def __eq__(self, other):
...         return False
...
...     @__eq__.register
...     def _(self, other: 'User'):
...         return self.firstname == other.firstname \
...            and self.lastname == other.lastname
...
...     @__eq__.register
...     def _(self, other: 'Admin'):
...         return False
...
...
... class Admin:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...
... user = User('Mark', 'Watney')
... admin = Admin('Mark', 'Watney')
...
... user == admin
False
>>> user is admin  
False