Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decompose a combined IntFlag into its individual flags

Tags:

python

enums

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]
like image 605
sourcenouveau Avatar asked Sep 27 '19 14:09

sourcenouveau


1 Answers

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.

like image 135
sourcenouveau Avatar answered Nov 20 '22 11:11

sourcenouveau