As known, we cannot create weakref to __builtin__ object
in python.
import weakref
a = 1
awr = weakref.proxy(a) # TypeError: cannot create weak reference to 'int' object
a = (1, 2)
awr = weakref.proxy(a) # TypeError: cannot create weak reference to 'tuple' object
For that the field __weakrefoffset__
refers to availability of weakref, we can see something below:
class TupleInherit(tuple):
pass
class ListInherit(list):
pass
print 'TupleInherit.__weakrefoffset__', TupleInherit.__weakrefoffset__
print 'ListInherit.__weakrefoffset__', ListInherit.__weakrefoffset__
print 'tuple.__weakrefoffset__', tuple.__weakrefoffset__
print 'list.__weakrefoffset__', list.__weakrefoffset__
# OUTPUT:
# TupleInherit.__weakrefoffset__ 0
# ListInherit.__weakrefoffset__ 48
# tuple.__weakrefoffset__ 0
# list.__weakrefoffset__ 0
As above represented, list
, tuple
and tuple
inheritor doesn't provide availability of weakref, while list
inheritance provides. Result is shown below:
import weakref
a = TupleInherit()
awr = weakref.proxy(a) # TypeError: cannot create weak reference to 'TupleInherit' object
a = ListInherit()
awr = weakref.proxy(a) # OK
So, why? May the reason be that tuple is built by __new__
?
And what if we wanna create a tuple inheritor which support weakref?