Skip to content

Inconsistent behaviour of Enums which are also strings in/before 3.10 #135370

Closed as not planned
@zahlman

Description

@zahlman

Bug report

Bug description:

In 3.10, since StrEnum is not yet provided, I thought to emulate it by simply using str as a mixin:

>>> from enum import Enum
>>> class x(str, Enum):
...     KEY = 'value'
... 

The result seems mostly correct, but there is an inconsistency between various ways of converting the instance to an ordinary string:

>>> isinstance(x.KEY, str)
True
>>> '%s' % x.KEY
'x.KEY'
>>> f'{x.KEY}'
'value'
>>> '{}'.format(x.KEY)
'value'
>>> str(x.KEY)
'x.KEY'

Compare in 3.11, which is consistent when using this mixin approach:

>>> from enum import Enum
>>> class x(str, Enum):
...     KEY = 'value'
... 
>>> isinstance(x.KEY, str)
True
>>> '%s' % x.KEY
'x.KEY'
>>> f'{x.KEY}'
'x.KEY'
>>> '{}'.format(x.KEY)
'x.KEY'
>>> str(x.KEY)
'x.KEY'

And consistent the other way when using the new StrEnum:

>>> from enum import StrEnum
>>> class x(StrEnum):
...     KEY = 'value'
... 
>>> isinstance(x.KEY, str)
True
>>> '%s' % x.KEY
'value'
>>> f'{x.KEY}'
'value'
>>> '{}'.format(x.KEY)
'value'
>>> str(x.KEY)
'value'

I don't have a firm opinion on which is correct, but I don't think it should depend on the conversion method.

CPython versions tested on:

3.10

Operating systems tested on:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions