Sprawa dla StrEnum w Pythonie 3.11
Dec 21 2022
Wraz z aktualizacją do Pythona 3.11 natknęliśmy się na subtelną zmianę w zachowaniu Enum.
Wraz z aktualizacją do Pythona 3.11 natknęliśmy się na subtelną zmianę w zachowaniu Enum. Dzieje się tak dzięki PEP 663 — Standaryzacja zachowań Enum str(), repr() i format() .
Przed Pythonem 3.11
Przed Pythonem 3.11 wyliczenie łańcucha, jak pokazano poniżej, zwracałoby wartość wpisu w wyliczeniu, gdy zostało użyte przez format lub f-string, ale nie w przypadku niejawnego wywołania __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'
W Pythonie 3.11 StrEnum zostało dodane do biblioteki standardowej. Używanie tego zamiast wspomnianego stylu wyliczeń zapewnia bardziej oczywiste zachowanie.
# 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'

![Czym w ogóle jest lista połączona? [Część 1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































