Following this answer it seems that a class' metaclass may be changed after the class has been defined by using the following*:
class MyMetaClass(type):
# Metaclass magic...
class A(object):
pass
A = MyMetaClass(A.__name__, A.__bases__, dict(A.__dict__))
Defining a function
def metaclass_wrapper(cls):
return MyMetaClass(cls.__name__, cls.__bases__, dict(cls.__dict__))
allows me to apply a decorator to a class definition like so,
@metaclass_wrapper
class B(object):
pass
It seems that the metaclass magic is applied to B
, however B
has no __metaclass__
attribute. Is the above method a sensible way to apply metaclasses to class definitions, even though I am definiting and re-definiting a class, or would I be better off simply writing
class B(object):
__metaclass__ = MyMetaClass
pass
I presume there are some differences between the two methods.
*Note, the original answer in the linked question, MyMetaClass(A.__name__, A.__bases__, A.__dict__)
, returns a TypeError
:
TypeError: type() argument 3 must be a dict, not dict_proxy
It seems that the __dict__
attribute of A
(the class definition) has a type dict_proxy
, whereas the type of the __dict__
attribute of an instance of A
has a type dict
. Why is this? Is this a Python 2.x vs. 3.x difference?