Whats the best way to initialise and use constants across Python classes?

Whats the best way to initialise and use constants across Python classes?

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 — lets do more of those!

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

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.

Whats the best way to initialise and use constants across Python classes?

You have a few options:

  1. Do it the way youre 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, its much easier to use one of the following conventions:

  • import constants; some_func(constants.AWFUL)
  • from constants import *; some_func(AWFUL)

Leave a Reply

Your email address will not be published.