Why is IntEnum anyway if I use a tuple?

Noticed that someone wrote the listing as follows:

from enum import IntEnum

class Animal(IntEnum):
    dog = 1,
    cat = 2

And I thought it was a mistake that would lead to a runtime error because the value of the dog was actually a tuple. To my surprise, this works, and Animal.dog.value == 1.

It works:

class Potato(IntEnum):
    spud = ()

with an empty tuple that somehow converts to an integer (maybe the splatting argument to call int?).

This does not work:

class Potato(IntEnum):
    spud = []

We receive TypeError: int() argument must be a string or a number, not 'list'.

I see this on both python3 and enum34 backport on python 2.

How / why IntEnumor does its metaclass implicitly convert tuples to integers?

+4
source share
2 answers

enum.py, , . , , , (value,), . a IntEnum int(*args).

, :

  • int: int(10) = 10,
  • , int:
  • : int([...])
  • (string_value, base) ('1f', 16): 31!

    >>> class Animal(IntEnum):
        dog = '1F', 16
        cat = 5
    
    >>> Animal.dog.value
    31
    

, , ...

+3

__new__ __init__, __init__ __new__ . .

:

: __new__() / __init__(), , , . . Planet .

Planet:

__new__() __init__(), .

:

  • , 2 (2,)
  • Tuple , 1, () .

int.__new__ int.__new__(*args).

:

  • int(1,) - 1.
  • int(2,) - 2.
  • int() - 0.

, :

>>> class BasesOfTenEnum(IntEnum):
...     octal = '10', 8
...     decimal = '10', 10
...     hexadecimal = '10', 16
... 
>>> list(BasesOfTenEnum)
[<BasesOfTenEnum.octal: 8>, <BasesOfTenEnum.decimal: 10>, <BasesOfTenEnum.hexadecimal: 16>]

, , tuple Enum, , tuple.__new__ .

+1

All Articles