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.

Answer from Paul Stephenson on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_variables_global.asp
Python - Global Variables
Global variables can be used by everyone, both inside of functions and outside. Create a variable outside of a function, and use it inside the function · x = "awesome" def myfunc(): print("Python is " + x) myfunc() Try it Yourself »
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.)

Discussions

Is there a way to make a variable global to all functions?
Sounds like you maybe want a class instead. All functions would be implemented as methods on the class that can all access the class instance's variables. More on reddit.com
🌐 r/learnpython
18
0
April 22, 2025
How to make variables global by default, Python 3.11
So if I want to use them in a function I have to use the global prefix/keyword. # In main block. myvar = '' # Here's my function. def myfunc(): global myvar myvar = "hi" return myvar print(myfunc()) in Python 3.11 is there a way to make all these variables global by default. I ... More on discuss.python.org
🌐 discuss.python.org
0
June 10, 2024
Why not use global variables?
They add unneeded complexity and doubt into your code. Imagine you have a variable at the start of your program called "really_important" now imagine your code is 50,000 lines long and somewhere in there you import another module that also has a "really_important" global. Imagine trying to figure out which one is which, when they're used, when they're being modified, by whom, etc. Scope is a very powerful organizational tool. It helps you (and your IDE) remember what is important for any piece of code. For example: x = 0 y = 0 def add_x_y(): return x + y In the above you need to remember that this adds x and y together and inside the function you have zero assurance that x and y are even set. Contrasted with: def add_x_y(x, y): return x + y Not only is this shorter, the function prototype tells you exactly what you need to give it (two things named x and y), your IDE will helpfully provide you with insight about it, and the error you receive if you failed to define x or y properly will make a lot more sense. More on reddit.com
🌐 r/learnpython
31
21
July 27, 2021
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
June 25, 2022
🌐
Python documentation
docs.python.org › 3 › tutorial › modules.html
6. Modules — Python 3.14.3 documentation
Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode). A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__.
🌐
DEV Community
dev.to › veer66 › global-variables-in-python-are-not-that-global-280j
Global Variables in Python Are Not That Global - DEV Community
December 13, 2025 - As you can see, a global variable in Bash is truly global across files. In Python, however, a global variable is only global within its module, i.e., file.
🌐
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 Python, global variables are accessible across your entire program, including within functions. Understanding how Python handles global variables is key to writing efficient code.
Find elsewhere
🌐
Squash
squash.io › how-to-use-global-variables-in-a-python-function
How to Use Global Variables in a Python Function
Global variables in Python are variables that are defined outside of any function and can be accessed from anywhere in the program. While global variables can be convenient, their use should be approached with caution as they can lead to code ...
🌐
Python.org
discuss.python.org › python help
How to make variables global by default, Python 3.11 - Python Help - Discussions on Python.org
June 10, 2024 - So if I want to use them in a function I have to use the global prefix/keyword. # In main block. myvar = '' # Here's my function. def myfunc(): global myvar myvar = "hi" return myvar print(myfunc()) in Python 3.11 is there a way to make all these variables global by default. I ...
🌐
Vultr Docs
docs.vultr.com › python › built-in › globals
Python globals() - Access Global Variables | Vultr Docs
September 27, 2024 - The globals() function in Python is instrumental for accessing global variables within a program. This function returns a dictionary of the current global symbol table, which is always available from any point in the Python code.
🌐
GitHub
github.com › pyenv › pyenv
GitHub - pyenv/pyenv: Simple Python version management · GitHub
December 27, 2025 - You can use the pyenv shell command to set this environment variable in your current shell session. The application-specific .python-version file in the current directory (if present). You can modify the current directory's .python-version file with the pyenv local command. The first .python-version file found (if any) by searching each parent directory, until reaching the root of your filesystem. The global $(pyenv root)/version file.
Starred by 44.4K users
Forked by 3.2K users
Languages   Shell 86.9% | Python 10.8% | Makefile 1.5% | C 0.4% | Roff 0.2% | Dockerfile 0.2%
🌐
GeeksforGeeks
geeksforgeeks.org › python › global-local-variables-python
Global and Local Variables in Python - GeeksforGeeks
To modify a global variable use the global keyword. ... Explanation: Inside fun(), Python assumes s is local since we try to modify it.
Published   September 20, 2025
🌐
Reddit
reddit.com › r/learnpython › why not use global variables?
r/learnpython on Reddit: Why not use global variables?
July 27, 2021 -

I have people telling me to avoid using global variables in my functions. But why should I?

Top answer
1 of 14
40
They add unneeded complexity and doubt into your code. Imagine you have a variable at the start of your program called "really_important" now imagine your code is 50,000 lines long and somewhere in there you import another module that also has a "really_important" global. Imagine trying to figure out which one is which, when they're used, when they're being modified, by whom, etc. Scope is a very powerful organizational tool. It helps you (and your IDE) remember what is important for any piece of code. For example: x = 0 y = 0 def add_x_y(): return x + y In the above you need to remember that this adds x and y together and inside the function you have zero assurance that x and y are even set. Contrasted with: def add_x_y(x, y): return x + y Not only is this shorter, the function prototype tells you exactly what you need to give it (two things named x and y), your IDE will helpfully provide you with insight about it, and the error you receive if you failed to define x or y properly will make a lot more sense.
2 of 14
12
Global variables are not universially bad. It is absolutely fine to use global variables for constants, values that are not changed during the execution of the program. The thing that people (rightfully) warn about is writing to or modifying the values of global variables from functions as a means of sharing state between them or writing to global variables read by functions as means of passing data to them. Ideally, a function should be self-contained: it interacts with its environment only via the arguments it was passed and the value it returns. That has two distinct advantages: The function (and the program as a whole) is less prone to errors, since each function's behaviour is determined only by the code within it and the well-defined interface it has to other code via the calling mechanism. For example, if you have multiple active calls of the same function or set of functions, either due to multithreading or recursion, functions that share state globally can easily result in unwanted, hard-to-debug behaviour. It makes the function more reusable, since it is not entangled with the state of other unrelated functions or application-specific code. Say, you realise later in your project that you need to solve a problem you have already written a function for someplace else. It is that much easier just to directly reuse the existing function if you do not have to worry about the other code that surrounds it. That said, there are legitimate uses even for non-constant global variables. The issue is that those uses are highly specific/advanced. The things that beginner or intermediate programmers tend to use global variables for are not such legitimate uses, hence the oft repeated mantra of "global variables bad" you see in this sub.
🌐
Python documentation
docs.python.org › 3 › reference › datamodel.html
3. Data model — Python 3.14.3 documentation
The difference between a code object and a function object is that the function object contains an explicit reference to the function’s globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time).
🌐
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.
🌐
FastAPI
fastapi.tiangolo.com › advanced › events
Lifespan Events - FastAPI
Doing that in separated functions that don't share logic or variables together is more difficult as you would need to store values in global variables or similar tricks.
🌐
WsCube Tech
wscubetech.com › resources › python › global-variable
Global Variable in Python: Explained With Examples
February 10, 2026 - Learn about global variables in Python with examples in this tutorial. Understand how to use and manage them effectively in your Python code.
🌐
Python.org
discuss.python.org › python help
How to handle 'global' variables? - Python Help - Discussions on Python.org
May 8, 2024 - Hi, Newby question here. I’m creating a program that traverses a directory tree using os.walk. Each directory in that tree is checked for a distinct text file, the text file is opened, and the contents searched for image filenames & urls. I want to keep track of the total number of text files that were found, and the number of image filenames & URLs found in those text files.
🌐
Intellipaat
intellipaat.com › home › blog › how to use a global variable in a function in python?
How to Use a Global Variable in a Function in Python? - Intellipaat Blog
May 26, 2025 - Using a global variable in a function allows you direct access with the global keyword. It can also be passed as an argument to the function. Another option is to store it in structures like dictionaries or objects for easier handling.