Wrapper class mapping object to id fails despite type(id(object)) == int

25 Views Asked by At

Why isn't it possible to wrap an object id in a class derived from int? I have some code working on the id's of some class instances. I would like to differentiate between int as a numeric datatype and int as an object id in type hinting.

As far as I can see, the type of an object id is int:

>>> x = object()
>>> id(x)
140068343605104
>>> type(id(x))
<class 'int'>

So, why isn't it possible to do the following:

class ObjectID(int):
    def __init__(self, obj: object):
        super().__init__(id(obj))

def some_func(object_id: ObjectID):
    # Do something with object_id

class A:
    pass

x = ObjectID(A())

->

Traceback (most recent call last):
  File "/home/user/pycharm-2023.2/plugins/python/helpers/pydev/pydevconsole.py", line 364, in runcode
    coro = func()
  File "<input>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'A'

My ugly workaround is:

class ObjectID(int):
    pass


x = ObjectID(id(A()))

->

>>> x
140068324407856
0

There are 0 best solutions below