Python Constants

This section explains how constants work in Python and provides examples of their different types. It also introduces commonly used built-in constants such as True, False, None, Ellipsis, and NotImplemented.

How constants work in Python

For most purposes, constants work just like variables in Python – they can be passed as arguments to functions or included in sequences like list, tuple, or dict.

The main difference from variables is that constants are fixed, not supposed to be changed.

Types of Python constants

There are different kinds of constants in Python:

  • Built-in constants such as True, False, None, Ellipsis, and NotImplemented
  • Module based constants, such as math.pi or datetime.MAXYEAR
  • Class constants, used for values common to all instances of the class
  • Global constants typically defined at the beginning of a script or file and named with uppercase letters

How to create a constant

To create a constant in Python, assign a value to a constant name, just like with variables.

WEBSITE_NAME = 'PyTut'
HOME_URL = 'https://www.pytut.com/'
DEFAULT_FONT_SIZE = 12

By convention, constant names use all capital letters, but this is not enforced.

Python constant examples

Constants are commonly used to store values or information which don't change throughout the program execution.

  • Database names, file paths, URLs
  • Screen width and height, default font size, screen refresh rate
  • Mathematical constants such as pi or e
  • Scientific constants, such as speed of light or gravitational constant
  • Economic constants, like tax rates or interest rates

A Python constant does not need to be just a numeric value or string. Sequences like tuples, lists, or dicts are also commonly used as constants. For example:

  • Tuple with x, y coordinates
  • List of files to process
  • List of stock symbols
  • Dict to convert csv file column names to database column names
  • Dict of country codes and sales tax rates
EU_VAT_RATES = {
    'AT' : 20, # Austria
    'BE' : 21, # Belgium
    'BG' : 20, # Bulgaria
    'HR' : 25, # Croatia
    'CY' : 19, # Cyprus
    'CZ' : 21, # Czech Republic
    ...
}

Constants can also be other types. For instance, date or datetime objects from the datetime module are often used as constants.

import datetime as dt

START_DATE = dt.date(2023, 7, 1)
END_DATE = dt.date(2027, 6, 30)

Built-in Python constants

Python core includes several built-in constants which are always available without the need to import them. Additional constants come with various modules.

Commonly used built-in Python constants are the following:

True, False

The two boolean constants True and False are mainly used for program logic – controlling the flow of execution based on variables being true or false. Variables are True if they are non-zero numbers, non-empty strings, or non-empty sequences. They are False if they are zero numbers, empty strings, empty sequences, or None. True/False variables can be created through literal assignment, using comparison operators with other variables, or the bool() function. [more details...]

None

The None constant represent a null, empty, or missing value. To assign a variable None, use the None keyword (with capital "N"). A None variable evaluates False in boolean operations. To test if a variable is None, use the is operator instead of == as it is faster and more reliable. None has its own data type called NoneType. [more details...]

Ellipsis

The Ellipsis constant can be used as a placeholder or to omit code. It is typed either using the keyword Ellipsis (with uppercase E) or as three dots (...) – the two are equivalent. In Python 2, ellipsis was only available in slices, but since Python 3.0, it is available anywhere in Python. [more details...]

NotImplemented

NotImplemented is a special constant that is used to indicate that a particular operation or method is not implemented for a specific class or object. It is often used in abstract base classes, where methods are defined but not implemented, and in comparison methods, where the result of a comparison cannot be determined. [more details...]

Changing a constant

Built-in constants can't be changed

This does not apply to built-in constants. You can't assign any value to True, False, or None.

>>> True = some_other_word_for_true
  File "", line 1
    True = some_other_word_for_true
    ^^^^
SyntaxError: cannot assign to True

Other constants can be changed (but mostly shouldn't be)

Other than built-in constants, although not supposed to be changed, Python does not prevent you or raise any errors. From this perspective, constants behave just like variables (the case does not matter).

>>> TAX_RATE = 0.20
>>> TAX_RATE
0.2
>>> TAX_RATE = 0.22
>>> TAX_RATE
0.22

You can also change most module based constants. Even math.pi if you want to change it to 100 for some reason (it will only apply to the current session):

>>> import math
>>> math.pi
3.141592653589793
>>> math.pi = 100
>>> math.pi
100

That being said, although Python lets you change constants, in most cases (like the extreme pi example above) it makes no sense to do so and goes against the very nature and purpose of constants.

By remaining on this website or using its content, you confirm that you have read and agree with the Terms of Use Agreement.

We are not liable for any damages resulting from using this website. Any information may be inaccurate or incomplete. See full Limitation of Liability.

Content may include affiliate links, which means we may earn commission if you buy on the linked website. See full Affiliate and Referral Disclosure.

We use cookies and similar technology to improve user experience and analyze traffic. See full Cookie Policy.

See also Privacy Policy on how we collect and handle user data.

© 2024 PyTut