How to create module-wide variables in Python?

How to create module-wide variables in Python?

Here is what is going on.

First, the only global variables Python really has are module-scoped variables. You cannot make a variable that is truly global; all you can do is make a variable in a particular scope. (If you make a variable inside the Python interpreter, and then import other modules, your variable is in the outermost scope and thus global within your Python session.)

All you have to do to make a module-global variable is just assign to a name.

Imagine a file called, containing this single line:

X = 1

Now imagine you import it.

import foo
print(foo.X)  # prints 1

However, lets suppose you want to use one of your module-scope variables as a global inside a function, as in your example. Pythons default is to assume that function variables are local. You simply add a global declaration in your function, before you try to use the global.

def initDB(name):
    global __DBNAME__  # add this line!
    if __DBNAME__ is None: # see notes below; explicit test for None
        __DBNAME__ = name
        raise RuntimeError(Database name has already been set.)

By the way, for this example, the simple if not __DBNAME__ test is adequate, because any string value other than an empty string will evaluate true, so any actual database name will evaluate true. But for variables that might contain a number value that might be 0, you cant just say if not variablename; in that case, you should explicitly test for None using the is operator. I modified the example to add an explicit None test. The explicit test for None is never wrong, so I default to using it.

Finally, as others have noted on this page, two leading underscores signals to Python that you want the variable to be private to the module. If you ever do an import * from mymodule, Python will not import names with two leading underscores into your name space. But if you just do a simple import mymodule and then say dir(mymodule) you will see the private variables in the list, and if you explicitly refer to mymodule.__DBNAME__ Python wont care, it will just let you refer to it. The double leading underscores are a major clue to users of your module that you dont want them rebinding that name to some value of their own.

It is considered best practice in Python not to do import *, but to minimize the coupling and maximize explicitness by either using mymodule.something or by explicitly doing an import like from mymodule import something.

EDIT: If, for some reason, you need to do something like this in a very old version of Python that doesnt have the global keyword, there is an easy workaround. Instead of setting a module global variable directly, use a mutable type at the module global level, and store your values inside it.

In your functions, the global variable name will be read-only; you wont be able to rebind the actual global variable name. (If you assign to that variable name inside your function it will only affect the local variable name inside the function.) But you can use that local variable name to access the actual global object, and store data inside it.

You can use a list but your code will be ugly:

__DBNAME__ = [None] # use length-1 list as a mutable

# later, in code:  
if __DBNAME__[0] is None:
    __DBNAME__[0] = name

A dict is better. But the most convenient is a class instance, and you can just use a trivial class:

class Box:

__m = Box()  # m will contain all module-level values
__m.dbname = None  # database name global in module

# later, in code:
if __m.dbname is None:
    __m.dbname = name

(You dont really need to capitalize the database name variable.)

I like the syntactic sugar of just using __m.dbname rather than __m[DBNAME]; it seems the most convenient solution in my opinion. But the dict solution works fine also.

With a dict you can use any hashable value as a key, but when you are happy with names that are valid identifiers, you can use a trivial class like Box in the above.

Explicit access to module level variables by accessing them explicity on the module

In short: The technique described here is the same as in stevehas answer, except, that no artificial helper object is created to explicitly scope variables. Instead the module object itself is given a variable pointer, and therefore provides explicit scoping upon access from everywhere. (like assignments in local function scope).

Think of it like self for the current module instead of the current instance !

import sys

# this is a pointer to the module object instance itself.
this = sys.modules[__name__]

# we can explicitly make assignments on it 
this.db_name = None

def initialize_db(name):
    if (this.db_name is None):
        # also in local function scope. no scope specifier like global is needed
        this.db_name = name
        # also the name remains free for local use
        db_name = Locally scoped db_name variable. Doesnt do anything here.
        msg = Database is already initialized to {0}.
        raise RuntimeError(msg.format(this.db_name))

As modules are cached and therefore import only once, you can import as often on as many clients as you want, manipulating the same, universal state:

import db

import db

if (db.db_name == mongo):
    db.db_name = None  # this is the preferred way of usage, as it updates the value for all clients, because they access the same reference from the same module object
from db import db_name
# be careful when importing like this, as a new reference db_name will
# be created in the module namespace of client_c, which points to the value 
# that db.db_name has at import time of client_c.

if (db_name == mongo):  # checking is fine if db.db_name doesnt change
    db_name = None  # be careful, because this only assigns the reference client_c.db_name to a new value, but leaves db.db_name pointing to its current value.

As an additional bonus I find it quite pythonic overall as it nicely fits Pythons policy of Explicit is better than implicit.

How to create module-wide variables in Python?

Stevehas answer was helpful to me, but omits an important point (one that I think wisty was getting at). The global keyword is not necessary if you only access but do not assign the variable in the function.

If you assign the variable without the global keyword then Python creates a new local var — the module variables value will now be hidden inside the function. Use the global keyword to assign the module var inside a function.

Pylint 1.3.1 under Python 2.7 enforces NOT using global if you dont assign the var.

module_var = /dev/hello

def readonly_access():

def readwrite_access():
    global module_var
    module_var = /dev/hello2

Leave a Reply

Your email address will not be published. Required fields are marked *