A class decorator for adding ordering to enums
Project description
ordered_enum
ordered_enum is a small library for adding (total) orderings to enum.Enum
s.
It provides two ordering behaviors:
ordered_enum.OrderedEnum
: total ordering by definitionordered_enum.ValueOrderedEnum
: "total" ordering by member values
Installation
ordered_enum requires Python 3.6 or newer.
pip3 install ordered_enum
Usage
To use ordered_enum, just use OrderedEnum
or ValueOrderedEnum
as your parent class:
from ordered_enum import OrderedEnum
class State(OrderedEnum):
Disabled = 4
Loaded = 3
Waiting = 2
Running = 1
Dead = 0
assert(State.Disabled < State.Loaded)
assert(sorted([State.Dead, State.Waiting]) == [State.Waiting, State.Dead])
OrderedEnum
doesn't require @enum.unique
(or unique values at all); it uses the order of
definition to impose an ordering between members.
If you'd like to impose an ordering based on member values, you can use ValueOrderedEnum
instead:
import enum
from ordered_enum import ValueOrderedEnum
@enum.unique
class State(ValueOrderedEnum):
Disabled = 4
Loaded = 3
Waiting = 2
Running = 1
Dead = 0
assert(State.Disabled > State.Loaded)
assert(sorted([State.Waiting, State.Dead]) == [State.Dead, State.Waiting])
ValueOrderedEnum
does require unique values, which can be enforced via @enum.unique
.
Failing to make a ValueOrderedEnum
's values unique will result in a silently broken ordering.
Caveats
As mentioned above, ordered_enum.OrderedEnum
provides an ordering of enum values based on their order
of definition in the class. This means that:
- Enum values doesn't have to be unique for ordered_enum to work
- Enum values can be heterogeneously typed
- Moving enum values around changes their ordering
Therefore, you should either not depend on a specific ordering or ensure that your order of definition is the order you'd like.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file ordered_enum-0.0.1.tar.gz
.
File metadata
- Download URL: ordered_enum-0.0.1.tar.gz
- Upload date:
- Size: 2.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.42.1 CPython/3.6.9
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 6be0b6aab56d736dafe00b19338e2e5b1bfdf6d1668b57d57e959045bd272871 |
|
MD5 | 529cdc7ed0e3c5b58cd01609c2ec2a86 |
|
BLAKE2b-256 | 821f62370504a5f06845caf74e5a0c325ce01e5fab136531231da102d0da1f7a |