DeveloperBreeze

Tutorials Programming Tutorials, Guides & Best Practices

Explore 149+ expertly crafted tutorials tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Mastering Metaclasses and Dynamic Class Creation in 2024

Tutorial December 10, 2024
python

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

class Base(metaclass=InterfaceMeta):
    def execute(self):
        pass  # Required method

class Derived(Base):
    def execute(self):
        print("Executing Derived")

Derived().execute()  # Works fine

# Uncommenting the following will raise an error:
# class InvalidDerived(Base):
#     pass

Automatically register all subclasses using a metaclass.