Constantly: Symbolic Constants

23.10.4 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This example demonstrates how to define a set of named constants using `Values` and `NamedConstant`, and how to access and compare them. `NamedConstant` instances within a `Values` class are singletons.

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}")

view raw JSON →