Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to initialize global variables in Python

Tags:

python

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.

like image 621
blueSurfer Avatar asked May 27 '14 12:05

blueSurfer


People also ask

Can we initialize global variable in Python?

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.

How do you declare a global variable in Python?

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.

How do you initialize a global variable?

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.

How do you initialize a global list in Python?

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.


2 Answers

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.

like image 165
Martijn Pieters Avatar answered Sep 30 '22 10:09

Martijn Pieters


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
like image 45
gulden Avatar answered Sep 30 '22 12:09

gulden