Skip to content

enum.Flag with a flag set to None raises an exception #115539

@elicn

Description

@elicn

Bug report

Bug description:

The following code snippet defines a Flag class denoting an unsupported flag with None.

from enum import Flag

class TestFlag(Flag):
    O_NONE = 0
    O_ONE = 1
    O_TWO = 2
    O_FOUR = 4
    O_NOT_SUPPORTED = None

While working fine on earlier Python versions, this code raises an exception on Python 3.11 and 3.12 without even instantiating the class.

The snippet above on Python 3.9:

Python 3.9.13 (tags/v3.9.13:6de2ca5, May 17 2022, 16:36:42) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from enum import Flag
>>> class TestFlag(Flag):
...     O_NONE = 0
...     O_ONE = 1
...     O_TWO = 2
...     O_FOUR = 4
...     O_NOT_SUPPORTED = None
...
>>>

Same snippet on Python 3.12:

Python 3.12.2 (tags/v3.12.2:6abddd9, Feb  6 2024, 21:26:36) [MSC v.1937 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from enum import Flag
>>> class TestFlag(Flag):
...     O_NONE = 0
...     O_ONE = 1
...     O_TWO = 2
...     O_FOUR = 4
...     O_NOT_SUPPORTED = None
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.752.0_x64__qbz5n2kfra8p0\Lib\enum.py", line 593, in __new__
    raise exc.with_traceback(tb)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.752.0_x64__qbz5n2kfra8p0\Lib\enum.py", line 583, in __new__
    enum_class = super().__new__(metacls, cls, bases, classdict, **kwds)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.752.0_x64__qbz5n2kfra8p0\Lib\enum.py", line 286, in __set_name__
    enum_class._flag_mask_ |= value
TypeError: unsupported operand type(s) for |=: 'int' and 'NoneType'
>>>

Works on:

  • Python 3.8 (Windows and Linux)
  • Python 3.9 (Windows and Linux)

Fails on:

  • Python 3.11 (Windows, Linux not tested)
  • Python 3.12 (Windows and Linux)

CPython versions tested on:

3.8, 3.9, 3.11, 3.12

Operating systems tested on:

Linux, Windows

Linked PRs

Metadata

Metadata

Assignees

Labels

stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions