2

As of now we have a file conf.py which stores most of our configuration variables for the service. We have code similar to this:

environment = 'dev' # could be dev, local, staging, production
configa = 'something'
configb = 'something else'

if environment = 'dev':
    configa = 'something dev'

elif environment = 'local':
    configa = 'something local'

Is this the right way to manage configuration file in a python project? Are these configuration loaded into variables at compile time (while creating pyc files), or are the if conditions checked every time the conf is imported in a python script or is it every time a configuration variable is accessed?

Sambhav Sharma
  • 5,495
  • 9
  • 52
  • 85

3 Answers3

2

All code runs at import time. But since you are unlikely to import your application again and again while it's running you can ignore the (minimal) overhead.

ThiefMaster
  • 298,938
  • 77
  • 579
  • 623
2

This is subjective but there is a good discussion in this post: What's the best practice using a settings file in Python?

With your method, it will be treated the same way as any other python script, i.e. on import. If you wanted it updated on access/or without restarting the service it is best to use an external/non-python config file (e.g. json, .ini) and set up functionality to refresh the file.

Community
  • 1
  • 1
Lewis Fogden
  • 505
  • 4
  • 8
0

You must create a file, example settings.py, add the path to the module where the file to the system. Example:

sys.path.append(os.path.dirname(__file__))

Аfter anywhere you can import the file and to obtain from any setting:

import settings

env = settings.environment

Similarly, many working frameworks.

alex10
  • 2,336
  • 3
  • 16
  • 32