Programmer's Python - Metaclass |
Written by Mike James | ||||
Wednesday, 13 August 2025 | ||||
Page 3 of 3
An Example – Final ClassesMany languages have the concept of a final class – one that cannot be inherited. Python does not have such a facility as any class can be inherited, but you can use a metaclass to make the equivalent of a final class. What is special about the metaclass mechanism is that it is the only Python construct that can come into effect before the class has been created. You can use decorators to modify a class after it has been created, but only a metaclass can intervene in the creation of a class. Even this doesn’t seem to be enough to stop a class being inherited as this is something that occurs after the class has been created, but it is not the original class that concerns us. When a class inherits from a class it also inherits the same metaclass and this means we can process it in the metaclass’s __new__. All we have to do is check that there isn’t a class in base that is an instance of the metaclass. This has to be done before the class is created: class Final(type): def __new__(self, name, base, ns): for b in base: if isinstance(b, Final): raise TypeError("Class isfinal: " + When you try: class A(metaclass=Final): pass and __new__ is called, the class is created because there isn’t anything in the base list. However, following this if you try: class B(A): pass then you will generate the exception because A is in base and it is an instance of Final. In short, if any class in the base list is marked as final by using the metaclass Final then the new class isn’t created. Notice that the fact that class B uses Final as its metaclass is essential to the way that this works as it is vital that Final is run as part of the class definition. Many Python programmers would not find this use of metaclasses idiomatic Python because the feeling is that classes should always be inheritable and the most you should do is put a polite warning in the form of comments if you don’t want a class used in that way. In chapter but not in this extract
Summary
Programmer's Python
|
||||
Last Updated ( Wednesday, 13 August 2025 ) |