Skip to content
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

enum.Flag ignores bitwise operator methods from mixins #121291

Open
gswifort opened this issue Jul 2, 2024 · 2 comments
Open

enum.Flag ignores bitwise operator methods from mixins #121291

gswifort opened this issue Jul 2, 2024 · 2 comments
Assignees

Comments

@gswifort
Copy link

gswifort commented Jul 2, 2024

When I define methods ('__or__', '__and__', '__xor__', '__ror__', '__rand__', '__rxor__', '__invert__')
directly in the class inheriting from enum.Flag, these methods are "added" (mro) to the members, however, if the method is defined in the mixin, the methods defined in enum.Flag are added (e.g. Flag.__or__). I would expect methods to be called from mixin.

from enum import Flag


class Mixin:
    def __or__(self, value): ...


class MyFlag(Mixin, Flag):
    pass


class MyFlag2(Flag):
    def __or__(self, value): ...


print(MyFlag.__or__.__qualname__)  # Flag.__or__, I would expect Mixin.__or__
print(MyFlag2.__or__.__qualname__)  # MyFlag2.__or__ - GOOD

cpython/Lib/enum.py

Lines 610 to 619 in 0898354

if Flag is not None and issubclass(enum_class, Flag):
for name in (
'__or__', '__and__', '__xor__',
'__ror__', '__rand__', '__rxor__',
'__invert__'
):
if name not in classdict:
enum_method = getattr(Flag, name)
setattr(enum_class, name, enum_method)
classdict[name] = enum_method

@ethanfurman ethanfurman self-assigned this Jul 2, 2024
@pygeek
Copy link
Contributor

pygeek commented Jul 3, 2024

super().__or__()

@gswifort
Copy link
Author

gswifort commented Jul 3, 2024

super().__or__()

Yes, it is a workaround, but I use mixins so as not to add the method in all derived classes. It's easier to add them in __init_subclass__:

class Mixin:

    def __or__(self, value): ...

    def __init_subclass__(cls) -> None:
        setattr(cls, "__or__", Mixin.__or__)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants