Create constants using a "settings" module?

Question:

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

Asked By: Lark

||

Answers:

Leave your settings.py exactly as it is, then you can use it just as Django does:

import settings

def func():
    var = settings.CONSTANT
Answered By: Ned Batchelder

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.

Answered By: aaronasterling

When you import settings, a module object called settings is placed in the global namespace – and this object carries has that was in settings.py as attributes. I.e. outside of settings.py, you refer to CONSTANT as settings.CONSTANT.

Answered By: user395760

…Or, if you really want all the constants from settings.py to be imported into the global namespace, you can run

from settings import *

…but otherwise using settings.CONSTANT, as everyone else has mentioned here, is quite right.

Answered By: ewall

Try this:

In settings.py:

CONSTANT = 5

In your main file:

from settings import CONSTANT

class A:
    b = CONSTANT

    def printb(self):
         print self.b

I think your above error is coming from the settings file being imported too late. Make sure it’s at the top of the file.

Answered By: kcunning

See the answer I posted to Can I prevent modifying an object in Python? which does what you want (as well as force the use of UPPERCASE identifiers). It might actually be a better answer for this question than it was for the the other.

Answered By: martineau

I’m new in python but if we define an constant like a function
on setings.py

def CONST1():
    return "some value"

main.py

import setings

print setings.CONST1() ##take an constant value

here I see only one, value cant be changed but its work like a function..

Answered By: IVI

step 1: create a new file settings.py on the same directory for easier access.

#database configuration settings

database = dict(
    DATABASE = "mysql",
    USER     = "Lark",
    PASS     = ""
)

#application predefined constants

app = dict(
    VERSION   = 1.0,
    GITHUB    = "{url}"
)

step 2: importing settings module into your application file.

import settings as s            # s is aliasing settings & settings is the actual file you do not have to add .py 

print(s.database['DATABASE'])   # should output mysql

print(s.app['VERSION'])         # should output 1.0

if you do not like to use alias like s you can use a different syntax

from settings import database, app

print(database['DATABASE'])   # should output mysql

print(app['VERSION'])         # should output 1.0

notice on the second import method you can use the dict names directly

A small tip you can import all the code on the settings file by using * in case you have a large file and you will be using most of the settings on it on your application

from settings import *      # * represent all the code on the file, it will work like step 2


print(database['USER'])       # should output lark

print(app['VERSION'])         # should output 1.0

i hope that helps.

Answered By: Fady Faried

Also worth checking out is the simple-settings project which allows you to feed the settings into your script at runtim, which allows for environment-specific settings (think dev, test, prod,…)

Answered By: Gregor

This way is more efficient since it loads/evaluates your settings variables only once. It works well for all my Python projects.

pip install python-settings

Docs here: https://github.com/charlsagente/python-settings

You need a settings.py file with all your defined constants like:

# settings.py

DATABASE_HOST = '10.0.0.1'

Then you need to either set an env variable (export SETTINGS_MODULE=settings) or manually calling the configure method:

# something_else.py

from python_settings import settings
from . import settings as my_local_settings

settings.configure(my_local_settings) # configure() receives a python module

The utility also supports Lazy initialization for heavy to load objects, so when you run your python project it loads faster since it only evaluates the settings variable when its needed

# settings.py

from python_settings import LazySetting
from my_awesome_library import HeavyInitializationClass # Heavy to initialize object

LAZY_INITIALIZATION = LazySetting(HeavyInitializationClass, "127.0.0.1:4222") 
# LazySetting(Class, *args, **kwargs)

Just configure once and now call your variables where is needed:

# my_awesome_file.py

from python_settings import settings 

print(settings.DATABASE_HOST) # Will print '10.0.0.1'
Answered By: charls
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.