Il caso di StrEnum in Python 3.11

Dec 21 2022
Con l'aggiornamento a Python 3.11, ci siamo imbattuti in un sottile cambiamento nel comportamento di Enum.
Invece di un serpente, perché non un'immagine della luna?

Con l'aggiornamento a Python 3.11, ci siamo imbattuti in un sottile cambiamento nel comportamento di Enum. Questo grazie a PEP 663 — Standardizzazione dei comportamenti Enum str(), repr() e format() .

Prima di Python 3.11

Prima di Python 3.11, una stringa enum come mostrato di seguito restituisce il valore di una voce nell'enumerazione quando viene utilizzata tramite format o una stringa f ma non quando si chiama implicitamente __str__().

# Python 3.10

from enum import Enum

class Foo(str, Enum):
    BAR = "bar"

x = Foo.BAR

x               # Outputs <Foo.BAR: 'bar'>
f"{x}"          # Outputs 'bar'
"{}".format(x)  # Outputs 'bar'
str(x)          # Outputs 'Foo.BAR'
x.value         # Outputs 'bar'Python 3.11

# Python 3.11

from enum import Enum

class Foo(str, Enum):
    BAR = "bar"

x = Foo.BAR

x               # Outputs <Foo.BAR: 'bar'>
f"{x}"          # Outputs 'Foo.BAR'
"{}".format(x)  # Outputs 'Foo.BAR'
str(x)          # Outputs 'Foo.BAR'
x.value         # Outputs 'bar'

In Python 3.11, StrEnum è stato aggiunto alla libreria standard. Usarlo invece dello stile di enum summenzionato rende il comportamento più ovvio.

# Python 3.11

from enum import StrEnum, auto

class Foo(StrEnum):
    BAR = auto()

x = Foo.BAR

x               # Outputs <Foo.BAR: 'bar'>
f"{x}"          # Outputs 'bar'
"{}".format(x)  # Outputs 'bar'
str(x)          # Outputs 'bar'
x.value         # Outputs 'bar'