Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

specify metaclass for dynamic type

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)

like image 832
Michael Green Avatar asked Nov 02 '25 15:11

Michael Green


1 Answers

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.

like image 172
wim Avatar answered Nov 04 '25 07:11

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!