Allen Huang
Allen Huang

Reputation: 105

enum class definition process

I am reading the enum source code, so

class Enum(metaclass=EnumMeta)

there's a __call__ and __new__ method in EnumMeta and a __new__ in Enum, my question is when we instantiate an Enum class, why the __call__ of the meta class is called, instead of the __new__ of the Enum?

Upvotes: 1

Views: 103

Answers (1)

Ethan Furman
Ethan Furman

Reputation: 69288

The __new__ in any class is used to create instances of that class. So:

class Buffer:
    def __new__(cls, size):
        instance = object.__new__(cls)
        instance.storage = bytearray(size)
        return instance

and in the REPL:

>>>> buffer = Buffer(32)
>>> buffer
<__main__.Buffer object at 0x7fb146867a60>

>>> type(buffer)
<class '__main__.Buffer'>

So if Buffer.__new__ is used to create an instance of Buffer, what is Buffer itself an instance of?

>>> type(Buffer)
<class 'type'>

Okay, Buffer is an instance of type -- so, just like Buffer.__new__ is used to create an instance of Buffer, type.__new__ is used to create an instance of type, which Buffer is.

Turning this back to Enum and EnumMeta: EnumMeta.__new__ is used to create instances of itself, which are Enum classes, and Enum.__new__ is used to create Enum instances, which are its members.

Part of the magic of Enum, and probably also part of the confusion, is that the members are instances of the class, even though they are listed in the body of the Enum class (usually such things are just attributes, like the storage used above in Buffer).

Upvotes: 2

Related Questions