Enum Tools

Tools to expand Python’s enum module.

Docs

Documentation Build Status Docs Check Status

Tests

Linux Test Status Windows Test Status macOS Test Status Coverage

PyPI

PyPI - Package Version PyPI - Supported Python Versions PyPI - Supported Implementations PyPI - Wheel

Anaconda

Conda - Package Version Conda - Platform

Activity

GitHub last commit GitHub commits since tagged version Maintenance PyPI - Downloads

QA

CodeFactor Grade Flake8 Status mypy status

Other

License GitHub top language Requirements Status

This library provides the following:

  1. enum_tools.autoenum – A Sphinx extension to document Enums better than autoclass can currently.

  2. @enum_tools.documentation.document_enum – A decorator to add docstrings to Enum members from a comment at the end of the line.

  3. enum_tools.custom_enums – Additional Enum classes with different functionality.

Installation

python3 -m pip install enum_tools --user

Contents

enum_tools.autoenum – Sphinx Extension

A Sphinx directive for documenting Enums in Python.

Provides the autoenum directive for documenting Enums, and autoflag for documenting Flags. These behaves much like autoclass and autofunction.

Attention

This extension / module has the following additional requirements:

sphinx>=3.4.0
sphinx-jinja2-compat>=0.1.1
sphinx-toolbox>=2.16.0

These can be installed as follows:

python -m pip install enum-tools[sphinx]

Enable enum_tools.autoenum by adding the following to the extensions variable in your conf.py:

extensions = [
    ...
    'enum_tools.autoenum',
    ]

For more information see https://www.sphinx-doc.org/en/master/usage/extensions#third-party-extensions .

Usage

.. autoenum::
.. autoflag::

These directives are used for documenting Enums and Flags respectively.

They support the same options as autoclass, but with a few changes to the behaviour:

  • Enum members are always shown regardless of whether they are documented or not.

  • Enum members are grouped separately from methods.

The docstrings of the Enum members are taken from their __doc__ attributes. This can be set during initialisation of the enum (see an example here), with the DocumentedEnum class, or with the document_enum() decorator.

See the autodoc module documentation for further details of the general autoclass behaviour.

:py:enum:mem:
:py:enum:member:
:py:flag:mem:
:py:flag:member:

These roles provide cross-references to Enum/Flag members.

New in version 0.4.0.

Unlike a standard :class: or :enum: xref the default behaviour of the ~ prefix is to show both the Enum’s name and the member’s name. For example:

:py:enum:mem:`~enum_tools.demo.StatusFlags.Running`

StatusFlags.Running

The original behaviour can be restored by using the + prefix:

:py:enum:mem:`+enum_tools.demo.StatusFlags.Running`

Running

Demo

These two have been created with automodule.

.. automodule:: enum_tools.demo
    :members:
enum NoMethods(value)[source]

Bases: enum.IntEnum

An enumeration of people without any methods.

Member Type

int

Valid values are as follows:

Bob = <NoMethods.Bob: 1>

A person called Bob

Alice = <NoMethods.Alice: 2>

A person called Alice

Carol = <NoMethods.Carol: 3>

A person called Carol

enum People(value)[source]

Bases: enum.IntEnum

An enumeration of people.

Member Type

int

Valid values are as follows:

Bob = <People.Bob: 1>

A person called Bob

Alice = <People.Alice: 2>

A person called Alice

Carol = <People.Carol: 3>

A person called Carol.

This is a multiline docstring.

Dennis = <People.Dennis: 4>

A person called Dennis

The Enum and its members also have the following methods:

classmethod iter_values()[source]

Iterate over the values of the Enum.

classmethod as_list()[source]

Return the Enum’s members as a list.

Return type

List

This one has been created with autoenum.

.. autoenum:: enum_tools.demo.People
    :members:
enum People(value)[source]

Bases: enum.IntEnum

An enumeration of people.

Member Type

int

Valid values are as follows:

Bob = <People.Bob: 1>

A person called Bob

Alice = <People.Alice: 2>

A person called Alice

Carol = <People.Carol: 3>

A person called Carol.

This is a multiline docstring.

Dennis = <People.Dennis: 4>

A person called Dennis

The Enum and its members also have the following methods:

classmethod iter_values()[source]

Iterate over the values of the Enum.

classmethod as_list()[source]

Return the Enum’s members as a list.

Return type

List

If members don’t have their own docstrings no docstring is shown:

.. autoenum:: enum_tools.demo.NoMemberDoc
    :members:
enum NoMemberDoc(value)[source]

Bases: enum.IntEnum

An enumeration of people without any member docstrings.

Member Type

int

Valid values are as follows:

Bob = <NoMemberDoc.Bob: 1>
Alice = <NoMemberDoc.Alice: 2>
Carol = <NoMemberDoc.Carol: 3>

Flags can also be documented:

.. autoflag:: enum_tools.demo.StatusFlags
    :members:
flag StatusFlags(value)[source]

Bases: enum.IntFlag

An enumeration of status codes.

Member Type

int

Valid values are as follows:

Running = <StatusFlags.Running: 1>

The system is running.

Stopped = <StatusFlags.Stopped: 2>

The system has stopped.

Error = <StatusFlags.Error: 4>

An error has occurred.

The Flag and its members also have the following methods:

has_errored()[source]

Returns whether the operation has errored.

Return type

bool

API Reference

Classes:

EnumDocumenter(*args)

Sphinx autodoc Documenter for documenting Enums.

EnumMemberDocumenter(directive, name[, indent])

Sphinx autodoc Documenter for documenting Enum members.

FlagDocumenter(*args)

Sphinx autodoc Documenter for documenting Flags.

PyEnumXRefRole([fix_parens, lowercase, …])

XRefRole for Enum/Flag members.

Functions:

setup(app)

Setup Sphinx Extension.

class EnumDocumenter(*args)[source]

Bases: ClassDocumenter

Sphinx autodoc Documenter for documenting Enums.

Methods:

can_document_member(member, membername, …)

Called to see if a member can be documented by this documenter.

document_members([all_members])

Generate reST for member documentation.

generate([more_content, real_modname, …])

Generate reST for the object given by self.name, and possibly for its members.

classmethod can_document_member(member, membername, isattr, parent)[source]

Called to see if a member can be documented by this documenter.

Parameters
Return type

bool

document_members(all_members=False)[source]

Generate reST for member documentation.

Parameters

all_members (bool) – If True, document all members, otherwise document those given by self.options.members. Default False.

generate(more_content=None, real_modname=None, check_module=False, all_members=False)[source]

Generate reST for the object given by self.name, and possibly for its members.

Parameters
  • more_content (Optional[Any]) – Additional content to include in the reST output. Default None.

  • real_modname (Optional[str]) – Module name to use to find attribute documentation. Default None.

  • check_module (bool) – If True, only generate if the object is defined in the module name it is imported from. Default False.

  • all_members (bool) – If True, document all members. Default False.

class EnumMemberDocumenter(directive, name, indent='')[source]

Bases: AttributeDocumenter

Sphinx autodoc Documenter for documenting Enum members.

Methods:

add_directive_header(sig)

Add the directive header for the Enum member.

generate([more_content, real_modname, …])

Generate reST for the object given by self.name, and possibly for its members.

import_object([raiseerror])

Import the object given by self.modname and self.objpath and set it as self.object.

add_directive_header(sig)[source]

Add the directive header for the Enum member.

Parameters

sig (str)

generate(more_content=None, real_modname=None, check_module=False, all_members=False)[source]

Generate reST for the object given by self.name, and possibly for its members.

Parameters
  • more_content (Optional[Any]) – Additional content to include in the reST output. Default None.

  • real_modname (Optional[str]) – Module name to use to find attribute documentation. Default None.

  • check_module (bool) – If True, only generate if the object is defined in the module name it is imported from. Default False.

  • all_members (bool) – If True, document all members. Default False.

Changed in version 0.8.0: Multiline docstrings are now correctly represented in the generated output.

import_object(raiseerror=False)[source]

Import the object given by self.modname and self.objpath and set it as self.object.

Parameters

raiseerror (bool) – Default False.

Return type

bool

Returns

True if successful, False if an error occurred.

class FlagDocumenter(*args)[source]

Bases: EnumDocumenter

Sphinx autodoc Documenter for documenting Flags.

Methods:

can_document_member(member, membername, …)

Called to see if a member can be documented by this documenter.

classmethod can_document_member(member, membername, isattr, parent)[source]

Called to see if a member can be documented by this documenter.

Parameters
Return type

bool

class PyEnumXRefRole(fix_parens=False, lowercase=False, nodeclass=None, innernodeclass=None, warn_dangling=False)[source]

Bases: PyXRefRole

XRefRole for Enum/Flag members.

New in version 0.4.0.

Methods:

process_link(env, refnode, …)

Called after parsing title and target text, and creating the reference node (given in refnode).

Called after parsing title and target text, and creating the reference node (given in refnode).

This method can alter the reference node and must return a new (or the same) (title, target) tuple.

Parameters
Return type

Tuple[str, str]

setup(app)[source]

Setup Sphinx Extension.

Parameters

app (Sphinx)

Return type

Dict[str, Any]

enum_tools.custom_enums

Custom subclasses of enum.Enum and enum.Flag.

Classes:

AutoNumberEnum(value)

Enum that automatically assigns increasing values to members.

DuplicateFreeEnum(*args)

Enum that disallows duplicated member names.

IntEnum(value)

Enum where members are also (and must be) ints.

IterableFlag(value)

Flag with support for iterating over members and member combinations.

IterableIntFlag(value)

IntFlag with support for iterating over members and member combinations.

MemberDirEnum(value)

Enum which includes attributes as well as methods.

OrderedEnum(value)

Enum that adds ordering based on the values of its members.

StrEnum(value)

Enum where members are also (and must be) strings.

enum AutoNumberEnum(value)[source]

Bases: enum.Enum

Enum that automatically assigns increasing values to members.

enum DuplicateFreeEnum(value)[source]

Bases: enum.Enum

Enum that disallows duplicated member names.

enum IntEnum(value)[source]

Bases: int, enum.Enum

Enum where members are also (and must be) ints.

Member Type

int

flag IterableFlag(value)[source]

Bases: enum.Flag

Flag with support for iterating over members and member combinations.

This functionality was added to Python 3.10’s enum module in python/cpython#22221python/cpython#22221.

New in version 0.5.0.

The Flag and its members have the following methods:

__iter__()[source]

Returns members in definition order.

Return type

Iterator[Flag]

flag IterableIntFlag(value)[source]

Bases: enum.IntFlag

IntFlag with support for iterating over members and member combinations.

This functionality was added to Python 3.10’s enum module in python/cpython#22221python/cpython#22221.

New in version 0.5.0.

Member Type

int

The Flag and its members have the following methods:

__iter__()[source]

Returns members in definition order.

Return type

Iterator[IntFlag]

enum MemberDirEnum(value)[source]

Bases: enum.Enum

Enum which includes attributes as well as methods.

This will be part of the enum module starting with Python 3.10.

See also

Pull request python/cpython#19219python/cpython#19219 by Angelin BOOZ, which added this to CPython.

New in version 0.6.0.

enum OrderedEnum(value)[source]

Bases: enum.Enum

Enum that adds ordering based on the values of its members.

The Enum and its members have the following methods:

__ge__(other)[source]

Return self>=value.

Return type

bool

__gt__(other)[source]

Return self>value.

Return type

bool

__le__(other)[source]

Return self<=value.

Return type

bool

__lt__(other)[source]

Return self<value.

Return type

bool

enum StrEnum(value)[source]

Bases: str, enum.Enum

Enum where members are also (and must be) strings.

Member Type

str

enum_tools.documentation

Core Functionality

Decorators to add docstrings to enum members from comments.

Classes:

DocumentedEnum(value)

An enum where docstrings are automatically added to members from comments starting with doc:.

Functions:

document_enum(an_enum)

Document all members of an enum by parsing a docstring from the Python source..

document_member(enum_member)

Document a member of an enum by adding a comment to the end of the line that starts with doc:.

enum DocumentedEnum(value)[source]

Bases: enum.Enum

An enum where docstrings are automatically added to members from comments starting with doc:.

Note

This class does not (yet) support the other docstring formats @document_enum does.

@document_enum(an_enum)[source]

Document all members of an enum by parsing a docstring from the Python source..

The docstring can be added in several ways:

  1. A comment at the end the line, starting with doc::

    Running = 1  # doc: The system is running.
    
  2. A comment on the previous line, starting with #:. This is the format used by Sphinx.

    #: The system is running.
    Running = 1
    
  3. A string on the line after the attribute. This can be used for multiline docstrings.

    Running = 1
    """
    The system is running.
    
    Hello World
    """
    

If more than one docstring format is found for an enum member a MultipleDocstringsWarning is emitted.

Parameters

an_enum (enum.Enum) – An Enum subclass

Returns

The same object passed as an_enum. This allows this function to be used as a decorator.

Return type

enum.Enum

Changed in version 0.8.0: Added support for other docstring formats and multiline docstrings.

document_member(enum_member)[source]

Document a member of an enum by adding a comment to the end of the line that starts with doc:.

Parameters

enum_member (Enum) – A member of an Enum subclass

Utilities

Exceptions:

MultipleDocstringsWarning(member[, docstrings])

Warning emitted when multiple docstrings are found for a single Enum member.

Functions:

get_base_indent(base_indent, all_tokens, indent)

Determine the base level of indentation (i.e.

get_dedented_line(line)

Returns the line without indentation, and the amount of indentation.

get_tokens(line)

Returns a list ot tokens generated from the given Python code.

parse_tokens(all_tokens)

Parse the tokens representing a line of code to identify Enum members and doc: comments.

get_base_indent(base_indent, all_tokens, indent)[source]

Determine the base level of indentation (i.e. one level of indentation in from the c of class).

Parameters
  • base_indent (Optional[int]) – The current base level of indentation

  • all_tokens (Sequence[Sequence])

  • indent (int) – The current level of indentation

Return type

Optional[int]

Returns

The base level of indentation

get_dedented_line(line)[source]

Returns the line without indentation, and the amount of indentation.

Parameters

line (str) – A line of Python source code

Return type

Tuple[int, str]

get_tokens(line)[source]

Returns a list ot tokens generated from the given Python code.

Parameters

line (str) – Line of Python code to tokenise.

Return type

List[Tuple]

parse_tokens(all_tokens)[source]

Parse the tokens representing a line of code to identify Enum members and doc: comments.

Parameters

all_tokens

Returns

A list of the Enum members’ names, and the docstring for them.

Warnings

exception MultipleDocstringsWarning(member, docstrings=())[source]

Bases: UserWarning

Warning emitted when multiple docstrings are found for a single Enum member.

New in version 0.8.0.

Parameters
  • member (Enum)

  • docstrings (Iterable[str]) – The list of docstrings found for the member. Default ().

__str__()[source]

Return str(self).

Return type

str

docstrings

Type:    Iterable[str]

The list of docstrings found for the member.

member

Type:    Enum

The member with multiple docstrings.

enum_tools.utils

General utility functions.

Classes:

HasMRO

typing.Protocol for classes that have a method resolution order magic method (__mro__).

Functions:

get_base_object(enum)

Returns the object type of the enum’s members.

is_enum(obj)

Returns True if obj is an enum.Enum.

is_enum_member(obj)

Returns True if obj is an enum.Enum member.

is_flag(obj)

Returns True if obj is an enum.Flag.

protocol HasMRO[source]

Bases: Protocol

typing.Protocol for classes that have a method resolution order magic method (__mro__).

This protocol is runtime checkable.

Classes that implement this protocol must have the following methods / attributes:

__mro__ = (<class 'enum_tools.utils.HasMRO'>, <class 'typing_extensions.Protocol'>, <class 'typing.Generic'>, <class 'object'>)

Type:    tuple

__non_callable_proto_members__ = {'__mro__'}

Type:    set

get_base_object(enum)[source]

Returns the object type of the enum’s members.

If the members are of indeterminate type then the object class is returned.

Parameters

enum (Type[HasMRO])

Return type

Type

Raises

TypeError – If enum is not an Enum.

is_enum(obj)[source]

Returns True if obj is an enum.Enum.

Parameters

obj (Type)

Return type

bool

is_enum_member(obj)[source]

Returns True if obj is an enum.Enum member.

Parameters

obj (Type)

Return type

bool

is_flag(obj)[source]

Returns True if obj is an enum.Flag.

Parameters

obj (Type)

Return type

bool

Contributing

enum_tools uses tox to automate testing and packaging, and pre-commit to maintain code quality.

Install pre-commit with pip and install the git hook:

python -m pip install pre-commit
pre-commit install

Coding style

formate is used for code formatting.

It can be run manually via pre-commit:

pre-commit run formate -a

Or, to run the complete autoformatting suite:

pre-commit run -a

Automated tests

Tests are run with tox and pytest. To run tests for a specific Python version, such as Python 3.6:

tox -e py36

To run tests for all Python versions, simply run:

tox

Type Annotations

Type annotations are checked using mypy. Run mypy using tox:

tox -e mypy

Build documentation locally

The documentation is powered by Sphinx. A local copy of the documentation can be built with tox:

tox -e docs

Downloading source code

The enum_tools source code is available on GitHub, and can be accessed from the following URL: https://github.com/domdfcoding/enum_tools

If you have git installed, you can clone the repository with the following command:

git clone https://github.com/domdfcoding/enum_tools
Cloning into 'enum_tools'...
remote: Enumerating objects: 47, done.
remote: Counting objects: 100% (47/47), done.
remote: Compressing objects: 100% (41/41), done.
remote: Total 173 (delta 16), reused 17 (delta 6), pack-reused 126
Receiving objects: 100% (173/173), 126.56 KiB | 678.00 KiB/s, done.
Resolving deltas: 100% (66/66), done.
Alternatively, the code can be downloaded in a ‘zip’ file by clicking:
Clone or download –> Download Zip
Downloading a 'zip' file of the source code.

Downloading a ‘zip’ file of the source code

Building from source

The recommended way to build enum_tools is to use tox:

tox -e build

The source and wheel distributions will be in the directory dist.

If you wish, you may also use pep517.build or another PEP 517-compatible build tool.

License

enum_tools is licensed under the GNU Lesser General Public License v3.0

Permissions of this copyleft license are conditioned on making available complete source code of licensed works and modifications under the same license or the GNU GPLv3. Copyright and license notices must be preserved. Contributors provide an express grant of patent rights. However, a larger work using the licensed work through interfaces provided by the licensed work may be distributed under different terms and without source code for the larger work.

Permissions Conditions Limitations
  • Commercial use
  • Modification
  • Distribution
  • Patent use
  • Private use
  • Disclose source
  • State changes
  • Same license (library)
  • Liability
  • Warranty

                   GNU LESSER GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.


  This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.

  0. Additional Definitions.

  As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.

  "The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.

  An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.

  A "Combined Work" is a work produced by combining or linking an
Application with the Library.  The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".

  The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.

  The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.

  1. Exception to Section 3 of the GNU GPL.

  You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.

  2. Conveying Modified Versions.

  If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:

   a) under this License, provided that you make a good faith effort to
   ensure that, in the event an Application does not supply the
   function or data, the facility still operates, and performs
   whatever part of its purpose remains meaningful, or

   b) under the GNU GPL, with none of the additional permissions of
   this License applicable to that copy.

  3. Object Code Incorporating Material from Library Header Files.

  The object code form of an Application may incorporate material from
a header file that is part of the Library.  You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:

   a) Give prominent notice with each copy of the object code that the
   Library is used in it and that the Library and its use are
   covered by this License.

   b) Accompany the object code with a copy of the GNU GPL and this license
   document.

  4. Combined Works.

  You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:

   a) Give prominent notice with each copy of the Combined Work that
   the Library is used in it and that the Library and its use are
   covered by this License.

   b) Accompany the Combined Work with a copy of the GNU GPL and this license
   document.

   c) For a Combined Work that displays copyright notices during
   execution, include the copyright notice for the Library among
   these notices, as well as a reference directing the user to the
   copies of the GNU GPL and this license document.

   d) Do one of the following:

       0) Convey the Minimal Corresponding Source under the terms of this
       License, and the Corresponding Application Code in a form
       suitable for, and under terms that permit, the user to
       recombine or relink the Application with a modified version of
       the Linked Version to produce a modified Combined Work, in the
       manner specified by section 6 of the GNU GPL for conveying
       Corresponding Source.

       1) Use a suitable shared library mechanism for linking with the
       Library.  A suitable mechanism is one that (a) uses at run time
       a copy of the Library already present on the user's computer
       system, and (b) will operate properly with a modified version
       of the Library that is interface-compatible with the Linked
       Version.

   e) Provide Installation Information, but only if you would otherwise
   be required to provide such information under section 6 of the
   GNU GPL, and only to the extent that such information is
   necessary to install and execute a modified version of the
   Combined Work produced by recombining or relinking the
   Application with a modified version of the Linked Version. (If
   you use option 4d0, the Installation Information must accompany
   the Minimal Corresponding Source and Corresponding Application
   Code. If you use option 4d1, you must provide the Installation
   Information in the manner specified by section 6 of the GNU GPL
   for conveying Corresponding Source.)

  5. Combined Libraries.

  You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:

   a) Accompany the combined library with a copy of the same work based
   on the Library, uncombined with any other library facilities,
   conveyed under the terms of this License.

   b) Give prominent notice with the combined library that part of it
   is a work based on the Library, and explaining where to find the
   accompanying uncombined form of the same work.

  6. Revised Versions of the GNU Lesser General Public License.

  The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.

  Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.

  If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View the Function Index or browse the Source Code.

Browse the GitHub Repository