How to create module-wide variables in Python? [duplicate]

Is there a way to set up a global variable inside of a module? When I tried to do it the most obvious way as appears below, the Python interpreter said the variable __DBNAME__ did not exist.

...
__DBNAME__ = None

def initDB(name):
    if not __DBNAME__:
        __DBNAME__ = name
    else:
        raise RuntimeError("Database name has already been set.")
...

And after importing the module in a different file

...
import mymodule
mymodule.initDB('mydb.sqlite')
...

And the traceback was:


UnboundLocalError: local variable ‘DBNAME‘ referenced before assignment

Any ideas? I’m trying to set up a singleton by using a module, as per this fellow’s recommendation.

5 Answers
5

Leave a Comment