Programmer's Python - Metaclass
Written by Mike James   
Wednesday, 13 August 2025
Article Index
Programmer's Python - Metaclass
Implicit Calls
An Example – Final Classes

An Example – Final Classes

Many 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: " +
b.__name__) return type.__new__(self, name, base, ns)

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

  • Meta Attributes and Methods
  • Abstract Base Class
  • How Classes become Functions
  • Singleton Revisited
  • Class As Decorators
  • Decorating Classes
  • Class Decorators With Parameters
  • Singleton As Decorator

Summary 

  • A class is an object that creates instances.
  • A metaclass is an object that creates classes.
  • The base metaclass is type.
  • type can also be used as a function to dynamically create classes.
  • A metaclass has to inherit from type.
  • A metaclass goes through the usual stages of calling __new__ to create an instance of the class and __init__ to initialize it.
  • A metaclass also has __prepare__, which can supply a data structure suitable for storing the namespace.
  • Metaclasses can be used for many things, but they are mostly sophisticated. Typical uses are implementing a final class and a singleton.
  • The metaclass __call__ is used to convert a class object into a callable. You can override this to control how the class constructs an instance.
  • As a class is a callable it can be used as a decorator with its behavior set by its metaclass’s __call__.
  • As a class is a callable it can also be decorated by either a class or a function.
  • There are many cases where the job of a metaclass can be taken on by a decorator.


Programmer's Python
Everything is an Object
Second Edition

Is now available as a print book: Amazon

pythonObject2e360

Contents

  1. Get Ready For The Python Difference
  2. Variables, Objects and Attributes
  3. The Function Object
  4. Scope, Lifetime and Closure
      Extract 1: Local and Global 
  5. Advanced Functions
  6. Decorators
  7. Class, Methods and Constructors
      Extract 1: Objects Become Classes 
  8. Inside Class 
  9. Meeting Metaclasses
      Extract 1: Metaclass ***NEW!
  10. Advanced Attributes
  11. Custom Attribute Access
  12. Single Inheritance
  13. Multiple Inheritance
  14. Class and Type
  15. Type Annotation
  16. Operator Overloading
  17. Python In Visual Studio Code

 Extracts from the first edition

<ASIN:1871962749>

<ASIN:1871962595>

<ASIN:1871962765>

Related Articles

Creating The Python UI With Tkinter

Creating The Python UI With Tkinter - The Canvas Widget

The Python Dictionary

Arrays in Python

Advanced Python Arrays - Introducing NumPy

pico book

 

Comments




or email your comment to: comments@i-programmer.info

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner



Last Updated ( Wednesday, 13 August 2025 )