In Python, you can create types dynamically using the function my_type = type(name, bases, dict). How would you specify a metaclass for this type my_type? (Ideally other than defining a throwaway class object that simply binds the metaclass to instantiated subclasses)
For Dynamic Type Creation where you need to provide keywords in the class statement (including, but not limited to, the keyword "metaclass"), you would use types.new_class. The following class definition:
class A(B, C, metaclass=AMeta):
pass
Can be created dynamically like:
A = types.new_class(
name="A",
bases=(B, C),
kwds={"metaclass": AMeta},
exec_body=None,
)
This is preferable to directly calling type, or any other metaclass, since it resolves the metaclass bases - depending on the types of B and C, the type(A) here might not necessarily be AMeta.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With