pythonenums

Inheriting str and enum, why is the output different?


I have this python code. But why does it print "NEW" in the first case, and "Status.NEW" in the second case?

import enum

class Status(str, enum.Enum):
    """Status options."""
    NEW = "NEW"
    EXCLUDED = "EXCLUDED"
    
print("" + Status.NEW)
print(Status.NEW)

Solution

  • This is a quirk of multiple inheritance (one of the reasons why a lot of people choose to shun it).

    print("" + Status.NEW)
    

    Here you're using the + operator on your Status.NEW object. Since Status inherits from str, it inherits the __add__ method from there. str.__add__ does string concatenation and uses its raw string value.

    print(Status.NEW)
    

    Here there's no string concatenation, but print calls the __str__ method on any object you pass to it. Your Status.NEW object inherits its __str__ method from the Enum side of the family, so in that context it gets printed as an Enum value instead of a string.

    If you're in Python 3.11 or greater, you can do this:

    import enum
    
    class Status(enum.StrEnum):
        """Status options."""
        NEW = "NEW"
        EXCLUDED = "EXCLUDED"
        
    print("" + Status.NEW)
    print(Status.NEW)
    

    That avoids ambiguity about whether your objects are treated as Enums or strings. Otherwise, you just have to be careful.