On Python 3, use the nonlocal keyword:

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

def foo():
    a = 1
    def bar():
        nonlocal a
        a = 2
    bar()
    print(a)  # Output: 2

On Python 2, use a mutable object (like a list, or dict) and mutate the value instead of reassigning a variable:

def foo():
    a = []
    def bar():
        a.append(1)
    bar()
    bar()
    print a

foo()

Outputs:

[1, 1]
Answer from Adam Wagner on Stack Overflow
🌐
Wordpress
unspecified.wordpress.com › 2008 › 06 › 27 › py3k-nonlocal
Py3K: Solving the “outer scope” problem | Unspecified Behaviour
July 1, 2008 - As with global variables, Python can find outer scope variables if you only read them (as inner_read does), but if you write to them anywhere in the function, it assumes you are making a new local variable (as inner_write does).
Discussions

Why can I access some variables from the outer scope but not others
You're calling a function to append to the array, whereas on the string you're just modifying it, in which case you need to declare it as global in your function. You should be able to access it by doing print(string) as it currently stands, just not modify it. More on reddit.com
🌐 r/learnpython
5
0
October 23, 2021
Accessing the outer scope in Python 2.6 - Stack Overflow
However, there are some options ... in the outer scope: Use globals. By the way, func.__globals__ is a mutable dictionary ;) Store variables in a dict/class-instance/any other mutable container · Give variables as arguments & get them back as a tuple: a,b,c = innerfunc(a,b,c) Inject other function's bytecode. This is possible with byteplay python ... More on stackoverflow.com
🌐 stackoverflow.com
Being able to use a non-local variable inside a local scope without referencing as a parameter?
If you assign to a name anywhere inside a function python considers that name to be local to the function. Just referencing (not assigning to) a non-local name inside a function works fine. Look at this tutorial . More on reddit.com
🌐 r/learnpython
9
0
August 2, 2022
Is it bad practice to use variables in functions that are not defined in parameters
Yes, you can use variables defined in the global scope also within functions. You cannot, however, directly use variables defined inside of a main function inside other functions, unless those functions themselves are defined locally inside that main function. In general, you can access variables from all scopes that surround the function definition (provided they are not shadowed by a variable of the same name that's more local), and that's how most programming languages work. In Python, it's constrained by default to reading accesses, but you can also assign to such variables via the use of the global and nonlocal keywords. Some examples: a = 1 # Defined in global scope def test(): print(a) # Local access to global variable def outer(): b = 2 def inner(): print(b) # Reading access to variable in surrounding function scope. def assign(): global a # Required, otherwise below assignment creates a new local variable instead a = 3 # Assigning to global variable The use of global variables within functions is considered bad practice, unless they are constants. Having a global variable with the value of pi, for example, that's then used in calculations within some functions but never changes, is fine. Using global variables to emulate parameters and return values or otherwise using it to share state between functions is usually very much frowned upon. Hence, the global and nonlocal keywords are only very rarely used in well written code. More on reddit.com
🌐 r/learnpython
10
2
March 18, 2022
🌐
Learn By Example
learnbyexample.org › python-variables-scope
Python Variables Scope - Learn By Example
April 20, 2020 - It allows you to assign to variables in an outer, but no-global, scope. Here’s an example that tries to reassign enclosing (outer) function’s local variable inside a nested (inner) function.
🌐
Python Tutorial
pythontutorial.net › home › advanced python › python nonlocal
Python nonlocal Scopes and nonlocal Variables
March 27, 2025 - When you use the nonlocal keyword for a variable, Python will look for the variable in the enclosing local scopes chain until it first encounters the variable name. More importantly, Python won’t look for the variable in the global scope. ... message = 'outer scope' def outer(): print(message) def inner(): nonlocal message message = 'inner scope' print(message) inner() print(message) outer()Copy
Find elsewhere
🌐
DataCamp
datacamp.com › tutorial › scope-of-variables-python
Python Variable Scope And The LEGB Rule Explained | DataCamp
September 11, 2025 - Scope is the region of code where a name is visible. When you use a name, Python looks it up in this order (LEGB): Local: the current function’s scope. Enclosing: any outer function scopes (for nested functions).
🌐
W3Schools
w3schools.com › python › python_scope.asp
Python Scope
The nonlocal keyword is used to work with variables inside nested functions. The nonlocal keyword makes the variable belong to the outer function.
🌐
Medium
medium.com › codex › legb-variable-scope-in-python-4d367142373b
LEGB — Variable Scope in Python. Local, Enclose, Global and Build-in | by Allie Hsu | CodeX | Medium
April 2, 2022 - For python, we could simply follow the LEGB rule that includes · Local, Enclose, Global, and Built-in. In this article, we will use a few examples to understand their feature and how to access objects of different scopes. ... There are three variables with the same name called x, which represent different scopes. x = 'global var'def outer(): # y is local variable for outer(), enclose variable for inner() x = 'enclose var' def inner(): x = 'local var' print('inner: {}'.format(x)) inner() print('outer: {}'.format(x))outer() print(x)) >>>>>>>>>>>>>>>>>>>>>>>>> inner local var outer enclose var global var
🌐
GeeksforGeeks
geeksforgeeks.org › python › accessing-python-function-variable-outside-the-function
Accessing Python Function Variable Outside the Function - GeeksforGeeks
July 23, 2025 - A closure allows a nested function to remember and access variables from its enclosing function even after execution. This method ensures encapsulation while avoiding global scope pollution. Closures are useful for maintaining state and are often used in callbacks and decorators. ... def outer_fun(): var = 42 def inner_fun(): return var return inner_fun # create a closure get_var = outer_fun() # accessing the function variable outside the function print(get_var())
🌐
freeCodeCamp
freecodecamp.org › news › global-variable-in-python-non-local-python-variables
Global Variable in Python – Non-Local Python Variables
June 10, 2022 - Variables defined inside functions are called local variables. Their value can only be used within the function where they are declared. You can change the scope of a local variable using the global keyword – which we'll discuss in the next section.
🌐
Python
peps.python.org › pep-3104
PEP 3104 – Access to Names in Outer Scopes | peps.python.org
October 12, 2006 - Within a block, an assignment to a name implies a declaration of a local variable only if it would not shadow a name already bound in an outer scope; otherwise assignment is interpreted as rebinding of the outer name.
🌐
Python
docs.python.org › 3 › faq › programming.html
Programming FAQ — Python 3.15.0 documentation
Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results. In the example above you can access the outer scope variable by declaring it global:
🌐
Alma Better
almabetter.com › bytes › tutorials › python › python-variable-scope
Variable Scope in Python
February 16, 2024 - Nonlocal may be a keyword in Python utilized to declare a variable as nonlocal (outside the current scope). This implies that the variable can be referenced and adjusted inside a nested function.
🌐
Medium
martinxpn.medium.com › python-variable-scope-30-100-days-of-python-c7f74c46c0a5
Python Variable Scope (30/100 Days of Python) | by Martin Mirakyan | Medium
April 10, 2023 - The outer_function has a variable x with a value of 10 in its local scope. Within the inner_function, we use the nonlocal keyword to access and modify the variable x in the outer local scope.
🌐
Readthedocs
python-textbok.readthedocs.io › en › 1.0 › Variables_and_Scope.html
Variables and scope — Object-Oriented Programming in Python 1 documentation
There is also a nonlocal keyword in Python – when we nest a function inside another function, it allows us to modify a variable in the outer function from inside the inner function (or, if the function is nested multiple times, a variable in one of the outer functions). If we use the global keyword, the assignment statement will create the variable in the global scope if it does not exist already.
🌐
Real Python
realpython.com › python-scope-legb-rule
Python Scope and the LEGB Rule: Resolving Names in Your Code – Real Python
July 16, 2026 - Use global names as constants that don’t change during your program’s execution. Up to this point, you’ve covered three different levels of scope in Python. Check out the following example for a summary of where they’re located in your code and how Python looks up names through them: ... >>> number = 42 >>> def outer_func(): ...
🌐
SaltyCrane
saltycrane.com › blog › 2008 › 01 › python-variable-scope-notes
Notes on Python variable scope - SaltyCrane Blog
January 9, 2008 - To set the global variable inside a function, I need to use the global statement. This declares the inner variable to have module scope. Now var remains 'bar' after the function is called. var = 'foo' def ex3(): global var var = 'bar' print 'inside the function var is ', var ex3() print 'outside the function var is ', var · inside the function var is bar outside the function var is bar · Scoping for nested functions works similarly. In the example below, the inner function can access both var_outer and var_inner.
🌐
CodingNomads
codingnomads.com › python-variable-scope
Python Variable Scope
There are two different scopes that you need to concern yourself with: ... You can have nested local scopes. A variable defined in an outer scope will be available in any inner scope unless the variable is defined again.