Shouldn't __metaclass__ force the use of a metaclass in Python? Shouldn't __metaclass__ force the use of a metaclass in Python? python-3.x python-3.x

Shouldn't __metaclass__ force the use of a metaclass in Python?


In Python 3 (which you are using) metaclasses are specified by a keyword parameter in the class definition:

class ClassMeta(metaclass=M):  pass

Specifying a __metaclass__ class property or global variable is old syntax from Python 2.x and not longer supported. See also "What's new in Python 3" and PEP 2115.


This works as you expect in Python 2.6 (and earlier), but in 3.0 metaclasses are specified differently:

class ArgMeta(metaclass=M): ...


The syntax of metaclasses has changed in Python 3.0. The __metaclass__ attribute is no longer special at either the class nor the module level. To do what you're trying to do, you need to specify metaclass as a keyword argument to the class statement:

p = printclass M(type):    def __init__(*args):        type.__init__(*args)        print("The rain in Spain")p(1)class ClassMeta(metaclass=M): pass

Yields:

1The rain in Spain

As you'd expect.