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

Defintion of global variables in Cython
Hi, I have a main python file (main.py) which declares a variable W as follows: W = main.py imports a cython file 'my_lib.pyx" consisting of multiple cdef or cpdef functions that use or modify this W. Note that W mayโ€ฆ More on discuss.python.org
๐ŸŒ discuss.python.org
0
0
May 15, 2023
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
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
0
June 10, 2024
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
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-define-global-variables-in-python-modules-398175
How to define global variables in Python modules | LabEx
As a result, it's generally recommended ... In Python, global variables can be defined at the module level, which allows them to be accessed by multiple functions or classes within the same module....
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ glossary.html
Glossary โ€” Python 3.14.3 documentation
Note that nested scopes by default work only for reference and not for assignment. Local variables both read and write in the innermost scope. Likewise, global variables read and write to the global namespace.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Defintion of global variables in Cython - Python Help - Discussions on Python.org
May 15, 2023 - Hi, I have a main python file (main.py) which declares a variable W as follows: W = main.py imports a cython file 'my_lib.pyx" consisting of multiple cdef or cpdef functions that use or modify this W. Note that W mayโ€ฆ
Find elsewhere
๐ŸŒ
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.
๐ŸŒ
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 โ€บ 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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-use-access-a-global-variable-in-a-function-python
How to use/access a Global Variable in a function - Python - GeeksforGeeks
July 23, 2025 - In Python, variables declared outside of functions are global variables, and they can be accessed inside a function by simply referring to the variable by its name.
๐ŸŒ
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 ...
๐ŸŒ
Temp Mail
tempmail.us.com โ€บ temp mail โ€บ blog โ€บ python โ€บ global variable utilization in python functions
Global Variable Utilization in Python Functions
July 24, 2024 - The script illustrates how shared_value is changed by several functions by calling multiply_value(5) and add_value(3); the final value is printed at the end. These examples highlight how crucial the global keyword is for accessing and changing global variables in Python across several functions.
๐ŸŒ
Conda
docs.conda.io โ€บ projects โ€บ conda โ€บ en โ€บ stable โ€บ user-guide โ€บ tasks โ€บ manage-environments.html
Managing environments โ€” conda 26.1.1 documentation
Environment variables set using conda env config vars will be retained in the output of conda env export. Further, you can declare environment variables in the environment.yml file as shown here: name: env-name channels: - conda-forge - defaults dependencies: - python=3.7 - codecov variables: VAR1: valueA VAR2: valueB
๐ŸŒ
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 ...
๐ŸŒ
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
๐ŸŒ
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.
๐ŸŒ
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.