|
| 1 | +__doc__ = """In Python we can use meta-programming to create classes and functions dynamically. |
| 2 | +By default, Python uses `type` metaclass to create classes. |
| 3 | +It can be changed by specifying `metaclass` keyword argument in the class definition. |
| 4 | +
|
| 5 | +Usually metaclass is derived from `type` metaclass, but technically it's not necessary. |
| 6 | +Metaclass must provide `__call__` method, which is called when the class is instantiated. |
| 7 | +On this place can be any callable, e.g. function, class, lambda, etc. |
| 8 | +
|
| 9 | +Method `__prepare__` is called before `__new__` and `__init__` |
| 10 | +It must return a mapping object that will be used as a namespace for the class. |
| 11 | +
|
| 12 | +Useful metaclasses: |
| 13 | +* `abc.ABCMeta` - abstract base classes |
| 14 | +* Iterable - `collections.abc.Iterable` throws an exception if `__iter__` is not implemented |
| 15 | +""" |
| 16 | + |
| 17 | +import abc |
| 18 | + |
| 19 | + |
| 20 | +class Base: |
| 21 | + pass |
| 22 | + |
| 23 | + |
| 24 | +# noinspection PyUnresolvedReferences |
| 25 | +class UseMetaLambda(Base, var=92, metaclass=lambda *args, **kwargs: print(f"meta({args}, {kwargs})")): |
| 26 | + """ |
| 27 | + Pass lambda object as a metaclass |
| 28 | + It's enough as it's just another callable |
| 29 | + It prints: class name, base classes, keyword arguments, etc. |
| 30 | + """ |
| 31 | + |
| 32 | + def __init__(self, a, b): |
| 33 | + self.a = a |
| 34 | + self.b = b |
| 35 | + |
| 36 | + def print_me(self): |
| 37 | + print(f"a == {self.a}, b == {self.b}") |
| 38 | + |
| 39 | + |
| 40 | +# Don't create instance of this class, it won't work |
| 41 | +# print() as a metaclass is not a good idea, because it returns None |
| 42 | +# However class declaration itself is enough to call metaclass |
| 43 | + |
| 44 | + |
| 45 | +# noinspection PyUnresolvedReferences |
| 46 | +class Meta(type): |
| 47 | + """ |
| 48 | + Typical metaclass implementing `__call__`, `__new__` and `__prepare__` methods |
| 49 | + """ |
| 50 | + |
| 51 | + def __new__(mcs, name, bases, namespace, **kwargs): |
| 52 | + """ |
| 53 | + :param mcs: metaclass |
| 54 | + :param name: name of the class |
| 55 | + :param bases: base classes |
| 56 | + :param namespace: namespace of the class |
| 57 | + :param kwargs: keyword arguments |
| 58 | + :return: new instance of the class |
| 59 | + """ |
| 60 | + print(f"Meta.__new__({mcs}, {name}, {bases}, {namespace}, {kwargs})") |
| 61 | + return super().__new__(mcs, name, bases, namespace) |
| 62 | + |
| 63 | + def __init__(cls, name, bases, namespace, **kwargs): |
| 64 | + """ |
| 65 | + `__init__` can be compared to "decorator" of metaclass, because |
| 66 | + it's called after the class is created, but before it's returned as a result |
| 67 | + in order to modify the behavior |
| 68 | + :param cls: class |
| 69 | + :param name: name of the class |
| 70 | + :param bases: base classes |
| 71 | + :param namespace: namespace of the class |
| 72 | + :param kwargs: keyword arguments |
| 73 | + """ |
| 74 | + print(f"Meta.__init__({cls}, {name}, {bases}, {namespace}, {kwargs})") |
| 75 | + super().__init__(name, bases, namespace) |
| 76 | + |
| 77 | + @classmethod |
| 78 | + def __prepare__(mcs, name, bases, **kwargs): |
| 79 | + """ |
| 80 | + Before Python 3.7. it specified the namespace of the class as an OrderedDict. |
| 81 | + After 3.7 dict is ordered by default, so it's not necessary anymore. |
| 82 | + :param mcs: metaclass |
| 83 | + :param name: name of the class |
| 84 | + :param bases: base classes |
| 85 | + :param kwargs: keyword arguments |
| 86 | + :return: mapping object that will be used as a namespace for the class |
| 87 | + """ |
| 88 | + print(f"Meta.__prepare__({mcs}, {name}, {bases}, {kwargs})") |
| 89 | + return super().__prepare__(name, bases) |
| 90 | + |
| 91 | + def __call__(cls, *args, **kwargs): |
| 92 | + """ |
| 93 | + :param cls: class |
| 94 | + :param args: arguments to be passed to the constructor of the class |
| 95 | + :param kwargs: keyword arguments to be passed to the constructor of the class |
| 96 | + :return: instance of the class |
| 97 | + """ |
| 98 | + print(f"Meta.__call__({cls}, {args}, {kwargs})") |
| 99 | + obj = cls.__new__(cls, *args, **kwargs) |
| 100 | + |
| 101 | + |
| 102 | +# noinspection PyUnresolvedReferences |
| 103 | +class Iterable(metaclass=abc.ABCMeta): |
| 104 | + """ |
| 105 | + Metaclass is used to check that the class implements `__iter__` method |
| 106 | + You also can check method signature using `inspect.signature` module |
| 107 | + """ |
| 108 | + @abc.abstractmethod |
| 109 | + def __iter__(self): |
| 110 | + raise NotImplementedError() |
0 commit comments