Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, what is the object method of built-in id()?

In Python:

  • len(a) can be replaced by a.__len__()
  • str(a) or repr(a) can be replaced by a.__str__() or a.__repr__()
  • == is __eq__, + is __add__, etc.

Is there similar method to get the id(a) ? If not, is there any workaround to get an unique id of a python object without using id() ?


edit: additional question: if not ? is there any reason not to define a __id__() ?

like image 793
w00d Avatar asked Apr 22 '13 17:04

w00d


1 Answers

No, this behavior cannot be changed. id() is used to get "an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime" (source). No other special meaning is given to this integer (in CPython it is the address of the memory location where the object is stored, but this cannot be relied upon in portable Python).

Since there is no special meaning for the return value of id(), it makes no sense to allow you to return a different value instead.

Further, while you could guarantee that id() would return unique integers for your own objects, you could not possibly satisfy the global uniqueness constraint, since your object cannot possibly have knowledge of all other living objects. It would be possible (and likely) that one of your special values clashes with the identity of another object alive in the runtime. This would not be an acceptable scenario.

If you need a return value that has some special meaning then you should define a method where appropriate and return a useful value from it.

like image 95
cdhowie Avatar answered Sep 28 '22 08:09

cdhowie