Skip to content

Instantly share code, notes, and snippets.

@judy2k
Last active July 5, 2022 06:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save judy2k/64e319ed9a599427c6557aaf60a9df1a to your computer and use it in GitHub Desktop.
Save judy2k/64e319ed9a599427c6557aaf60a9df1a to your computer and use it in GitHub Desktop.
__qualname__ implementation in Python 2
from inspect import isclass
import __builtin__
# We're going to overwrite object, so we need to squirrel away the old one:
obj = object
# Metaclass, overriding the class' __getattribute__,
# so that __qualname__ can be generated and cached on access:
class QualnameMeta(type):
def __getattribute__(cls, name):
if name == '__qualname__' and '__qualname__' not in dir(cls):
result = cls.__name__
else:
result = obj.__getattribute__(cls, name)
if isclass(result) and '__qualname__' not in dir(result):
result.__qualname__ = '.'.join([cls.__qualname__, name])
return result
# OMG I'm swapping out object for my own implementation:
class object(object):
__metaclass__ = QualnameMeta
# Make it properly global:
__builtin__.object = object
import know_thyself
# Test implementation - only the top-level class needs to extend MagicQual:
class A(object):
class B(object):
class C(object):
pass
# Ensure it works
print A.__qualname__ # => A
print A.B.__qualname__ # => A.B
# Just make sure reassignment still works:
C = A.B.C
print C.__qualname__ # => A.B.C
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment