2

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?

vahvero
  • 525
  • 11
  • 24
  • 1
    Does this answer your question? [Python Enums with duplicate values](https://stackoverflow.com/questions/31537316/python-enums-with-duplicate-values) – Guy Mar 10 '20 at 11:28
  • Unfortunately it seems that it is unrelated as only the return value is my concern. I have overridden comparison operators and the only problem at the moment is the wrong return value from this function. – vahvero Mar 10 '20 at 11:39

1 Answers1

1

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.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • This is interesting. Any particular reason why standard enum has been implemented this way? – vahvero Mar 11 '20 at 10:21
  • Because `Enum` is meant to give a name to a value -- if you have more than one member assigned to the same value then some of the usefulness is lost. Oh, I forgot to mention: `NoAlias` enumerations can be looked up by value -- `A(1)` raises a `TypeError`. – Ethan Furman Mar 11 '20 at 17:06