Last active
December 30, 2015 10:19
-
-
Save maedoc/7815086 to your computer and use it in GitHub Desktop.
Reminder of how Python metaclasses work
This file contains hidden or 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
| offset=[0] | |
| def log(f): | |
| def wrap(*args, **kwds): | |
| tab = '\t'*offset[0] | |
| print tab, f, args, kwds | |
| offset[0] += 1 | |
| ret = f(*args, **kwds) | |
| print tab, f, ' () -> ', ret | |
| offset[0] -= 1 | |
| return ret | |
| return wrap | |
| class Meta(type): | |
| @log | |
| def __new__(mcs, name, bases, dikt): | |
| return super(Meta, mcs).__new__(mcs, name, bases,dikt) | |
| @log | |
| def __init__(cls, name, bases, dikt): | |
| return super(Meta, cls).__init__(name, bases, dikt) | |
| @log | |
| def __call__(cls, *args, **kwds): | |
| return super(Meta, cls).__call__(*args, **kwds) | |
| print 'defining class' | |
| class Type(object): | |
| __metaclass__ = Meta | |
| @log | |
| def __new__(cls, *args, **kwds): | |
| return super(Type, cls).__new__(cls, *args, **kwds) | |
| @log | |
| def __init__(self, *args, **kwds): | |
| pass | |
| print 'creating instance' | |
| t = Type() | |
| """ | |
| Output of this is: | |
| defining class | |
| <function __new__ at 0x2740f50> (<class '__main__.Meta'>, 'Type', (<type 'object'>,), {'__module__': '__main__', '__metaclass__': <class '__main__.Meta'>, '__new__': <function wrap at 0x2743140>, '__init__': <function wrap at 0x27438c0>}) {} | |
| <function __new__ at 0x2740f50> () -> <class '__main__.Type'> | |
| <function __init__ at 0x27432a8> (<class '__main__.Type'>, 'Type', (<type 'object'>,), {'__module__': '__main__', '__metaclass__': <class '__main__.Meta'>, '__new__': <function wrap at 0x2743140>, '__init__': <function wrap at 0x27438c0>}) {} | |
| <function __init__ at 0x27432a8> () -> None | |
| creating instance | |
| <function __call__ at 0x2743230> (<class '__main__.Type'>,) {} | |
| <function __new__ at 0x27431b8> (<class '__main__.Type'>, <class '__main__.Type'>) {} | |
| <function __new__ at 0x27431b8> () -> <__main__.Type object at 0x2745590> | |
| <function __init__ at 0x2743050> (<__main__.Type object at 0x2745590>, <class '__main__.Type'>) {} | |
| <function __init__ at 0x2743050> () -> None | |
| <function __call__ at 0x2743230> () -> <__main__.Type object at 0x2745590> | |
| """ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment