type — Advanced Examples
Declares a type alias (3.12+)
type as metaclass
Understanding type as the default metaclass.
python
# Every class is an instance of type class MyClass: pass print(f"type(MyClass): {type(MyClass)}") print(f"type(type): {type(type)}") print(f"isinstance(MyClass, type): {isinstance(MyClass, type)}") # The class statement is syntactic sugar for type() # class Foo(Bar): x = 1 # is equivalent to: # Foo = type("Foo", (Bar,), {"x": 1}) # Custom metaclass inherits from type class Meta(type): def __new__(mcs, name, bases, namespace): cls = super().__new__(mcs, name, bases, namespace) cls.created_by = "Meta" return cls class Widget(metaclass=Meta): pass print(f"type(Widget): {type(Widget)}") print(f"Widget.created_by: {Widget.created_by}") print(f"isinstance(Widget, Meta): {isinstance(Widget, Meta)}")
type is the metaclass of all classes. 'class X: pass' is syntactic sugar for 'X = type("X", (), {})'. Custom metaclasses inherit from type to customize class creation.
Want to try these examples interactively?
Open Advanced Playground