0

Here is something odd that I came across while experimenting with the 'is' keyword. When I use Python built-ins to create identical objects, Python assigns the same id to them:

>>> a = str()
>>> b = str()
>>> id(a), id(b)
(29857888 29857888)
>>> a is b
True

Creating the string explicitly works the same way:

>>> a = ''
>>> b = ''
>>> id(a), id(b)
(29857888 29857888)
>>> a is b
True 

However, when I make my own classes, Python assigns different ids.

>>> class MyClass:
...    pass
>>> c = MyClass()
>>> d = MyClass()
>>> id(c), id(d)
(16566256 16566800)
>>> c is d
False

How/why does Python do this? Is there a way to implement this "id matching" functionality for my own classes?

Daniel Q
  • 137
  • 1
  • 2
  • 11
  • Small immutable objects may be cached, depending on the implementation. `c` and `d` are not the same object, so `c is d` is `False`. – timgeb Oct 21 '18 at 21:51
  • It's not about assigning IDs. Two objects alive at the same time never have the same ID. It's about *returning the same object*. – user2357112 Oct 21 '18 at 21:51
  • https://stackoverflow.com/questions/2519580/are-strings-pooled-in-python – xrisk Oct 21 '18 at 21:51
  • If you want to do this with your own class, check out [`__new__`](https://docs.python.org/3/reference/datamodel.html#object.__new__). – user2357112 Oct 21 '18 at 22:00

0 Answers0