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 foo.py, containing this single line:

X = 1

Now imagine you import it.

import foo
print(foo.X)  # prints 1

However, let's suppose you want to use one of your module-scope variables as a global inside a function, as in your example. Python's 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
    else:
        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 can't 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 from mymodule import *, 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 won't care, it will just let you refer to it. The double leading underscores are a major clue to users of your module that you don't 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 doesn't 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 won't 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:
    pass

__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 don't 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.

Answer from steveha on Stack Overflow
Top answer
1 of 5
334

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 foo.py, containing this single line:

X = 1

Now imagine you import it.

import foo
print(foo.X)  # prints 1

However, let's suppose you want to use one of your module-scope variables as a global inside a function, as in your example. Python's 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
    else:
        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 can't 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 from mymodule import *, 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 won't care, it will just let you refer to it. The double leading underscores are a major clue to users of your module that you don't 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 doesn't 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 won't 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:
    pass

__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 don't 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.

2 of 5
136

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


In short: The technique described here is the same as in steveha's 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 !

# db.py
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. Doesn't do anything here."
    else:
        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 db.py as often on as many clients as you want, manipulating the same, universal state:

# client_a.py
import db

db.initialize_db('mongo')
# client_b.py
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
# client_c.py
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" doesn't 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.

๐ŸŒ
Real Python
realpython.com โ€บ python-use-global-variable-in-function
Using and Creating Global Variables in Your Python Functions โ€“ Real Python
December 8, 2024 - In this tutorial, you'll learn how to use global variables in Python functions using the global keyword or the built-in globals() function. You'll also learn a few strategies to avoid relying on global variables because they can lead to code ...
Discussions

Global variables shared across modules
Hello to all Pythonians here. I encountered a strange behavior about the global keyword and modules, which I cannot understand. Module test1: Variable a is created Module test2: Module test1 is imported, and function f is created, which modifies variable a through the global keyword Module ... More on discuss.python.org
๐ŸŒ discuss.python.org
0
0
June 25, 2022
python - How to make a cross-module variable? - Stack Overflow
The __debug__ variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it? The variable (let's be original and call i... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How can I use a global variable in a function? - Stack Overflow
How do I create or use a global variable inside a function? How do I use a global variable that was defined in one function inside other functions? Failing to use the global keyword where appropri... More on stackoverflow.com
๐ŸŒ stackoverflow.com
August 25, 2021
How do I create global variables I can use across my modules?
I import scene from file sceneSetup.js into initFloor1.js and get error ReferenceError: scene is not defined Can't find solution of this issue and can't understand if it is the issue of javascript or More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Finxter
blog.finxter.com โ€บ how-to-use-global-variables-in-a-python-function
How to Use Global Variables In a Python Function? โ€“ Be on the Right Side of Change
October 9, 2020 - Summary: Use the global keyword to declare a global variable inside the local scope of a function so that it can be modified or used outside the function as well. To use global variables across modules create a special configuration module and import the module into our main program.
๐ŸŒ
Quora
quora.com โ€บ How-will-you-share-variables-across-modules-in-Python
How will you share variables across modules in Python? - Quora
All this makes NetworkX especially well suited to analyzing complex social networks. ... RelatedHow do I create modules in Python where a variable will be accessible to all the modules (variable accessible means I can use values present in a variable in other modules)? ... Python s/w developer since 2011 - published since 2015 ยท Author has 13.3K answers and 23.8M answer views ยท Updated 6y ... Note that func1 needs to declare my_global as a global variable (line 8) in order to be able to change it.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-do-i-share-global-variables-across-modules-in-python
How do I share global variables across modules in Python?
September 19, 2022 - To form it as a global i.e. a global variable accessible from everywhere as shown in the above example, just import the config module in all modules of your application ? ... By importing the module in all the modules, the module then becomes available as a global name.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_variables_global.asp
Python - Global Variables
Create a variable outside of a ... Try it Yourself ยป ยท If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function....
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Global variables shared across modules - Python Help - Discussions on Python.org
June 25, 2022 - Hello to all Pythonians here. I encountered a strange behavior about the global keyword and modules, which I cannot understand. Module test1: Variable a is created Module test2: Module test1 is imported, and function f is created, which modifies variable a through the global keyword Module test3: Modules test1 and test2 are imported, f is called, and a is printed.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ faq โ€บ programming.html
Programming FAQ โ€” Python 3.14.3 documentation
The same thing happens when you use import foo, and then try to access foo.foo_var in global code. There are (at least) three possible workarounds for this problem. Guido van Rossum recommends avoiding all uses of from <module> import ..., and placing all code inside functions. Initializations of global variables and class variables should use constants or built-in functions only.
Find elsewhere
Top answer
1 of 16
5288

You can use a global variable within other functions by declaring it as global within each function that assigns a value to it:

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print(globvar)     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

Since it's unclear whether globvar = 1 is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the global keyword.

See other answers if you want to share a global variable across modules.

2 of 16
932

If I'm understanding your situation correctly, what you're seeing is the result of how Python handles local (function) and global (module) namespaces.

Say you've got a module like this:

# sample.py
_my_global = 5

def func1():
    _my_global = 42

def func2():
    print _my_global

func1()
func2()

You might be expecting this to print 42, but instead, it prints 5. As has already been mentioned, if you add a 'global' declaration to func1(), then func2() will print 42.

def func1():
    global _my_global 
    _my_global = 42

What's going on here is that Python assumes that any name that is assigned to, anywhere within a function, is local to that function unless explicitly told otherwise. If it is only reading from a name, and the name doesn't exist locally, it will try to look up the name in any containing scopes (e.g. the module's global scope).

When you assign 42 to the name _my_global, therefore, Python creates a local variable that shadows the global variable of the same name. That local goes out of scope and is garbage-collected when func1() returns; meanwhile, func2() can never see anything other than the (unmodified) global name. Note that this namespace decision happens at compile time, not at runtime -- if you were to read the value of _my_global inside func1() before you assign to it, you'd get an UnboundLocalError, because Python has already decided that it must be a local variable but it has not had any value associated with it yet. But by using the 'global' statement, you tell Python that it should look elsewhere for the name instead of assigning to it locally.

(I believe that this behavior originated largely through optimization of local namespaces -- without this behavior, Python's VM would need to perform at least three name lookups each time a new name is assigned to inside a function (to ensure that the name didn't already exist at module/builtin level), which would significantly slow down a very common operation.)

๐ŸŒ
Great Learning
mygreatlearning.com โ€บ blog โ€บ it/software development โ€บ global variables in python
Global Variables in Python
August 15, 2024 - It's important to note that if ... errors. Therefore, always use the global keyword to explicitly declare global variables when you intend to modify them within a function or class method....
๐ŸŒ
Index.dev
index.dev โ€บ blog โ€บ how-to-set-global-variables-python
How to Set Global Variables Across Modules in Python
February 27, 2025 - Setting global variables across modules in Python can be done in multiple ways, from simple imports to using the singleton pattern. The best approach depends on your use case. If you need a quick solution, using a separate config module works well.
๐ŸŒ
Net Informations
net-informations.com โ€บ python โ€บ iq โ€บ global.htm
Global and Local Variables in Python - Net-Informations.Com
How to share a global variable across python modules, it is better to use a single module to hold all the global variables you want to use and whenever you want to use them, just import this module, and then you can modify that and it will be visible in other modules that do the same.
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ python global variables
Python Global Variable โ€“ PYnative
October 21, 2022 - First, create a special module config.py and create global variables in it. Now, import the config module in all application modules, then the module becomes available for a global name.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-15034.html
change value of a global variable across all modules
hello I wrote a minimum working example showing what I am unable to achieve: I have a variable in one.py called foo, i would like to change it's value and then use the new value accross all modules one.py import two foo = 'a' def main(): two...
๐ŸŒ
Codingdeeply
codingdeeply.com โ€บ home โ€บ python global variables across files: how to share data between modules
Python Global Variables Across Files: How to Share Data Between Modules
February 23, 2024 - In the example above, we declare the variable x as global inside the function foo using the global keyword. This allows us to modify the global variable x from within the function and update its value to 5. The output of the print statement ...
๐ŸŒ
Codedamn
codedamn.com โ€บ news โ€บ javascript
Javascript Global Variables-How to create and access them in JS
September 17, 2023 - One way is to define it as a property of the window object. Then we can reference it as foo or window.foo anywhere in our code. window.foo = 1;Code language: JavaScript (javascript) Another way is to use the var keyword in the top level of our code.
๐ŸŒ
Byby
byby.dev โ€บ js-global-variables
How to use global variables in JavaScript
// webpack.config.js const webpack = require("webpack"); module.exports = { // ... plugins: [ new webpack.DefinePlugin({ FOO: JSON.stringify("bar"), // define a global constant }), ], }; // module1.js console.log(FOO); // use the global constant // will log "bar" It is generally recommended to avoid or minimize the use of global variables in JavaScript, and follow some best practices, such as: