Correct way to initialize global variables in Python

python

Solution

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.

Problem

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.

Original source