Reputation: 1512
I asked this question in interpret an integer as enum flags but did not state the challenge as clearly as I should have. I am looking for how to take a pure integer, not an instance of a class based on Flags, and interpret the integer according to the definitions in the class.
Suppose I have a Flag enum like this:
From enum import Flag
class suspicion(Flag):
TOT_PCNT_LOW = 1
IND_PCNT_LOW = 2
IND_SCORE_LOW = 4
And suppose I have an integer that has bits set consistent with the definition, but is just an integer. It is ot an instance of the suspicion enumeration.
i == 3
How do I get a list of the names of the flags that correspond to the bits in the integer?
For example:
print(some_method(i)) # prints ["IND_PCNT_LOW", "TOT_PCNT_LOW"]
Upvotes: 3
Views: 1582
Reputation: 11431
you can instantiate a new suspicion
object with the value i
. python will join corresponding names with a |
symbol:
>>> i = 3
>>> suspicion(i)
<suspicion.TOT_PCNT_LOW|IND_PCNT_LOW: 3>
>>> suspicion(i).name
'TOT_PCNT_LOW|IND_PCNT_LOW'
>>> suspicion(i).name.split('|')
['TOT_PCNT_LOW', 'IND_PCNT_LOW']
Upvotes: 0
Reputation: 21275
You can iterate through the possible flags & evaluate if the corresponding bit is set. Use the enum value for the check. And then you can access the .name
attribute of the enum object to get the name associated with the value
Like so:
from enum import Flag
class suspicion(Flag):
TOT_PCNT_LOW = 1 # 001
IND_PCNT_LOW = 2 # 010
IND_SCORE_LOW = 4 # 100
i = 3 # 011
def flags_set(num):
return [sus.name for sus in suspicion if num & sus.value]
print(flags_set(i))
Prints:
['TOT_PCNT_LOW', 'IND_PCNT_LOW']
Upvotes: 3