I am trying to use a *.py file to take variables from and use them across multiple imports in my python application, similar to how a Django settings file works.
An example settings file:
DB_NAME = 'foo'
DB_TABLE = 'bar'
#Lots of other variable names and values here
The benefit is that I can load different settings very quickly this way. I can reference a sort of global "DB_NAME" wherever I want without having specific objects to deal with.
The drawback is that I have to change the import statement in every file that has to import them.
Can I set it up so that I import the file once and then reference a generic import to get all of these values?
Or is there a much better way to do this?
Any help is appreciated.
EDIT: The problem stems from having multiple settings files. I would have to import settings.py for one file, or if I want a different settings file, I would need to change all the import statements to reference test_settings.py, etc..
I don't want to manually change the import locations in order to change what is imported across the entire application.
create our own config.py file in a folder
settings = {}
settings['server'] = '172.16.150.106:1433'
settings['user'] = 'pyadmin'
settings['password'] = 'admin'
settings['db'] = 'SQLSERV_2005'
open shell (ipython)
In [1]: from config import settings
In [2]: print settings
{'password': 'admin', 'db': 'SQLSERV_2005', 'user': 'pyadmin', 'server': '172.16.150.106:1433'}
don't forget your __init__.py file !
You can use module __builtin__:
File a.py:
#!/usr/bin/env python
import __builtin__
import b
if __name__ == "__main__":
import conf
__builtin__.__dict__["CONF"] = conf
print "IN A: %s" % CONF.VAR
b.test_conf()
File b.py:
def test_conf():
print "IN B: %s" % CONF.VAR
File conf.py:
VAR = "VAL"
So basically you need to setup an element in builtin dict once and then access it in any other loaded modules by name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With