Explain Codes LogoExplain Codes Logo

How do I create a constant in Python?

python
constants
emulation
typing-final
Anton ShumikhinbyAnton ShumikhinΒ·Aug 23, 2024
⚑TLDR

In Python, create a constant by using ALL CAPS for the variable name:

MY_CONSTANT = "I'm a constant. Don't change me, please πŸ˜…"

This doesn't enforce the constant's immutability but signifies that MY_CONSTANT should not be modified.

Emulating constants in Python

Python doesn't natively support constants, but we can emulate them:

Wield typing.Final

From Python 3.8+, you can use typing.Final to denote that a variable should never be reassigned. This doesn't enforce runtime immutability, but tools like mypy will catch reassignments.

from typing import Final MY_FINAL: Final = "Constant as a northern star ⭐️" # Will raise an error if you try to reassign MY_FINAL

Opt for OOP

Use classes to house your constants. A clever use of properties can prevent modifications.

class MyConfig: @property def CONSTANT_SIZE(self): return "Size doesn't matter 😜" # Now MyConfig().CONSTANT_SIZE is a constant value

Explore __slots__

__slots__ prevents the dynamic creation of attributes in a class, providing a way to emulate immutability:

class MyConfigWithSlots: __slots__ = ("NO_NEW_ATTRIBUTES",) def __init__(self): self.NO_NEW_ATTRIBUTES = "Try and create another attribute. I dare you πŸ™ƒ" # Any attempts to create new attributes raise AttributeError

Experiment with immutable collections

Python offers namedtuple and Enums β€” special types ideal for creating sets of constants:

from enum import Enum class Planets(Enum): MERCURY = (3.303e+23, 2.4397e6) # Mass and radius constant values # Planets.MERCURY is now a constant pair that represents Mercury's characteristics

Constants in disguise

We can disguise variables as constants. Here are some methods:

Sprinkle some decorator magic

A @constant decorator for class properties can make your intent clear and prevent modifications:

def constant_property(func): """ Decorator that transforms a method into a read-only property. It's like putting a do-not-touch sign🚫 """ return property(func)

Enforce in functions

Create constants using functions to prevent them from being redefined within the scope:

def IT_IS_FINAL(): return "Not the final you wished for at the end of class? πŸ˜‰" # Attempt to reassign IT_IS_FINAL will yield UnboundLocalError

Dive into local scope

Locally, read-only variables can be created using the locals() function:

def local_function(): LOCAL_CONSTANTS = locals() LOCAL_CONSTANTS['SECRET_KEY'] = "My precious! πŸ’" # Within local_function, SECRET_KEY behaves like a constant