You’re the Expert!

pynfinity

Build mountain with each pebble 🧗

Topics | Stepping Stones

📚 Guides

🌍 Pebbles & Contributions

✍️ Write a Post
🐼 Pandas DataFrames
🐼 Pandas DataFrames
🔢 NumPy Arrays
🔢 NumPy Arrays
📉 Matplotlib Plotting
📉 Matplotlib Plotting
🔥 Seaborn Heatmaps
🔥 Seaborn Heatmaps
🤖 Scikit-Learn Linear Regression
🤖 Scikit-Learn Linear Regression
🧹 Data Cleaning with Dropna
🧹 Data Cleaning with Dropna
🔍 Exploratory Data Analysis (EDA)
🔍 Exploratory Data Analysis (EDA)
⏳ Time Series Resampling
⏳ Time Series Resampling
🕸️ Web Scraping with BeautifulSoup
🕸️ Web Scraping with BeautifulSoup
🗄️ SQLAlchemy Basics
🗄️ SQLAlchemy Basics
📊 Interactive Plots with Plotly
📊 Interactive Plots with Plotly
📝 NLTK Tokenization
📝 NLTK Tokenization
🧠 TensorFlow Basics
🧠 TensorFlow Basics
🔥 PyTorch Tensors
🔥 PyTorch Tensors
📉 Statsmodels OLS
📉 Statsmodels OLS
📸 OpenCV Image Reading
📸 OpenCV Image Reading
🕸️ NetworkX Graphs
🕸️ NetworkX Graphs
🗺️ Folium Maps
🗺️ Folium Maps
🚀 Streamlit Apps
🚀 Streamlit Apps
⚡ FastAPI Endpoints
⚡ FastAPI Endpoints
✨ Jupyter Magic Commands
✨ Jupyter Magic Commands
📦 Virtual Environments
📦 Virtual Environments
🌲 Git Basics
🌲 Git Basics
🐳 Dockerfiles
🐳 Dockerfiles
☁️ AWS S3 with Boto3
☁️ AWS S3 with Boto3
🧩 Regular Expressions
🧩 Regular Expressions
λ Lambda Functions
λ Lambda Functions
📜 List Comprehensions
📜 List Comprehensions
⚡ Generators
⚡ Generators
🎀 Decorators
🎀 Decorators
🚪 Context Managers
🚪 Context Managers
🧵 Multithreading
🧵 Multithreading
🎛️ Multiprocessing
🎛️ Multiprocessing
⏳ AsyncIO
⏳ AsyncIO
🏷️ Type Hinting
🏷️ Type Hinting
📦 Dataclasses
📦 Dataclasses
🛡️ Pydantic Models
🛡️ Pydantic Models
🧪 Pytest Testing
🧪 Pytest Testing
🪵 Logging
🪵 Logging
💻 Argparse CLI
💻 Argparse CLI
📄 JSON Handling
📄 JSON Handling
📊 CSV Processing
📊 CSV Processing
🥒 Pickle Serialization
🥒 Pickle Serialization
🖥️ OS Module
🖥️ OS Module
⚙️ Sys Module
⚙️ Sys Module
📚 Collections Module
📚 Collections Module
🔁 Itertools
🔁 Itertools
🛠️ Functools
🛠️ Functools
➗ Math Module
➗ Math Module
+ New Post

🏗 Metaclasses in Python

Metaclasses are the "classes of classes". They define how a class behaves. A class is an instance of a metaclass.


🧠 What is a Metaclass?

In Python, everything is an object, including classes.
- x is an instance of MyClass.
- MyClass is an instance of type.
- type is the default metaclass.

class MyClass:
    pass

print(type(MyClass))  # <class 'type'>

🛠 Creating a Custom Metaclass

To create a custom metaclass, inherit from type. You typically override __new__ or __init__.

  • __new__: Creates the class object (allocates memory).
  • __init__: Initializes the class object.
class Meta(type):
    def __new__(cls, name, bases, dct):
        print(f"Creating class {name}")
        x = super().__new__(cls, name, bases, dct)
        x.attr = 100
        return x

class MyClass(metaclass=Meta):
    pass

# Output: Creating class MyClass
print(MyClass.attr)  # 100

🛡 Use Case: Validation

You can use metaclasses to enforce rules on your classes, like ensuring certain methods are defined or attributes follow a naming convention.

class InterfaceMeta(type):
    def __new__(cls, name, bases, dct):
        if 'required_method' not in dct:
            raise TypeError(f"Class {name} must implement 'required_method'")
        return super().__new__(cls, name, bases, dct)

# class BadClass(metaclass=InterfaceMeta):
#     pass
# Raises TypeError: Class BadClass must implement 'required_method'

class GoodClass(metaclass=InterfaceMeta):
    def required_method(self):
        pass

🧩 Use Case: Automatic Registration

Metaclasses can automatically register classes in a central registry, useful for plugins or routing.

registry = {}

class RegisterMeta(type):
    def __new__(cls, name, bases, dct):
        new_cls = super().__new__(cls, name, bases, dct)
        registry[name] = new_cls
        return new_cls

class Base(metaclass=RegisterMeta): pass
class A(Base): pass
class B(Base): pass

print(registry)
# {'Base': <class '__main__.Base'>, 'A': <class '__main__.A'>, 'B': <class '__main__.B'>}

📝 Summary

  • Classes are Objects: They are instances of a metaclass (default is type).
  • Custom Metaclasses: Inherit from type and define __new__.
  • Power: Can intercept class creation, modify attributes, and enforce constraints.
  • Caution: "Metaclasses are deeper magic than 99% of users should ever worry about." - Tim Peters

Created with ❤️ by Pynfinity