Sobes.tech
Senior

What are metaclasses in Python?

sobes.tech AI

Answer from AI

A metaclass defines how classes are created. A class itself is an instance of its metaclass. type is the standard metaclass in Python.

Main properties of metaclasses:

  • They define the behavior of classes during creation.
  • They can intercept class creation, modifying or adding attributes and methods.
  • They enable implementing concepts like Singleton, ORM, or class registries.

Example of using a metaclass to add an attribute to all classes:

class MyMeta(type):
    def __new__(cls, name, bases, dct):
        # Called when creating a class
        dct['__custom_attribute__'] = 'This is a custom attribute'
        return super().__new__(cls, name, bases, dct)

class MyClass(metaclass=MyMeta):
    pass

# Checking for the attribute
# print(MyClass.__custom_attribute__) # Will output 'This is a custom attribute'

Comparison of class creation using class and type:

Creation method Syntax Usage example Flexibility
class class ClassName(BaseClasses): ... ```python
class MyClass:
pass``` | Limited, defined by `class` syntax |

| type | type(ClassName, BaseClasses, Attributes) | python MyClass = type('MyClass', (), {}) | High, allows dynamic class definition |

Implementation of Singleton using a metaclass:

class SingletonMeta(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

class Singleton(metaclass=SingletonMeta):
    pass

# Check that instances are the same
# s1 = Singleton()
# s2 = Singleton()
# print(s1 is s2) # Will output True

Incorrect or excessive use of metaclasses can complicate the code and make it harder to understand.