Q:

Decompose a combined IntFlag into its individual flags

How can I get the individual flags from a combined IntFlag value in Python?
import enum

class Example(enum.IntFlag):
    A = 0b0001
    B = 0b0010
    C = 0b0100

combined = Example.A | Example.B

# How can I get the individual flags back?
flags = [flag for flag in combined]

A:

A list comprehension could work:
flags = [flag for flag in Example if flag in combined]

If the bits in your flag values overlap then the above will give you all the possible flags found in the combined value.
I didn't see a public API to do this in Python 3.7's standard library. The enum module does have a private _decompose function that is a more sophisticated version of the above, and is used in IntFlag's __repr__ method.

