Created
February 13, 2019 12:43
-
-
Save un-def/727bf08bd8338cec99996eceee7e9e61 to your computer and use it in GitHub Desktop.
metaclass decorator Python 2/3
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
from __future__ import print_function, unicode_literals | |
def metaclass(meta): | |
def metaclass_decorator(cls): | |
dct = cls.__dict__.copy() | |
slots = dct.get('__slots__') | |
if slots is not None: | |
if not isinstance(slots, (list, tuple)): | |
slots = [slots] | |
for slots_var in slots: | |
dct.pop(slots_var, None) | |
dct.pop('__dict__', None) | |
dct.pop('__weakref__', None) | |
if hasattr(cls, '__qualname__'): | |
dct['__qualname__'] = cls.__qualname__ | |
cls_with_meta = meta(cls.__name__, cls.__bases__, dct) | |
return cls_with_meta | |
return metaclass_decorator | |
class Meta(type): | |
def __new__(meta, name, bases, dct): | |
print(name, bases, dct) | |
return super(Meta, meta).__new__(meta, name, bases, dct) | |
@metaclass(Meta) | |
class Class(object): | |
__slots__ = 'foo' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment