> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Metaclass

A metaclass in Python is a class whose instances are classes. While a standard class defines the behavior and memory layout of its objects, a metaclass defines the behavior, structure, and instantiation process of the class itself. In Python's object model, everything is an object, including classes; therefore, every class must be instantiated by a metaclass. The default metaclass for all new-style classes is the built-in `type`.

## The `type` Metaclass

When the Python interpreter executes a `class` statement, it translates the class definition into a call to the `type` metaclass. The `type` constructor dynamically creates the class object using three arguments:

```python theme={"dark"}
type(name: str, bases: tuple, namespace: dict) -> type
```

* `name`: The string name of the class (becomes the `__name__` attribute).
* `bases`: A tuple of base classes for inheritance (becomes the `__bases__` attribute).
* `namespace`: A dictionary containing the class body, including methods and attributes. This dictionary is used to populate the class's namespace, but it is copied into a read-only `mappingproxy` object, which is what actually becomes the class's `__dict__` attribute. Modifying the original dictionary after class creation does not affect the class.

## Defining a Custom Metaclass

To create a custom metaclass, you inherit from `type` and override its dunder (magic) methods to intercept the class creation pipeline. The four primary methods involved in the metaclass lifecycle are:

### 1. `__prepare__`

Called before the class body is executed. It returns a dictionary-like object that acts as the local execution namespace for the class body. Any keyword arguments passed in the class definition are received here. Because the built-in `type.__prepare__` does not accept arbitrary keyword arguments, any custom keyword arguments must be stripped before calling `super().__prepare__`.

```python theme={"dark"}
class CustomMeta(type):
    @classmethod
    def __prepare__(metacls, name, bases, **kwargs):
        # kwargs are stripped by not passing them to super().__prepare__
        return super().__prepare__(name, bases)
```

### 2. `__new__`

Called to allocate memory and create the actual class object. This is the most frequently overridden method in a metaclass, as it allows modification of the class namespace, name, or bases before the class object is compiled into memory. Like `__prepare__`, `type.__new__` rejects arbitrary keyword arguments. Any custom keyword arguments passed to the class definition must be stripped before calling `super().__new__`.

```python theme={"dark"}
class CustomMeta(type):
    def __new__(mcs, name, bases, namespace, **kwargs):
        # Mutate name, bases, or namespace here
        # kwargs are stripped by not passing them to super().__new__
        cls = super().__new__(mcs, name, bases, namespace)
        return cls
```

### 3. `__init__`

Called after the class object is created by `__new__`. It is used to initialize the class object, similar to how a standard `__init__` initializes an instance. At this stage, the class object already exists. Similar to `__new__`, `type.__init__` does not accept arbitrary keyword arguments, so they must be omitted when calling `super().__init__`.

```python theme={"dark"}
class CustomMeta(type):
    def __init__(cls, name, bases, namespace, **kwargs):
        # kwargs are stripped by not passing them to super().__init__
        super().__init__(name, bases, namespace)
        # Initialize class-level state here
```

### 4. `__call__`

Called when the newly created class is instantiated (e.g., `obj = MyClass()`). Overriding this in a metaclass intercepts the creation of the class's instances, controlling exactly how and when the class's own `__new__` and `__init__` methods are invoked.

```python theme={"dark"}
class CustomMeta(type):
    def __call__(cls, *args, **kwargs):
        # Intercept instance creation
        instance = super().__call__(*args, **kwargs)
        return instance
```

## Applying a Metaclass

To assign a metaclass to a class, pass the `metaclass` keyword argument in the class definition signature. Any additional keyword arguments provided here will be passed to the metaclass's `__prepare__`, `__new__`, and `__init__` methods.

```python theme={"dark"}
class MyClass(metaclass=CustomMeta, custom_kwarg="value"):
    pass
```

## Metaclass Resolution Order

When a class inherits from multiple base classes, Python must determine the correct metaclass to use for the derived class. Python enforces a strict rule: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases.

If base classes possess different metaclasses that do not share a subclass relationship, the interpreter cannot resolve a single most-derived metaclass and will raise a `TypeError` (commonly known as a metaclass conflict).

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Python Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
