I have a Python module that initialize some global variables; something like this:
#!/usr/bin/env python
import re
"""My awesome python library."""
# A word list from the standard UNIX dictionary.
with open('/usr/share/dict/words', 'rt') as f:
WORDS_LIST = f.read().split('\n') + ['http'] + ['fubob']
# Some compiled regular expressions.
COMPILED_REG1 = re.compile("a")
COMPILED_REG2 = re.compile("b")
# Some constants.
A = 10
B = 20
def say_hello(): print('hello')
def do_something(): return 'something'
Of course it works but I don't feel that this is the right way to do it: every time I import this module Python is going to execute it. In this example it will read the file and compile the regular expressions.
I read that some creates a config.py file and do something with that but I don't know exactly how this works.
So, I would like to know how would you deal with this if you have to make a standard Python library.
You can create a variable with global scope by initializing outside all the functions in a python program. And you can access the variable from anywhere in the python program.
We declare a variable global by using the keyword global before a variable. All variables have the scope of the block, where they are declared and defined in. They can only be used after the point of their declaration.
In C language both the global and static variables must be initialized with constant values. This is because the values of these variables must be known before the execution starts. An error will be generated if the constant values are not provided for global and static variables.
You can declare Global list on the file/module level like: my_global_list = list() in Python. If you want to append to it inside a function you can use the global keyword.
every time I import this module Python is going to execute it
This is not correct. Python executes your module globals just once, the first time it is imported. The resulting module object is then stored in sys.modules
and re-used for subsequent imports. See the import
statement documenation:
Once the name of the module is known (unless otherwise specified, the term “module” will refer to both packages and modules), searching for the module or package can begin. The first place checked is
sys.modules
, the cache of all modules that have been imported previously. If the module is found there then it is used in step (2) of import.
What you are doing is the correct way to do it and is exactly what standard Python library modules do.
You cold do this. SafeConfigParser should be available without installing
Python file:
from ConfigParser import SafeConfigParser
try:
# Getting DB connection data from config file
parser = SafeConfigParser()
parser.read('config.txt')
dhost = parser.get('db', 'host')
ddatabase = parser.get('db', 'db')
duser = parser.get('db', 'user')
dpassword = parser.get('db', 'pw')
except Exception, err:
print str(err)
logger.error(str(err))
Config file:
[db]
host = 179.10.13.2
db = main
user = max
pw = c45v243v5b2v6v25v6554v9
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