Reputation: 5860
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?
Upvotes: 2
Views: 687
Reputation: 2756
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.
Upvotes: 0
Reputation: 524
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.
Upvotes: 2
Reputation: 318518
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.
Upvotes: 2