Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 479
Thierry Lam Avatar asked Jun 14 '11 15:06

Thierry Lam


People also ask

How do you use constants in a class Python?

Constants enable you to use the same name to identify the same value throughout your code. If you need to update the constant's value, then you don't have to change every instance of the value. You just have to change the value in a single place: the constant definition. This improves your code's maintainability.

Where is the best place to declare constants?

You declare a constant within a procedure or in the declarations section of a module, class, or structure. Class or structure-level constants are Private by default, but may also be declared as Public , Friend , Protected , or Protected Friend for the appropriate level of code access.


2 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

like image 105
Daren Thomas Avatar answered Sep 21 '22 17:09

Daren Thomas


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.

like image 33
wheaties Avatar answered Sep 20 '22 17:09

wheaties