Last active
July 5, 2022 06:35
-
-
Save judy2k/64e319ed9a599427c6557aaf60a9df1a to your computer and use it in GitHub Desktop.
__qualname__ implementation in Python 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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