python - Why is issubclass(dict, collections.Mapping) true in CPython? -
in cpython following
import collections issubclass(dict, collections.mapping)
returns true
. confuses me bit, since dict
builtin class defined in ctypes , collections module explicitly relies on existence of dict
accomplish of functionality. other straightforward inheritance checks must going on , can't figure out why works. below provide of reasoning leads confusion.
if @ inheritance structure of collections.mapping
see inherits collection
. collection
's signature shows inherits sized
, iterable
, container
of inherit metaclass abcmeta
.
but dict
builtin, thought meant being defined directly ctype thought meant wouldn't inheriting anything.
so, why issubclass(dict, collections.mapping)
→ true
?
for more context why came see this nbformat issue, in in attempting recreate signature & functionality of dict
's update
need know how issubclass(foo, mapping)
behave.
that's because metaclasses can customize issubclass
, isinstance
return. in case of mutablemapping
done via abc.abcmeta
, allows register "virtual subclasses".
for example:
from collections import mutablemapping class a(object): pass mutablemapping.register(a) issubclass(a, mutablemapping) # true
it works subclasses of registered subclasses:
class b(object): pass class c(b): pass mutablemapping.register(b) issubclass(c, mutablemapping) # true
the same happens dict
. though it's not real subclass of mutablemapping
it's still virtual subclass. second example shows means "real" subclasses of dict
"virtual" subclasses of mutablemapping
.
note simpler abcs implement subclass checks based on presence of methods. example collections.sized
checks if class has __len__
:
from collections import sized class d(object): def __len__(self): return 1 issubclass(d, sized) # true
so without explicit register
d
recognized valid subclass of sized
.
Comments
Post a Comment