Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError on Python Enum when comma seperated [duplicate]

Tags:

python

Consider the following code. How does python interpret class RottenFruit when it is comma separated? Is this legal? If yes, what is the use case?

from enum import Enum
class Fruit(Enum):
     Apple = 4
     Orange = 5
     Pear = 6 
a = Fruit(5)

class RottenFruit(Enum):
     Apple = 4,
     Orange = 5,
     Pear = 6
print(Fruit(5))
print(RottenFruit(5))

output:

Fruit.Orange
Traceback (most recent call last):
  File "...\tests\sandbox.py", line 15, in <module>
    print(RottenFruit(5))
  File "...\AppData\Local\Programs\Python\Python36\lib\enum.py", line 291, in __call__
    return cls.__new__(cls, value)
  File "...\AppData\Local\Programs\Python\Python36\lib\enum.py", line 533, in __new__
    return cls._missing_(value)
  File "...\AppData\Local\Programs\Python\Python36\lib\enum.py", line 546, in _missing_
    raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 5 is not a valid RottenFruit
like image 584
goldcode Avatar asked Feb 09 '17 09:02

goldcode


People also ask

Can enum have two same values python?

Introduction to the enum aliases By definition, the enumeration member values are unique. However, you can create different member names with the same values.

What is enum Auto?

Syntax : enum.auto() Automatically assign the integer value to the values of enum class attributes. Example #1 : In this example we can see that by using enum. auto() method, we are able to assign the numerical values automatically to the class attributes by using this method.

Are enums iterable Python?

Like lists, tuples, or dictionaries, Python enumerations are also iterable. That's why you can use list() to turn an enumeration into a list of enumeration members.

Should enums be capitalized Python?

Because Enums are used to represent constants we recommend using UPPER_CASE names for enum members, and will be using that style in our examples.


1 Answers

Your second snippet is equivalent to this:

class RottenFruit(Enum):
     Apple = (4,)
     Orange = (5,)
     Pear = 6

In other words, Apple and Orange are each tuples of length one.

Let me add a quick explanation. You are running into the combination of two Python features here. One is that you can assign multiple things at once, like this:

 x = 7
 y = 8
 y, x = x, y  # Now x = 8 and y = 7
 q = [1, 2, 3, 4, 5]
 x, m, *r, y = q  # Even fancier: now x = 1, m = 2, r = [3, 4] and y = 5

The other is that parsing rules of Python always allow a trailing comma in a list; this is useful for having a list spanning multiple lines look a bit cleaner, and allows a one-element tuple to be defined with e.g. (1,). You have found a way to combine these rules in a way that's not really useful, but isn't worth preventing.

like image 200
Arthur Tacca Avatar answered Sep 23 '22 03:09

Arthur Tacca