Create constants using a "settings" module?

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.


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.

Tags:

Python