-
-
Notifications
You must be signed in to change notification settings - Fork 32.1k
IntEnum __format__ behavior can't be overridden through __str__ #81660
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Combining int and Enum, as with enum.IntEnum results in a class where __str__ cannot be effectively overridden. For example: from enum import IntEnum
class myIntEnum(IntEnum):
x = 1
def __str__(self):
return 'aaaaAAAa'
f'{myIntEnum.x}, {str(myIntEnum.x)}' Expected output: Actual output: Overriding __str__ in this way works as expected if the inherited classes are int or Enum individually. However, it does not work when inheriting (int, Enum) or when inheriting (intEnum). Presumably this is a side effect of Enum's mixin behavior documented at https://docs.python.org/3/library/enum.html#others and it is possibly related to https://bugs.python.org/issue18264 . |
I mistyped - __str__ can be overridden effectively, but __format__ has to be overridden instead or overridden also to get the desired f-string behavior. |
related cPython code: Line 626 in 19a1e1e
If we're in a mixed-in class but the class has overridden __str__(), we should probably use str(self) instead of self._value_. |
Note that this isn't really related to f-strings, except that they use the __format__ protocol, as does str.__format__. >>> format(myIntEnum.x)
'1' |
Thank you, Jason! |
Was this change really intended? The change will make projects break in their behavior when changed from 3.7 to a newer version. from enum import IntEnum
class Test(IntEnum):
A = 0
B = 0
t = Test.A
print(f"0x{t:X} {str(t)}") is valid python code and also compatible with python 3.7. from enum import IntEnum
class Test(IntEnum):
A = 0
B = 0
def __str__(self):
return self.name.lower()
t = Test.A
print(f"0x{t:X} {str(t)}") is valid in python 3.7 but due to the change not valid in python 3.8+ anymore. The str function exists in both cases, the override of the second case shall not alter the behavior of the class ! |
@zinnjonas This has been corrected in 3.11. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: