https://github.com/2degrees/python-enumeration
Enum implementation for Python 2 and 3
https://github.com/2degrees/python-enumeration
Last synced: 2 months ago
JSON representation
Enum implementation for Python 2 and 3
- Host: GitHub
- URL: https://github.com/2degrees/python-enumeration
- Owner: 2degrees
- Created: 2016-09-13T13:35:43.000Z (almost 10 years ago)
- Default Branch: master
- Last Pushed: 2016-10-28T11:03:22.000Z (over 9 years ago)
- Last Synced: 2025-12-31T11:28:06.250Z (6 months ago)
- Language: Python
- Size: 10.7 KB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# python-enumeration
[](https://travis-ci.org/2degrees/python-enumeration)
[](https://coveralls.io/github/2degrees/python-enumeration?branch=master)
An enumeration data type for Python.
## Getting started
python-enumeration can be installed from PyPi via:
```bash
pip install python-enumeration
```
You can then import the library and define an enumeration:
```python
from enumeration import Enum
MY_ENUM = Enum(
('value', 'IDENTIFIER'),
...
)
```
## Usage
python-enumeration allows you to define enumerated data so that you have
a consistent interface to the underlying data, e.g.
```python
>>> from enumeration import Enum
>>> AGES_OF_MAN = Enum(
... ('baby', 'BABY'),
... ('toddler', 'TODDLER'),
... ('child', 'CHILD'),
... ('teenager', 'TEENAGER'),
... ('adult', 'ADULT'),
... ('elderly', 'ELDERLY'),
... )
>>> AGES_OF_MAN.BABY
>>> str(AGES_OF_MAN.BABY)
'baby'
>>> AGES_OF_MAN.BABY.item_value
'baby'
```
### Comparison
python-enumeration supports comparison operations on its items so the
order in which the enum defines its items is importation:
```python
>>> AGES_OF_MAN.BABY < AGES_OF_MAN.TODDLER
True
>>> AGES_OF_MAN.TODDLER > AGES_OF_MAN.CHILD
False
>>> AGES_OF_MAN.ADULT <= AGES_OF_MAN.ADULT
True
```
It's also possible to list all the values which are less than or
greater than an item:
```python
>>> AGES_OF_MAN.CHILD.previous_values
('baby', 'toddler')
>>> AGES_OF_MAN.CHILD.previous_values_with_self
('baby', 'toddler', 'child')
>>> AGES_OF_MAN.CHILD.subsequent_values
('teenager', 'adult', 'elderly')
>>> AGES_OF_MAN.CHILD.subsequent_values_with_self
('child', 'teenager', 'adult', 'elderly')
```
### Setting human-readable labels
If you want to display a label for your enumeration in some UI, you can
define a set of UI labels for the enumeration:
```python
>>> AGES_OF_MAN.set_ui_labels({
... AGES_OF_MAN.BABY: "Baby",
... AGES_OF_MAN.TODDLER: "Toddler",
... AGES_OF_MAN.CHILD: "Child",
... AGES_OF_MAN.TEENAGER: "Teenager",
... AGES_OF_MAN.ADULT: "Adult",
... AGES_OF_MAN.ELDERLY: "Elderly",
... })
>>> AGES_OF_MAN.BABY.get_ui_label()
'Baby'
>>> AGES_OF_MAN.get_ui_labels()
((, 'Baby'), (, 'Toddler'), (, 'Child'), (, 'Teenager'), (, 'Adult'), (, 'Elderly'))
```
For further examples of how you can use the enumeration, see the test
suite.