My end goal is to try an alternative way to make type equality tests at runtime by checking an ancestor list of all the classnames. This does require that I own all the classes I want to typecheck this way and that's ok. The way I'm calling super
here isn't quite right, but maybe there's a better way to create this list.
This would allow me to replace my existing
isinstance(x, Child)
checks with Child.__name__ in x.typetags()
class HasTypeTags():
@classmethod
def typetags(cls):
try:
return cls._typetags
except:
cls._typetags = [cls.__name__]
for base in cls.__bases__:
cls._typetags.append(base.__name__)
try:
cls._typetags += super(cls, cls).typetags()
except:
pass
return cls._typetags
class Root(HasTypeTags, object):
pass
class Child(Root):
pass
class GrandChild(Child):
pass
grandchild = GrandChild()
print(grandchild.typetags())
# should output something like ['GrandChild', 'Child', 'Root', 'HasTypeTags', 'object']
# but actually prints ['GrandChild', 'Child', 'GrandChild', 'Child']