What's the best way to initialise and use constants across Python classes?

Question:

Here’s how I am declaring constants and using them across different Python classes:

# project/constants.py
GOOD = 1
BAD = 2
AWFUL = 3

# project/question.py
from constants import AWFUL, BAD, GOOD

class Question:
    def __init__(self):
        ...

Is the above a good way to store and use contant values? I realise that after a while, the constants file can get pretty big and I could explicitly be importing 10+ of those constants in any given file.

Asked By: Thierry Lam

||

Answers:

why not just use

import constants

def use_my_constants():
    print constants.GOOD, constants.BAD, constants.AWFUL

From the python zen:

Namespaces are good. Lets do more of those!

EDIT: Except, when you do quote, you should include a reference and check it, because as others have pointed out, it should read:

Namespaces are one honking great idea — let’s do more of those!

This time, I actually copied it from the source: PEP 20 — The Zen of Python

Answered By: Daren Thomas

You have a few options:

  1. Do it the way you’re doing right now with a file of constants
  2. Use a flat file and parse it once, pass a dictionary / class around
  3. Query off to a database

From an overhead point of view, 1 and 2 are about the same. As for your question about importing specific constants, it’s much easier to use one of the following conventions:

  • import constants; some_func(constants.AWFUL)
  • from constants import *; some_func(AWFUL)
Answered By: Chris Eberle

You also have the option, if the constants are tied to a particular class and used privately within that class of making them specific to that class:

class Foo(object):
   GOOD = 0
   BAD = 1
   WTF = -1

   def __init__(self...

and away you go.

Answered By: wheaties

Try to look at the following links(one link contains a receipt from active state of how to implement a real constants):

Importing a long list of constants to a Python file

Create constants using a "settings" module?

Can I prevent modifying an object in Python?

Answered By: Artsiom Rudzenka

I use a function as immutable constant, like this:

def test_immutable_constant():
    def GOOD():
        return 1

    good_value = GOOD()
    good_value = 2

    assert GOOD() == 1
    assert good_value == 2
Answered By: Wendel
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.