0

Currently my configuration options (constants / variables) are a bit fragmented, I have most of them in config.py but some are in the myfile.py at the top.

/utilities/myfile.py
/config.py

An example of what you might find in my myfile.py is:

TEMP_DIR = '/tmp'

If I wanted to move this definition from my myfile.py into my config.py but still use it in my myfile.py, how do I go about it?

I am new to python but I assume it is something along the lines of this at the top of myfile.py

from config
Jimmy
  • 12,087
  • 28
  • 102
  • 192

3 Answers3

0

In myfile.py you could put

import config

and access TEMP_DIR with

config.TEMP_DIR

provided the directory containing config.py is in your PYTHONPATH.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

variant 1

from config import *

this polutes the whole namespace in myfile.py

variant 2

from config import foo, bar, baz

Ever value used in myfile.py have to be mentioned.

variant 3

import config
...
x = config.foo

every value need to refer to config.

Your choice, but i prefer variant 3. To see config.py in myfile.py, you either have to edit your PYTHONPATH or use a relative import:

from ... import config
Peter Schneider
  • 1,683
  • 12
  • 31
  • I feel that this is important to note because many python users fail to mention this to new python users: if you use the code `import config`, then you need to add on the module when calling an object within it, like so: `x = config.foo` if you use `from config import *`, however, you do _NOT_ need to put the module before the object: `x = foo`. I forget why this is, but it will save you a lot of time and confusion if you remember this when using python. – Ben Schwabe Nov 20 '12 at 13:42
0

Another way to do this is to use execfile. This will make it easier to use different configuration files (for instance specify the configuration file to use on the command line).

Example:

# myconfig.py
TEMP_DIR = "/tmp/"

# myotherconfig.py
TEMP_DIR = "/tmp/foo"

# program.py (the main program)
import sys
config = {}
execfile(sys.argv[1], config)
print config["TEMP_DIR"]

Invoking the program:

$ python program.py myconfig.py
/tmp/
$ python program.py myotherconfig.py
/tmp/foo

Related: Python configuration file: Any file format recommendation? INI format still appropriate? Seems quite old school

Community
  • 1
  • 1
codeape
  • 97,830
  • 24
  • 159
  • 188