Skip to content

Instantly share code, notes, and snippets.

@grantwwu
Created July 3, 2017 19:31
Show Gist options
  • Select an option

  • Save grantwwu/f600049c31dfcb30e6e60c98db50cd86 to your computer and use it in GitHub Desktop.

Select an option

Save grantwwu/f600049c31dfcb30e6e60c98db50cd86 to your computer and use it in GitHub Desktop.
Metaclasses are hard
class foo(type):
def __new__(cls, name, bases, attrs):
raise Exception(str(attrs))
class bar(metaclass=foo):
var = 3
var2 = 4
# ---------------------------------------------------------------------------
# Exception Traceback (most recent call last)
# <ipython-input-6-11169c2bbbc3> in <module>()
# ----> 1 class bar(metaclass=foo):
# 2 var = 3
# 3 var2 = 4
# 4
#
# <ipython-input-5-536e4a315e68> in __new__(cls, name, bases, attrs)
# 1 class foo(type):
# 2 def __new__(cls, name, bases, attrs):
# ----> 3 raise Exception(str(attrs))
# 4
# 5
#
# Exception: {'__module__': '__main__', '__qualname__': 'bar', 'var': 3, 'var2': 4}
class foo(type):
def __new__(cls, name, bases, attrs):
print(str(attrs))
class bar(foo):
var1 = 3
var2 = 4
# Does not print anything - why?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment