Constantly: Symbolic Constants
constantly is a Python library providing symbolic constants, particularly useful for creating enumerated types and immutable values that are easily comparable by identity. It is maintained by the Twisted project, with releases appearing periodically. The current version is 23.10.4.
Warnings
- breaking Python 3.7 support was dropped in `constantly` version 23.10.0.
- gotcha NamedConstants defined within a `Values` class are singletons. Prefer identity comparison (`is`) over value comparison (`==`) for correctness, especially when comparing against other objects or similar strings.
- gotcha Attempting to modify the `name` or `value` attributes of a `Constant` or `NamedConstant` after definition will result in an `AttributeError`, as they are designed to be immutable.
Install
-
pip install constantly
Imports
- Constant
from constantly import Constant
- NamedConstant
from constantly import NamedConstant
- Values
from constantly import Values
Quickstart
from constantly import NamedConstant, Values
class Fruit(Values):
apple = NamedConstant()
banana = NamedConstant()
orange = NamedConstant()
# Accessing constants
print(f"Apple constant: {Fruit.apple}")
print(f"Apple name: {Fruit.apple.name}")
print(f"Apple value: {Fruit.apple.value}")
# Comparing constants by identity (preferred)
print(f"Is Fruit.apple the same object as Fruit.apple? {Fruit.apple is Fruit.apple}")
print(f"Is Fruit.apple the same object as Fruit.banana? {Fruit.apple is Fruit.banana}")
# Iterating over constants in the class
print("All fruits:")
for fruit in Fruit.iterconstants():
print(f"- {fruit.name}")