Author aspin2
Recipients aspin2
Date 2021-01-12.23:31:13
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1610494273.49.0.733516574302.issue42915@roundup.psfhosted.org>
In-reply-to
Content
Here's a code sample:

```
import time
from enum import Flag, auto


class MyFlag(Flag):
    NONE = 0
    FLAG_1 = auto()
    FLAG_2 = auto()
    FLAG_3 = auto()
    FLAG_4 = auto()
    FLAG_5 = auto()
    FLAG_6 = auto()
    #
    # NOT_FLAG_1_OR_2 = ~FLAG_1 & ~FLAG_2


def test_flag():
    f = MyFlag.NONE
    inverted = (
        ~MyFlag.FLAG_1
        & ~MyFlag.FLAG_2
        & ~MyFlag.FLAG_3
        & ~MyFlag.FLAG_4
        & ~MyFlag.FLAG_5
        & ~MyFlag.FLAG_6
    )
    return f & inverted


INVERTED = (
    ~MyFlag.FLAG_1
    & ~MyFlag.FLAG_2
    & ~MyFlag.FLAG_3
    & ~MyFlag.FLAG_4
    & ~MyFlag.FLAG_5
    & ~MyFlag.FLAG_6
)


def test_flag_cached():
    f = MyFlag.NONE
    return f & INVERTED


if __name__ == "__main__":
    start_time = time.time()
    for _ in range(10_000):
        test_flag()

    elapsed = time.time() - start_time
    print(f"Took normal {elapsed:2f} seconds.")

    start_time = time.time()
    for _ in range(10_000):
        test_flag_cached()

    elapsed = time.time() - start_time
    print(f"Took cached {elapsed:2f} seconds.")
```

And its outputs:
```
Took normal 1.799731 seconds.
Took cached 0.009488 seconds.
```

Basically, bitwise negation is very very slow. From what I can tell, it seems that a lot of time is spent here computing powers of two. I've read elsewhere that flag values are cached, and it looks like negated Flag values can't be cached? This seems related to the second issue, which is that any negated Flag value being defined results in `RecursionError: maximum recursion depth exceeded` as it searches for a good name for Flag.

Obviously, the simple workaround is just to define a constant variable elsewhere with the negated value, but it isn't very obvious anywhere that this is necessary, and I wanted to raise this to see if anyone has knowledge of the implementation details of Flag for possibly resolving this in the class itself.
History
Date User Action Args
2021-01-12 23:31:13aspin2setrecipients: + aspin2
2021-01-12 23:31:13aspin2setmessageid: <1610494273.49.0.733516574302.issue42915@roundup.psfhosted.org>
2021-01-12 23:31:13aspin2linkissue42915 messages
2021-01-12 23:31:13aspin2create