· Hakan Çelik · Python / Metaclass · 2 dk okuma

Invisible Metaclasses In Python

Every class in Python has a metaclass. If you don't specify one explicitly, type steps in as the default — invisible, but always there.

Invisible Metaclasses In Python

Every class in Python has a metaclass. If you don’t specify one explicitly, Python uses the type metaclass by default. This means the following two class definitions are completely equivalent:

class K(metaclass=type):
    pass

class Example(K, metaclass=type):
    pass

In the code above, metaclass=type is written explicitly. But you get the same result without writing it:

class K:
    pass

class Example(K):
    pass

What Does This Mean?

type sits at the very top of the metaclass hierarchy in Python. When you define a class, Python does the following behind the scenes:

>>> type(K)
<class 'type'>

>>> type(Example)
<class 'type'>

In both approaches the class’s type is type, because when no metaclass is specified Python automatically brings type into play. This is the “invisible metaclass” behavior — you don’t see it, but it is always there.

Inheritance and Metaclass

When a class inherits from another, the parent class’s metaclass is also inherited. In the Example(K) example, since K’s metaclass is type, Example’s metaclass is also type. When you define a custom metaclass this behavior changes:

class Meta(type):
    pass

class K(metaclass=Meta):
    pass

class Example(K):  # Meta is inherited, not type
    pass

>>> type(Example)
<class '__main__.Meta'>

Why Does This Matter?

The type metaclass remains invisible in most situations; however, understanding this default behavior is critically important when you are writing your own metaclass or examining a library’s metaclass. Not specifying a metaclass does not mean “no metaclass” — it simply means type is quietly doing its job.

Back to Blog

Related Posts

View All Posts »
Understanding Python Classes

Understanding Python Classes

Python · 2 dk

In Python, everything is an object and every object has a type — including primitives, functions, and classes themselves. type() and __class__ reveal this relationship.

Run Methods Order In Python

Run Methods Order In Python

Python · 2 dk

Which method runs when in Python metaclasses? The execution order of __prepare__, __new__, __init__, and __call__ during class definition and instance creation.