Python (2 only?) looks at the value of variable __metaclass__
to determine how to create a type
object from a class definition. It is possible to define __metaclass__
at the module or package level, in which case it applies to all subsequent class definitions in that module.
However, I encountered the following in the flufl.enum
package's __init__.py
:
__metaclass__ = type
Since the default metaclass if __metaclass__
is not defined is type
, wouldn't this have no effect? (This assignment would revert to the default if __metaclass__
were assigned to at a higher scope, but I see no such assignment.) What is its purpose?
In Python 2, a declaration __metaclass__ = type
makes declarations that would otherwise create old-style classes create new-style classes instead. Only old-style classes use a module level __metaclass__
declaration. New-style classes inherit their metaclass from their base class (e.g. object
), unless __metaclass__
is provided as a class variable.
The declaration is not actually used in the code you linked to above (there are no class declarations in the __init__.py
file), but it could be. I suspect it was included as part of some boilerplate that makes Python 2 code work more like Python 3 (where all classes are always new-style).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments