Python 3.6 has added Flag and IntFlag which support the usual bit-wise operations. As a bonus, the resulting values from the bit-wise operations are still members of the original flag class, and are singletons [1].

The aenum library also has this addition and is usable back to Python 2.7.

[1] A bug exists in 3.6.0: if the pseudo-flag members are being created in threads then there is no guarantee that you won't end up with duplicates; this is fixed in 3.6.1 (and never existed in aenum).

Answer from Ethan Furman on Stack Overflow
🌐
Python
docs.python.org › 3 › library › enum.html
enum — Support for enumerations
February 23, 2026 - Modify the str() and repr() of an enum to show its members as belonging to the module instead of its class, and export the enum members to the global namespace. ... Return a list of all power-of-two integers contained in a flag.
🌐
Python documentation
docs.python.org › 3 › howto › enum.html
Enum HOWTO — Python 3.14.3 documentation
The default for Flag is STRICT, the default for IntFlag is EJECT, and the default for _convert_ is KEEP (see ssl.Options for an example of when KEEP is needed). Enums have a custom metaclass that affects many aspects of both derived Enum classes and their instances (members).
Discussions

Automatically adding composite values to a Flag enum
The short version is that I have a Flag where every member (save one) should have a corresponding composite member of its value ORed with a special nonmember flag. Example: from enum import Flag, auto, nonmember # new in 3.11 class Planet(Flag): _BIZARRO = nonmember(1) # flag to denote other ... More on discuss.python.org
🌐 discuss.python.org
0
0
September 3, 2023
enum: Add Flags and IntFlags
BPO 23591 Nosy @warsaw, @rhettinger, @ezio-melotti, @bitdancer, @ethanfurman, @serhiy-storchaka, @MojoVampire, @vedgar Files intflags.patchintflags_2.patchintflags_3.patchissue23591.stoneleaf.02.pa... More on github.com
🌐 github.com
80
March 5, 2015
python - Representation of all values in Flag enum - Stack Overflow
I would like to have a "ALL" flag in my python Flags enum for which myenum.EVERY_MEMBER & myenum.ALL == myenum.EVERY_MEMBER holds true. I currently have: from enum import Flag, auto class More on stackoverflow.com
🌐 stackoverflow.com
Using an Enum as a flag in a class, Python - Stack Overflow
I would like to use an enum to represent an internal state of a class: #!/usr/bin/python3 from enum import Enum class testClass: class Color(Enum): red = 1 blue = 2 gre... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 3
61

Python 3.6 has added Flag and IntFlag which support the usual bit-wise operations. As a bonus, the resulting values from the bit-wise operations are still members of the original flag class, and are singletons [1].

The aenum library also has this addition and is usable back to Python 2.7.

[1] A bug exists in 3.6.0: if the pseudo-flag members are being created in threads then there is no guarantee that you won't end up with duplicates; this is fixed in 3.6.1 (and never existed in aenum).

2 of 3
24

I've recently published an opensource package py-flags that aims this problem. That library has exactly this functionality and its design is heavily influenced by the python3 enum module.

There are debates about whether it is pythonic enough to implement such a flags class because its functionality has huge overlaps with other methods provided by the language (collection of bool variables, sets, objects with bool attributes or dicts with bool items, ...). For this reason I feel a flags class to be too narrow purpose and/or redundant to make its way to the standard library but in some cases it is much better than the previously listed solutions so having a "pip install"-able library can come in handy.

Your example would look like the following using the py-flags module:

from flags import Flags

class NetlistKind(Flags):
    Unknown = 0
    LatticeNetlist = 1
    QuartusNetlist = 2
    XSTNetlist = 4
    CoreGenNetlist = 8
    All = 15

The above things could be tweaked a bit further because a flags class declared with the library automatically provides two "virtual" flags: NetlistKind.no_flags and NetlistKind.all_flags. These make the already declared NetlistKind.Unknown and NetlistKind.All redundant so we could leave them out from the declaration but the problem is that no_flags and all_flags don't match your naming convention. To aid this we declare a flags base class in your project instead of flags.Flags and you will have to use that in the rest of your project:

from flags import Flags

class BaseFlags(Flags):
    __no_flags_name__ = 'Unknown'
    __all_flags_name__ = 'All'

Based on the previously declared base class that can be subclassed by any of your flags in your project we could change your flag declaration to:

class NetlistKind(BaseFlags):
    LatticeNetlist = 1
    QuartusNetlist = 2
    XSTNetlist = 4
    CoreGenNetlist = 8

This way NetlistKind.Unknown is automatically declared with a value of zero. NetlistKind.All is also there and it is automatically the combination of all of your declared flags. It is possible to iterate enum members with/without these virtual flags. You can also declare aliases (flags that have the same value as another previously declared flag).

As an alternative declaration using the "function-call style" (also provided by the standard enum module):

NetlistKind = BaseFlags('NetlistKind', ['LatticeNetlist', 'QuartusNetlist',
                                        'XSTNetlist', 'CoreGenNetlist'])

If a flags class declares some members then it is considered to be final. Trying to subclass it will result in error. It is semantically undesired to allow subclassing a flag class for the purpose of adding new members or change functionality.

Besides this the flags class provides the operators your listed (bool operators, in, iteration, etc...) in a type-safe way. I'm going to finish the README.rst along with a little plumbing on the package interface in the next few days but the basic functionality is already there and tested with quite good coverage.

🌐
Python.org
discuss.python.org › python help
Automatically adding composite values to a Flag enum - Python Help - Discussions on Python.org
September 3, 2023 - Example: from enum import Flag, auto, nonmember # new in 3.11 class Planet(Flag): _BIZARRO = nonmember(1) # flag to denote other version SUN = 0 # no bizarro version MERCURY = 2 # need to start with 2 to avoid _BIZARRO VENUS = auto() # auto ...
🌐
YouTube
youtube.com › nsf unidata
MetPy Mondays #284 - Enums with Flags in Python - YouTube
In this episode, we dive deeper into the Python enum and explore their applications in meteorological analysis. Enums provide a convenient way to define and ...
Published   May 16, 2023
Views   433
🌐
Johnlekberg
johnlekberg.com › blog › 2020-06-06-enum.html
Using enumerated types in Python
Z80 = enum.Flag("Z80", ["Carry", "Subtract", "Parity", "Zero"]) IntZ80 = enum.IntFlag("IntZ80", ["Carry", "Subtract", "Parity", "Zero"]) Z80.Carry | 2 · TypeError: unsupported operand type(s) for |: 'Z80' and 'int' ... Enum and IntEnum represent states that can't be combined.
🌐
Real Python
realpython.com › python-enum
Build Enumerations of Constants With Python's Enum – Real Python
December 15, 2024 - Just like members of IntFlag enums, the members of Flag enums should have values that are powers of two. Again, this doesn’t apply to combinations of flags, like Role.ADMIN in the example above. Python’s enumerations can help you improve your code’s readability and organization.
🌐
AbyxDev's Blog
blog.abyx.dev › entries › 2022-06-23-enums-and-set-theory
Python Enum Flags and Basic Set Theory - AbyxDev's Blog
Because of this, flag instances support the complement, in addition to other set operations: >>> class U(Flag): ... """Definition of the universe""" ... def __repr__(self) -> str: ... """Hide the unimportant numeric enum value.""" ...
Find elsewhere
🌐
GitHub
github.com › python › cpython › issues › 67779
enum: Add Flags and IntFlags · Issue #67779 · python/cpython
March 5, 2015 - assignee = 'https://github.com/ethanfurman' closed_at = <Date 2016-11-21.16:31:14.558> created_at = <Date 2015-03-05.15:31:23.274> labels = ['type-feature', 'library'] title = 'enum: Add Flags and IntFlags' updated_at = <Date 2016-11-21.16:31:14.556> user = 'https://github.com/serhiy-storchaka' bugs.python.org fields: activity = <Date 2016-11-21.16:31:14.556> actor = 'python-dev' assignee = 'ethan.furman' closed = True closed_date = <Date 2016-11-21.16:31:14.558> closer = 'python-dev' components = ['Library (Lib)'] creation = <Date 2015-03-05.15:31:23.274> creator = 'serhiy.storchaka' dependen
Author   serhiy-storchaka
🌐
Python
docs.python.org › 3.7 › library › enum.html
enum — Support for enumerations — Python 3.7.17 documentation
June 28, 2023 - The last variation is Flag. Like IntFlag, Flag members can be combined using the bitwise operators (&, |, ^, ~). Unlike IntFlag, they cannot be combined with, nor compared against, any other Flag enumeration, nor int.
🌐
ZetCode
zetcode.com › python › enum
Python enum - working with enumerations in Python
In the example, we use the __members__ property. The enumeration members are created with a list of tuples using functional API. $ python main.py SPRING Season.SPRING SUMMER Season.SUMMER AUTUMN Season.AUTUMN WINTER Season.WINTER · The enum.Flag is a base class for creating enumerated constants that can be combined using the bitwise operations without losing their Flag membership.
Top answer
1 of 5
12

There are a few ways to overcome this issue:

  • use a classproperty (see Zero's answer)

  • use a class decorator (see MSeifert's answer)

  • use a mixin (currently buggy)

  • create a new base class (see below)


One thing to be aware of with the class property method is since the descriptor is defined on the class and not the metaclass the usual protections against setting and deleting are absent -- in other words:

>>> RefreshFlags.ALL
<RefreshFlags.DEFENSES|BUILDINGS|RESOURCES|EVENTS: 15>

>>> RefreshFlags.ALL = 'oops'
>>> RefreshFlags.ALL
'oops'

Creating a new base class:

# lightly tested
from enum import Flag, auto
from operator import or_ as _or_
from functools import reduce

class AllFlag(Flag):

    @classproperty
    def ALL(cls):
        cls_name = cls.__name__
        if not len(cls):
            raise AttributeError('empty %s does not have an ALL value' % cls_name)
        value = cls(reduce(_or_, cls))
        cls._member_map_['ALL'] = value
        return value

And in use:

class RefreshFlag(AllFlag):
    EVENTS = auto()
    RESOURCES = auto()
    BUILDINGS = auto()
    DEFENSES = auto()

>>> RefreshFlag.ALL
<RefreshFlag.DEFENSES|BUILDINGS|RESOURCES|EVENTS: 15>

The interesting difference in the ALL property is the setting of the name in _member_map_ -- this allows the same protections afforded to Enum members:

>>> RefreshFlag.ALL = 9
Traceback (most recent call last):
  ....
AttributeError: Cannot reassign members.

However, there is a race condition here: if RefreshFlag.ALL = ... occurs before RefreshFlag.ALL is activated the first time then it is clobbered; for this reason I would use a decorator in this instance, as the decorator will process the Enum before it can be clobbered.

# lightly tested

from enum import Flag, auto
from operator import or_ as _or_
from functools import reduce

def with_limits(enumeration):
    "add NONE and ALL psuedo-members to enumeration"
    none_mbr = enumeration(0)
    all_mbr = enumeration(reduce(_or_, enumeration))
    enumeration.NONE = none_mbr
    enumeration.ALL = all_mbr
    enumeration._member_map_['NONE'] = none_mbr
    enumeration._member_map_['ALL'] = all_mbr
    return enumeration

And in use:

@with_limits
class RefreshFlag(Flag):
    EVENTS = auto()
    RESOURCES = auto()
    BUILDINGS = auto()
    DEFENSES = auto()

>>> RefreshFlag.ALL = 99
Traceback (most recent call last):
  ...
AttributeError: Cannot reassign members.

>>> RefreshFlag.ALL 
<RefreshFlag.DEFENSES|BUILDINGS|RESOURCES|EVENTS: 15>

>>> RefreshFlag.NONE
<RefreshFlag.0: 0>
2 of 5
6

TL;DR Because property is only evaluated on instances of a class while the __members__ is only accessible on the class.


If you access a property on a class it just returns a property:

>>> RefreshFlags.ALL
<property at 0x2a5d93382c8>

To make this work however you need to either make it a classmethod:

from enum import Flag, auto

class RefreshFlags(Flag):
    NONE = 0
    EVENTS = auto()
    RESOURCES = auto()
    BUILDINGS = auto()
    DEFENSES = auto()

    @classmethod
    def ALL(cls):
        retval = self.NONE
        for member in cls.__members__.values():
            retval |= member
        return retval

>>> RefreshFlags.ALL()
<RefreshFlags.DEFENSES|BUILDINGS|RESOURCES|EVENTS: 15>

or access the property on an instance:

from enum import Flag, auto

class RefreshFlags(Flag):
    NONE = 0
    EVENTS = auto()
    RESOURCES = auto()
    BUILDINGS = auto()
    DEFENSES = auto()

    @property
    def ALL(self):
        retval = self.NONE
        # One needs to access .__class__ here!
        for member in self.__class__.__members__.values():
            retval |= member
        return retval

>>> RefreshFlags.EVENTS.ALL
<RefreshFlags.DEFENSES|BUILDINGS|RESOURCES|EVENTS: 15>

In both cases you can do your comparison later:

>>> RefreshFlags.EVENTS & RefreshFlags.EVENTS.ALL
<RefreshFlags.EVENTS: 1>

You stated in the comments that you want the ALL member to behave like the others, in that case I suggest using a class decorator:

def with_ALL_member(enumeration):
    retval = enumeration(0)  # in case NONE is not defined
    for name, member in enumeration.__members__.items():
        retval |= member
    enumeration.ALL = retval
    return enumeration

@with_ALL_member
class RefreshFlags(Flag):
    NONE = 0
    EVENTS = auto()
    RESOURCES = auto()
    BUILDINGS = auto()
    DEFENSES = auto()

>>> RefreshFlags.EVENTS & RefreshFlags.ALL
<RefreshFlags.EVENTS: 1>

>>> RefreshFlags.DEFENSES & RefreshFlags.ALL
<RefreshFlags.DEFENSES: 8>

The class decorator can also be used on other enums :)

🌐
Readthedocs
pradyunsg-cpython-lutra-testing.readthedocs.io › en › latest › library › enum.html
enum — Support for enumerations - Python 3.12.0a0 documentation
IntFlag is the same as Flag, but its members are also integers and can be used anywhere that an integer can be used. >>> from enum import IntFlag, auto >>> class Color(IntFlag): ... RED = auto() ... GREEN = auto() ...
🌐
Zenva
gamedevacademy.org › home › python › a guide to using the python enum
A Guide To Using The Python Enum - GameDev Academy
January 22, 2024 - Each month (i.e. enum member) is assigned a unique numeric constant. from enum import Enum, unique, Flag class Months(Enum) : JANUARY=1 FEBRUARY=2 MARCH = 3 APRIL=4 MAY=5 JUNE=6 JULY=7 AUGUST=8 SEPTEMBER=9 OCTOBER=10 NOVEMBER=11 DECEMBER=12
🌐
Python
docs.python.org › 3.11 › › howto › enum.html
Enum HOWTO — Python 3.11.14 documentation
March 14, 2019 - The default for Flag is STRICT, the default for IntFlag is EJECT, and the default for _convert_ is KEEP (see ssl.Options for an example of when KEEP is needed). Enums have a custom metaclass that affects many aspects of both derived Enum classes and their instances (members).
🌐
Qt
doc.qt.io › qtforpython-6 › developer › enumfeatures_doc.html
The Set of Enum Features - Qt for Python
It is unlikely that errors are hidden for global enums, because they should already produce an error during import. But for cases without access to the source code, you can help yourself with this flag. A flag value of 0x6 is likely to solve the majority of problems. The following flags complement the description of Python Enums.
🌐
GitHub
github.com › pasztorpisti › py-flags
GitHub - pasztorpisti/py-flags: Type-safe (bit)flags for python 3
To auto-assign a unique flag value use an empty iterable (for example empty tuple or list) as the value of the flag. Auto-assignment picks the first unused least significant bit for each auto-assignable flag in top-to-bottom order. >>> class TextStyle(Flags): >>> bold = () # value = 1 << 0 >>> italic = () # value = 1 << 1 >>> underline = () # value = 1 << 2 · As a shortcut you can call a flags class to create a subclass of it. This pattern has also been stolen from the standard enum module.
Starred by 36 users
Forked by 5 users
Languages   Python 100.0% | Python 100.0%
🌐
7-Zip Documentation
documentation.help › Python-3.6.8 › enum.html
8.13. enum — Support for enumerations - Python 3.6.8 Documentation
The last variation is Flag. Like IntFlag, Flag members can be combined using the bitwise operators (&, |, ^, ~). Unlike IntFlag, they cannot be combined with, nor compared against, any other Flag enumeration, nor int.
🌐
University of New Brunswick
cs.unb.ca › ~bremner › teaching › cs2613 › books › python3-doc › library › enum.html
enum — Support for enumerations — Python 3.9.2 documentation
The last variation is Flag. Like IntFlag, Flag members can be combined using the bitwise operators (&, |, ^, ~). Unlike IntFlag, they cannot be combined with, nor compared against, any other Flag enumeration, nor int.