Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of `__metaclass__ = type`?

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?

like image 886
Mechanical snail Avatar asked Sep 01 '13 02:09

Mechanical snail


People also ask

What is the purpose of metaclass?

In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances. Not all object-oriented programming languages support metaclasses.

What does metaclass mean in Python?

A metaclass is a class that creates other classes. By default, Python uses the type metaclass to create other classes. For example, the following defines a Person class: class Person: def __init__(self, name, age): self.name = name self.age = age. Code language: Python (python)

What does __ class __ mean in Python?

__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .

What is a metaclass in programming?

In object-oriented computer programming, a metaclass is one whose instances are also classes. For instance, in Python, the built-in class type is a metaclass: instances of class type are themselves a class of objects. The use of metaclasses is most prevalent in object-oriented languages.


1 Answers

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).

like image 131
Blckknght Avatar answered Sep 20 '22 15:09

Blckknght