Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python tuple and enum

So I was trying to use enums in python and came upon the following error: When I was using enum as a tuple and giving it two values, I can't access only one value such as tuple[0]

class Rank(Enum):
    ACE = 1
    TWO = 2
    THREE = 3
    FOUR = 4
    FIVE = 5
    SIX = 6
    SEVEN = 7
    EIGHT = 8
    NINE = 9
    TEN = 10
    JACK = 11
    QUEEN = 12
    KING = 13, "King"

print (Rank.KING.value)

and the print is

(13, 'King')

How can I access only one value so I can print 13 or 'King'?

like image 817
Flametrav Avatar asked Feb 20 '19 18:02

Flametrav


People also ask

Is tuple same enum?

Enum and namedtuple in python as enum and struct in C. In other words, enum s are a way of aliasing values, while namedtuple is a way of encapsulating data by name. The two are not really interchangeable, and you can use enum s as the named values in a namedtuple .

Why enum is used in Python?

Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over. An enum has the following characteristics.

What is Auto () in Python?

auto() method, we can get the assigned integer value automatically by just using enum. auto() method. Syntax : enum.auto() Automatically assign the integer value to the values of enum class attributes.


2 Answers

With enum.Enum, the class variable names themselves become the name attribute of the enumerated attributes of the Enum instance, so you don't have to make KING a tuple of value and name:

class Rank(Enum):
    King = 13

print(Rank.King.name) # outputs 'King'
print(Rank.King.value) # outputs 13

If you want to name the class variables with capital letters but have their name values to be mixed-cased, which isn't what Enum is designed for, you would have to subclass Enum and override the name method yourself to customize the behavior:

from enum import Enum, DynamicClassAttribute

class MixedCaseEnum(Enum):
    @DynamicClassAttribute
    def name(self):
        return self._name_.title()

class Rank(MixedCaseEnum):
    KING = 13

print(Rank.KING.name) # outputs 'King'
print(Rank.KING.value) # outputs 13
like image 193
blhsing Avatar answered Sep 30 '22 21:09

blhsing


You have the following possibilites to access 13 or "king":

Rank.KING.value[0]
Rank.KING.value[1]
like image 35
NGB Avatar answered Sep 30 '22 21:09

NGB