Returning Enum from function where enum has duplicate values

1.1k views Asked by At

I have a enumeration to represent different possible values of a function.

class A(Enum):
    NOT_FOUND = NONE
    INAQUATE = NONE
    POSITIVE = 1
    # Some more

However, when returning this enumeration from a function,

def search_function(target = 1):
    if target == 1:
        return A.INAQUATE
    else:
        return A.POSITIVE

returns A.NOT_FOUND, not A.INAQUATE which breaks the program down the line.

Python 3.7.6

>>> from enum import Enum
>>> class A(Enum):
...     NOT_FOUND = None
...     INAQUATE = None
...     POSITIVE = 1
... 
>>> def search_function(target = 1):
...     if target == 1:
...             return A.INAQUATE
...     return A.NOT_FOUND
... 
>>> search_function()
<A.NOT_FOUND: None>

Is there a way to properly return A.INAQUATE?

1

There are 1 answers

2
Ethan Furman On BEST ANSWER

When Enums have duplicate values, the members are the exact same object -- just referenced by both names in the Enum itself:

>>> list(A)
[<A.NOT_FOUND: None>, <A.POSITIVE: 1>]

>>> A.INAQUATE is A.NOT_FOUND
True

The easiest solution is give each member a unique value. The next easiest solution is to use the aenum library1:

from aenum import Enum, NoAlias

class A(Enum):
    #
    _settings_ = NoAlias
    #
    NOT_FOUND = None
    INAQUATE = None
    POSITIVE = 1

And in use:

>>> list(A)
[<A.INAQUATE: None>, <A.NOT_FOUND: None>, <A.POSITIVE: 1>]

>>> A.INAQUATE is A.NOT_FOUND
False

NB When using NoAlias enumerations the lookup-by-value functionality is lost:

>>> A(1)
Traceback (most recent call last):
  ...
TypeError: NoAlias enumerations cannot be looked up by value

1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.