Thom Smith
Thom Smith

Reputation: 14086

Turn a list of strings into an `IntFlag`

I have a bunch of IntFlag types, and I expect to frequently convert lists of strings from config files into members of those types. My current plan is to extend IntFlag:

class BetterIntFlag(IntFlag):
    @classmethod
    def parse(cls, items):
        value = cls(0)
        for item in items:
            value |= cls[item]
        return value

I'm satisfied with this solution, but I can't help but feel that I must be missing a concise built-in way to do this.

I'm on 3.3 with backported enums.

Upvotes: 3

Views: 937

Answers (1)

Ethan Furman
Ethan Furman

Reputation: 69288

If by backport you mean aenum1, it's built-in:

from aenum import IntFlag

class Color(IntFlag):
  red = 1
  green = 2
  blue = 4

and in use:

--> Color['red|blue']
<Color.blue|red: 5>

--> items = ['red', 'blue']
--> Color['|'.join(items)]
<Color.blue|red: 5>

1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

Upvotes: 1

Related Questions