Importing a long list of constants to a Python file

Viewed 173511

In Python, is there an analogue of the C preprocessor statement such as?:

#define MY_CONSTANT 50

Also, I have a large list of constants I'd like to import to several classes. Is there an analogue of declaring the constants as a long sequence of statements like the above in a .py file and importing it to another .py file?

Edit.

The file Constants.py reads:

#!/usr/bin/env python
# encoding: utf-8
"""
Constants.py
"""

MY_CONSTANT_ONE = 50
MY_CONSTANT_TWO = 51

And myExample.py reads:

#!/usr/bin/env python
# encoding: utf-8
"""
myExample.py
"""

import sys
import os

import Constants

class myExample:
    def __init__(self):
        self.someValueOne = Constants.MY_CONSTANT_ONE + 1
        self.someValueTwo = Constants.MY_CONSTANT_TWO + 1

if __name__ == '__main__':
    x = MyClass()

Edit.

From the compiler,

NameError: "global name 'MY_CONSTANT_ONE' is not defined"

function init in myExample at line 13 self.someValueOne = Constants.MY_CONSTANT_ONE + 1 copy output Program exited with code #1 after 0.06 seconds.

11 Answers

create constant file with any name like my_constants.py declare constant like that

CONSTANT_NAME = "SOME VALUE"

For accessing constant in your code import file like that

import my_constants as constant

and access the constant value as -

constant.CONSTANT_NAME

In commercial software, the constant(s) will frequently be buried many folders deep. Use solution below in combination with above solutions for best results. Here's the syntax that worked for me:

folder_a
    folder_b
        constants.py
# -----------
# constants.py
# ------------
MAXVAL = 1000

folder_c
    folder_d
        my_file.py

# ------------------------
# my_file.py
# ------------------------
import folder_a.folder_b.constants as consts

print(consts.MAXVAL)

In more recent editions, it seems a bit pickier.

the mode in the top answer

Main.py

import constants
print(token)

constants.py enter code heretoken = "12345"

failed. Instead, I had to import individual variable from constants.

Main.py

from constants import token
print(token)

A constants.py file is good, but I ran into a situation where I would rather had my constants on top of the file.

A similar Python dict would need an access to the variable with a string key dict['A'], but I needed something with the same syntax as a module import.

(For the curious, I was working on Google Collab .ipynb multiple files, with different configuration variables for each of them, and you can't edit quickly an imported constants.py from Collab, nor import directly another .ipynb file. )

from dataclasses import dataclass

@dataclass
class Constants:
    A = "foo"

cst = Constants()
print(cst.A)
>>> "foo"

You could also create a classic Python Class, but this needs to define a __init__

Related