Functions are added to the current namespace like any other name would be added. That means you can use the global keyword inside a function or method:

Copydef create_global_function():
    global foo
    def foo(): return 'bar'

The same applies to a class body or method:

Copyclass ClassWithGlobalFunction:
    global spam
    def spam(): return 'eggs'

    def method(self):
        global monty
        def monty(): return 'python'

with the difference that spam will be defined immediately as top-level class bodies are executed on import.

Like all uses of global you probably want to rethink the problem and find another way to solve it. You could return the function so created instead, for example.

Demo:

Copy>>> def create_global_function():
...     global foo
...     def foo(): return 'bar'
... 
>>> foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> create_global_function()
>>> foo
<function foo at 0x102a0c7d0>
>>> foo()
'bar'
>>> class ClassWithGlobalFunction:
...     global spam
...     def spam(): return 'eggs'
...     def method(self):
...         global monty
...         def monty(): return 'python'
... 
>>> spam
<function spam at 0x102a0cb18>
>>> spam()
'eggs'
>>> monty
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'monty' is not defined
>>> ClassWithGlobalFunction().method()
>>> monty()
'python'
Answer from Martijn Pieters on Stack Overflow
🌐
Quora
quora.com › How-can-you-create-or-use-a-global-variable-in-a-function-in-Python
How to create or use a global variable in a function in Python - Quora
Answer (1 of 11): With care. There is rarely a time when globals are neccessary (in any language - not just in Python). As a beginner (which I assume you are) they are a short cut, but they are a bad habit to get into. As you progress, you will realize that using global have the following effect...
Top answer
1 of 4
46

Functions are added to the current namespace like any other name would be added. That means you can use the global keyword inside a function or method:

Copydef create_global_function():
    global foo
    def foo(): return 'bar'

The same applies to a class body or method:

Copyclass ClassWithGlobalFunction:
    global spam
    def spam(): return 'eggs'

    def method(self):
        global monty
        def monty(): return 'python'

with the difference that spam will be defined immediately as top-level class bodies are executed on import.

Like all uses of global you probably want to rethink the problem and find another way to solve it. You could return the function so created instead, for example.

Demo:

Copy>>> def create_global_function():
...     global foo
...     def foo(): return 'bar'
... 
>>> foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> create_global_function()
>>> foo
<function foo at 0x102a0c7d0>
>>> foo()
'bar'
>>> class ClassWithGlobalFunction:
...     global spam
...     def spam(): return 'eggs'
...     def method(self):
...         global monty
...         def monty(): return 'python'
... 
>>> spam
<function spam at 0x102a0cb18>
>>> spam()
'eggs'
>>> monty
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'monty' is not defined
>>> ClassWithGlobalFunction().method()
>>> monty()
'python'
2 of 4
12

You can use global to declare a global function from within a class. The problem with doing that is you can not use it with a class scope so might as well declare it outside the class.

Copyclass X:
  global d
  def d():
    print 'I might be defined in a class, but I\'m global'

>> X.d

   Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   AttributeError: 'X' object has no attribute 'd'

>> d()

I might be defined in a class, but I'm global
Discussions

Why would one define "global variables" in python functions? How to use these correctly?
Imma just quote Code Complete, page 338, "Reasons to Use Global Data" Used with discipline, global variables are useful in several situations: Preservation of global values Sometimes you have data that applies conceptually to your whole program. This might be a variable that reflects the state of a program—for example, interactive vs. command-line mode, or normal vs. error-recovery mode. Or it might be information that’s needed throughout a program—for example, a data table that every routine in the program uses. Emulation of named constants Although C++, Java, Visual Basic, and most modern languages support named constants, some languages such as Python, Perl, Awk, and UNIX shell script still don’t. You can use global variables as substitutes for named constants when your language doesn’t support them. For example, you can replace the literal values 1 and 0 with the global variables TRUE and FALSE set to 1 and 0, or you can replace 66 as the number of lines per page with LINES_PER_PAGE = 66. It’s easier to change code later when this approach is used, and the code tends to be easier to read. This disciplined use of global data is a prime example of the distinction between programming in vs. programming into a language, which is discussed more in Section 34.4, “Program into Your Language, Not in It.” Emulation of enumerated types You can also use global variables to emulate enumerated types in languages such as Python that don’t support enumerated types directly. Streamlining use of extremely common data Sometimes you have so many references to a variable that it appears in the parameter list of every routine you write. Rather than including it in every parameter list, you can make it a global variable. However, in cases in which a variable seems to be accessed everywhere, it rarely is. Usually it’s accessed by a limited set of routines you can package into a class with the data they work on. More on this later. Eliminating tramp data Sometimes you pass data to a routine or class merely so that it can be passed to another routine or class. For example, you might have an error-processing object that’s used in each routine. When the routine in the middle of the call chain doesn’t use the object, the object is called “tramp data.” Use of global variables can eliminate tramp data. That said, most of the chapter is dedicated to why you should NOT use global data and how to avoid doing so... Most experienced programmers have concluded that using global data is riskier than using local data. Most experienced programmers have also concluded that access to data from several routines is pretty useful. Even if global variables don’t always produce errors, however, they’re hardly ever the best way to program. More on reddit.com
🌐 r/learnpython
23
23
December 31, 2017
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 can't imported functions access global variables?
“Global” is something of a misnomer; symbols defined in top-level scope are actually only in module scope. There actually aren’t global variables in Python the way you might expect that to mean. Ultimately the key is to write functions that don’t depend on global state. More on reddit.com
🌐 r/learnpython
6
4
December 24, 2018
Question about AWS Lambda, python, and globals

The code that sets the global variable will be evaluated once per Execution Context when your module is imported. After that, the value of the variable is in memory and there's no need to calculate it again.

More on reddit.com
🌐 r/Python
2
2
March 15, 2017
🌐
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 »
🌐
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 that's difficult to understand, debug, and maintain.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python global variables in function
Python Global Variables in Function - Spark By {Examples}
May 31, 2024 - In Python, variables that can be accessed from different parts of your code are known as global variables. They can be declared outside of a function or within a function using the global keyword.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-globals-function
Python - globals() function - GeeksforGeeks
April 28, 2025 - In Python, the globals() function is used to return the global symbol table - a dictionary representing all the global variables in the current module or script. It provides access to the global variables that are defined in the current scope.
Find elsewhere
🌐
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.
🌐
O’Reilly Media
oreilly.com › o'reilly › radar › in python, can i create a global variable inside a function and then use it in a different function?
In Python, can I create a global variable inside a function and then use it in a different function?
September 8, 2016 - In this hands-on tutorial David Blaikie explains the creation of global variables within functions, as well as the associated risks and caveats. Python beginners with a basic knowledge of variable assignment will further their understanding of variable scoping, which is essential to proper code design in Python.
🌐
Dive into Python
diveintopython.org › home › learn python programming › functions in python › global and local variables
Global Variables in Python Functions - How to Use, Set and Update
May 3, 2024 - A global scope means that a variable is accessible throughout the program, while a local scope means that a variable is accessible only within the function where it is defined. ... In Python, global variables can be accessed and modified from ...
🌐
Reddit
reddit.com › r/learnpython › why would one define "global variables" in python functions? how to use these correctly?
r/learnpython on Reddit: Why would one define "global variables" in python functions? How to use these correctly?
December 31, 2017 -

I am looking at some legacy code whereby the author often defines global variables within the functions with global. I have rarely seen this done, and I'm not sure it's been done correctly.

Let's take a concrete example: https://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them

globvariable = 0

def maketheglobalvariable1():
    global globalvariable
    globvariable = 1

def printglobvariable():
    print(globvariable) 

maketheglobalvariable1()

Here's it's clear that a variable has been defined outside any functions, and then a global variable was defined within a function in over to overwrite it when the function is called.

But when would there be a time to define global variables in python? These seem to be superfluous, no?

Any examples/resources to better help me understand this topic are greatly appreciated :)

Top answer
1 of 5
12
Imma just quote Code Complete, page 338, "Reasons to Use Global Data" Used with discipline, global variables are useful in several situations: Preservation of global values Sometimes you have data that applies conceptually to your whole program. This might be a variable that reflects the state of a program—for example, interactive vs. command-line mode, or normal vs. error-recovery mode. Or it might be information that’s needed throughout a program—for example, a data table that every routine in the program uses. Emulation of named constants Although C++, Java, Visual Basic, and most modern languages support named constants, some languages such as Python, Perl, Awk, and UNIX shell script still don’t. You can use global variables as substitutes for named constants when your language doesn’t support them. For example, you can replace the literal values 1 and 0 with the global variables TRUE and FALSE set to 1 and 0, or you can replace 66 as the number of lines per page with LINES_PER_PAGE = 66. It’s easier to change code later when this approach is used, and the code tends to be easier to read. This disciplined use of global data is a prime example of the distinction between programming in vs. programming into a language, which is discussed more in Section 34.4, “Program into Your Language, Not in It.” Emulation of enumerated types You can also use global variables to emulate enumerated types in languages such as Python that don’t support enumerated types directly. Streamlining use of extremely common data Sometimes you have so many references to a variable that it appears in the parameter list of every routine you write. Rather than including it in every parameter list, you can make it a global variable. However, in cases in which a variable seems to be accessed everywhere, it rarely is. Usually it’s accessed by a limited set of routines you can package into a class with the data they work on. More on this later. Eliminating tramp data Sometimes you pass data to a routine or class merely so that it can be passed to another routine or class. For example, you might have an error-processing object that’s used in each routine. When the routine in the middle of the call chain doesn’t use the object, the object is called “tramp data.” Use of global variables can eliminate tramp data. That said, most of the chapter is dedicated to why you should NOT use global data and how to avoid doing so... Most experienced programmers have concluded that using global data is riskier than using local data. Most experienced programmers have also concluded that access to data from several routines is pretty useful. Even if global variables don’t always produce errors, however, they’re hardly ever the best way to program.
2 of 5
4
Sometimes it's a cheap way to do a singleton. Here's an example from some code I've been using lately. import gzip from pickle import load DATA = None def get_training_data(): global DATA if DATA is None: DATA = load(gzip.open('./artifacts/train-tensor.pkl.gz')) return DATA Then I can import this module, and the first time get_training_data() is called the data is loaded, but on subsequent calls the in-memory version is used. Saves time when working with an interactive shell.
🌐
Sentry
sentry.io › sentry answers › python › use global variables in python functions
Use global variables in Python functions | Sentry
March 15, 2023 - Each function that uses a global variable must declare it with the global keyword before using it.
🌐
Python documentation
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.3 documentation
2 weeks ago - This function executes arbitrary code. Calling it with untrusted user-supplied input will lead to security vulnerabilities. The source argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the ...
🌐
Simplilearn
simplilearn.com › home › resources › software development › python global variables | definition, scope and examples
Python Global Variables | Definition, Scope and Examples
September 9, 2025 - Python global variables explained! Learn how to declare, modify and use them effectively while understanding their scope, limitations and best practices.
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
freeCodeCamp
freecodecamp.org › news › global-variable-in-python-non-local-python-variables
Global Variable in Python – Non-Local Python Variables
June 10, 2022 - To make it possible for x to be accessible outside its local scope, we declared it using the global keyword: global x. After that, we assigned a value to x. We then called the function we used to declare it: X()
🌐
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 ...
🌐
Mooc
programming-25.mooc.fi › part-6 › 4-scope-of-variables
Local and global variables - Python Programming MOOC 2025
Variables defined within the main function are global variables. We previously defined the main function as those sections of code in a Python program which do not fall within any other function.
🌐
Takeuforward
takeuforward.org › python › python-global-keyword
Python Global Keyword - Tutorial
takeuforward is the best place to learn data structures, algorithms, most asked coding interview questions, real interview experiences free of cost.
🌐
LabEx
labex.io › home › builtin › globals
Python globals() built-in function - Python Cheatsheet
# Define a global variable global_var = "I am global" def my_function(): # Access global variables using globals() global_dict = globals() print(global_dict["global_var"]) # Modify a global variable global_dict["global_var"] = "Modified global" my_function() print(global_var)
🌐
Oreate AI
oreateai.com › blog › understanding-the-globals-function-in-python-a-deep-dive › 8addbb9fe9cc15294d1a25fa6c11f90b
Understanding the Globals Function in Python: A Deep Dive - Oreate AI Blog
January 15, 2026 - Explore Python's globals() function and understand how it interacts with variable management across different namespaces in programming.
🌐
Real Python
realpython.com › courses › global-variables-in-python-functions
Working With Global Variables in Python Functions – Real Python
May 22, 2025 - In this video course, 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 that's difficult to understand, debug, and maintain.