What is the purpose of `__metaclass__ = type`?

Python (only 2?) Looks at the value of the __metaclass__ variable to determine how to create a type object from the class definition. You can define __metaclass__ at the module or package level , in which case it applies to all subsequent class definitions in this module.

However, I found the following in flufl.enum package __init__.py :

 __metaclass__ = type 

Since the default metaclass, if __metaclass__ not defined, type , will it have no effect? (This assignment will revert to default if __metaclass__ was assigned in a higher scope, but I do not see such an assignment.) What is its purpose?

+9
source share
3 answers

In Python 2, the __metaclass__ = type declaration makes declarations that would otherwise create old-style classes, instead create new-style classes. Only old-style classes use the __metaclass__ module-level declaration. New style classes inherit their metaclass from their base class (for example, object ) if __metaclass__ not provided as a class variable.

The declaration is not actually used in the code that you linked above (there are no class declarations in the __init__.py file), but it may be so. I suspect it was included as part of some template that makes Python 2 code more like Python 3 (where all classes are always new).

+11
source

Yes, it has no effect. This is probably just a misunderstanding from the author of flufl.enum or from the previous code.

The __metaclass__ super superpackage ’ __metaclass__ will have no effect because there is no such thing as Python superpackages.

0
source

I do not have enough reputation to add a comment, but for those who are interested, now you can find a link to an example:

https://bazaar.launchpad.net/~bloodaille/flufl.enum/trunk/view/head: / flufl / enum / init .py

0
source

Source: https://habr.com/ru/post/952908/


All Articles