Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create constants using a "settings" module?

Tags:

python

I am relatively new to Python. I am looking to create a "settings" module where various application-specific constants will be stored.

Here is how I am wanting to set up my code:

settings.py

CONSTANT = 'value' 

script.py

import settings  def func():     var = CONSTANT     # do some more coding     return var 

I am getting a Python error stating:

global name 'CONSTANT' is not defined.

I have noticed on Django's source code their settings.py file has constants named just like I do. I am confused on how they can be imported to a script and referenced through the application.

EDIT

Thank you for all your answers! I tried the following:

import settings  print settings.CONSTANT 

I get the same error

ImportError: cannot import name CONSTANT

like image 587
Lark Avatar asked Sep 29 '10 17:09

Lark


People also ask

How do you define a constant in Python module?

Constants are usually defined on a module level and written in all capital letters with underscores separating words.

How do you store constants in Python?

Assigning value to constant in Python In Python, constants are usually declared and assigned in a module. Here, the module is a new file containing variables, functions, etc which is imported to the main file. Inside the module, constants are written in all capital letters and underscores separating the words.

What are Python settings?

A settings file is just a Python module with module-level variables. If you set DEBUG to False , you also need to properly set the ALLOWED_HOSTS setting. Because a settings file is a Python module, the following apply: It doesn't allow for Python syntax errors.


1 Answers

The easiest way to do this is to just have settings be a module.

(settings.py)

CONSTANT1 = "value1" CONSTANT2 = "value2" 

(consumer.py)

import settings  print settings.CONSTANT1 print settings.CONSTANT2 

When you import a python module, you have to prefix the the variables that you pull from it with the module name. If you know exactly what values you want to use from it in a given file and you are not worried about them changing during execution, then you can do

from settings import CONSTANT1, CONSTANT2  print CONSTANT1 print CONSTANT2 

but I wouldn't get carried away with that last one. It makes it difficult for people reading your code to tell where values are coming from. and precludes those values being updated if another client module changes them. One final way to do it is

import settings as s  print s.CONSTANT1 print s.CONSTANT2 

This saves you typing, will propagate updates and only requires readers to remember that anything after s is from the settings module.

like image 165
aaronasterling Avatar answered Sep 29 '22 11:09

aaronasterling