gh-150817: Speed up Flag bitwise operations#150824
Open
gaborbernat wants to merge 1 commit into
Open
Conversation
Flag.__or__, __and__ and __xor__ walked both operands on every call to reject None values. Run that scan only when one of the operand values is actually None, so valid combinations skip it. The TypeError and its message are unchanged for the invalid cases.
151ff22 to
b16e4e8
Compare
ethanfurman
approved these changes
Jun 3, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Combining
Flagmembers with|,&and^walks both operands on every call to check that neither carries aNonevalue, raising a clearTypeErrorwhen one does. That check only matters in the rare case where a value really isNone; for every normal combination of two valid flags it adds work to each operation. Flag arithmetic is hot wherever flags model option sets — theremodule's own flags are anIntFlag, so eachre.compile(pattern, re.I | re.M)combines them, and permission systems, feature toggles and styling layers do the same in tight loops.The two values the guard inspects are already in hand: one is the member's own value, the other is the operand value computed just above. This runs the scan over the operands only when one of those is actually
None, so a valid combination skips it entirely. The offending-flag walk, theTypeErrorand its message are unchanged for the invalid cases.Running flag combinations mined from the top-1000 corpus, including the
reflag sets, improves from 72.6 µs to 49.5 µs, 47% faster.Benchmark (pyperf)
Run base vs patched by swapping
Lib/enum.pyon the same interpreter. The flag combinations are realreflag sets mined from the top-1000 corpus.Resolves #150817.