In Python 3.x this is possible:

def f1():
        x = 5
        def f2():
                nonlocal x
                x+=1
        return f2

The problem and a solution to it, for Python 2.x as well, are given in this post. Additionally, please read PEP 3104 for more information on this subject.

Answer from hochl on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-inner-functions
Python Inner Functions - GeeksforGeeks
May 22, 2026 - Example 2: This example shows how the nonlocal keyword allows the inner function to modify a variable from the outer function instead of creating a new local copy. ... Explanation: nonlocal tells Python to use the variable a from the outer scope ...
Discussions

How to change outer function local variables from an inner function in Python? - Stack Overflow
Possible Duplicate: Modify the function variables frominner function in python Say I have this python code def f(): x=2 def y(): x+=3 y() this raises: UnboundLocalError: l... More on stackoverflow.com
🌐 stackoverflow.com
Is it possible to modify a variable in python that is in an outer (enclosing), but not global, scope? - Stack Overflow
This is odd that class with its fields is "visible" in an inner function but variables are not, unless you define outer variable with the "nonlocal" keyword. 2018-02-02T13:01:28.657Z+00:00 ... Setting a key on a dictionary initialized in the outer scope also works. 2021-08-23T08:43:52.713Z+00:00 ... Save this answer. ... Show activity on this post. I'm a little new to Python... More on stackoverflow.com
🌐 stackoverflow.com
scope - Python overwriting variables in nested functions - Stack Overflow
Is it possible to modify a variable in python that is in an outer (enclosing), but not global, scope? (9 answers) Closed 3 years ago. ... def outer(): string = "" def inner(): string = "String was changed by a nested function!" inner() return string More on stackoverflow.com
🌐 stackoverflow.com
Modify the function variables from inner function in python - Stack Overflow
It's ok to get and print the outer function variable a def outer(): a = 1 def inner(): print a It's also ok to get the outer function array a and append something def outer(): ... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

How can an inner function change a variable from its parent function in Python
ANS: In Python 3, you can use the nonlocal keyword. For older versions or alternative approaches, you can use mutable objects like lists, pass variables explicitly as arguments, or use classes to manage state.
🌐
sqlpey.com
sqlpey.com › python › python-nested-functions-modify-outer-scope
Python Nested Functions Modify Outer Scope Variable Solutions
Can nested functions modify global variables
ANS: Yes, nested functions can modify global variables by using the global keyword. However, this affects the module-level scope and is generally not the preferred way to modify variables in an enclosing function’s scope.
🌐
sqlpey.com
sqlpey.com › python › python-nested-functions-modify-outer-scope
Python Nested Functions Modify Outer Scope Variable Solutions
Why does direct assignment in a nested function fail with UnboundLocalError
ANS: The UnboundLocalError occurs because Python, upon seeing an assignment in a function, assumes the variable is local. If the variable is also used before assignment within that same local scope (e.g., x = x + 1), Python raises this error as the local variable is referenced before it’s assigned. The nonlocal keyword resolves this by indicating the variable exists in an outer scope.
🌐
sqlpey.com
sqlpey.com › python › python-nested-functions-modify-outer-scope
Python Nested Functions Modify Outer Scope Variable Solutions
🌐
Learn By Example
learnbyexample.org › python-variables-scope
Python Variables Scope - Learn By Example
April 20, 2020 - The x inside the nested function now refers to the x outside the function, so changing x inside the function changes the x outside it. The usage of nonlocal is very similar to that of global, except that the former is primarily used in nested ...
Find elsewhere
🌐
Python Tutorial
pythontutorial.net › home › advanced python › python nonlocal
Python nonlocal Scopes and nonlocal Variables
March 27, 2025 - Since the scope of the outer function ... scopes of inner functions are called nonlocal scopes. Use the nonlocal keyword to modify the variable from the nonlocal scopes....
🌐
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 - Within the inner_function, we use the nonlocal keyword to access and modify the variable x in the outer local scope.
🌐
sqlpey
sqlpey.com › python › python-nested-functions-modify-outer-scope
Python Nested Functions Modify Outer Scope Variable Solutions
July 25, 2025 - By default, when you assign a value to a variable within a function, Python assumes you are creating or modifying a variable local to that function. This means an inner function cannot directly change a variable in the outer scope through simple assignment.
🌐
Reddit
reddit.com › r/learnpython › scopes in nested functions
r/learnpython on Reddit: scopes in nested functions
May 22, 2024 -

Is there a command like global or nonlocal with which I can make x=10 in my_nested_nested_function?
With global x it gets 1, with nonlocal it gets 100. If i comment the line where I set x to 100 in my_nested_function then the print statement puts out 10 (Which would be a workaround). But is there a way if I had to use the variable in my_nested_function?

x = 1
def my_function():
x = 10
def my_nested_function():
x = 100
def my_nested_nested_function():
nonlocal x
print(x)
my_nested_nested_function()
my_nested_function()
my_function()

Top answer
1 of 4
2
See here for how to format code on reddit: https://www.reddit.com/r/learnpython/wiki/faq#wiki_how_do_i_format_code.3F It is impossible to read your code without proper formatting, but this demonstrates how variables are found multiple levels of nesting: def foo(): """Outer Function.""" x = 10 y = 10 def nested(): """Function nested in foo().""" y = 100 def nested_in_nested(): """Function nested in nested().""" nonlocal x nonlocal y # Search 'up' the levels for x and y. print(f'In nested_in_nested(): {x=} {y=}') # Modify x and y x += 1 y += 1 # Cannot modify y # Call nested_in_nested() from inside nested(). nested_in_nested() print(f'In nested(): {x=} {y=}') # Call nested() from inside foo(). nested() print(f'In foo(): {x=} {y=}') x = 1 # Global foo() Which prints: In nested_in_nested(): x=10 y=100 In nested(): x=11 y=101 In foo(): x=11 y=10 In the first printed line: In nested_in_nested(), the variable y is found in nested(), so y=100 is printed. It is then incremented. The variable x is not found in nested(), so Python looks next in the enclosing function foo() and finds x there. x=10 is printed. It is then incremented The nonlocal keyword allows a function to modify variables from the nearest enclosing scope that is not global. y in the outer function foo() is not modified by y = 100 in nested() because y in nested() is local to nested(). In the second printed line, notice that 'y' from the local scope of nested() has been incremented to 101, and x from the outer scope foo() has been incremented to 11. In the third printed line, the local x has been incremented The local y has not been incremented because that was not the instance of y accessed by y += 1 in nested_in_nested(). DO NOT WRITE CODE LIKE THIS. Python emphasises readability and this kind of code is horrible to read.
2 of 4
2
Nested functions are best used when you need to repeat some code that only appears in your function. Since python's functions are closures, you can access variables from the outer scope just fine, which is handy. However, as soon as you want to modify one of those variables, you should think long and hard about whether this is the right way to do things. The keywords global and nonlocal are both good indications that you're doing something wrong. They are extremely rare in production code. This is for good reason, allowing variables to be modified outside of the scope they were defined in is a terrible idea and makes debugging so much more difficult when you accidentally set them to something wrong (and this will happen). You should also avoid reusing the same variable name when the previous variable is still visible. If there's one variable called x already available, do not create a new one inside a function with the same name. This also makes debugging errors harder, and can cause problems when you think you're referring to one variable, but it turns out you're actually referring to a different object that has the same name.
🌐
Reddit
reddit.com › r/learnpython › inner functions cannot access outer variable if it is primitive, why exactly is it like this?
r/learnpython on Reddit: Inner functions cannot access outer variable if it is primitive, why exactly is it like this?
November 26, 2021 -

Take this function as an example:

def foo(self, param1):

count = 0
buffer = []

def inner(x):

buffer.append(x + param1)
count += 1

inner(5)

So, the inner function can freely access param1 and buffer. However, it will complain about count, and in order to make it work, you need to declare "nonlocal count".

I was wondering why is this the case, how is the stack organized such that param1 and buffer is accessible without the need to declare nonlocal, but for count, it needs a nonlocal declaration? I'm guessing it has something to do with it being a primitive... but then again, so is param1

Top answer
1 of 3
3

First off, in this simple case you could return the desired value from inner() and assign it when calling inner(). But let's assume that this is a simplified example, and that you are in fact changing multiple variables, or returning inner somewhere else where it will be called multiple times and need to reexamine its variable.

In Python 3 you can declare variab as nonlocal, which would allow you to change it. In Python 2, the only way is to switch to mutating an object with state freshly created on each call to outer. For example, using a list:

def outer():
    variab = [""]
    #some code including, presumably, a call to inner()

    def inner():
        # some code
        variab[0] = "new_value"

    print variab[0]

Nicer variants of this can be achieved, e.g. by making variab contain a dict or a Python instance with mutable __dict__. An elegant idiom is to use the __dict__ of the inner function itself as the container:

def outer():
    def inner():
        # some code
        inner.variab = "new_value"

    inner.variab = ""
    #some code including, presumably, a call to inner()    
    print inner.variab
2 of 3
2

The cleanest way to do this is explicitly:

def outer():
    variab = ""
    #some code

    def inner(variab):
        # some code
        variab = "new_value"
        return variab

    variab = inner(variab)

    print variab

Now you don't have to worry about scoping, can test inner in isolation, etc. It is clear to the reader that inner requires access to variab to do its thing, and that variab may be different after the call.

See PEP-0020: "Explicit is better than implicit"; and "Readability counts".

🌐
PW Skills
pwskills.com › blog › python › python-inner-function
Python Inner Function
January 29, 2026 - As we mentioned, access is usually read-only. But what if you actually need to change the value? To Python inner function modify outer variable data, you can't just assign a new value.
🌐
TutorialsPoint
tutorialspoint.com › How-do-nested-functions-work-in-Python
How do nested functions work in Python?
September 28, 2023 - The following program changes the value of a variable inside the nested function (inner function) − · # creating an outer function def outerFunc(): sample_str = 'Hello tutorialspoint python' # creating an inner function def innerFunc(): # modifying the sample string sample_str = 'Welcome' print(sample_str) # calling an inner function inside the outer function innerFunc() print(sample_str) # calling outer function outerFunc()
🌐
Telusko
docs.telusko.com › docs › python › more-on-functions › inner-function
Inner Function - Python
January 28, 2026 - When an inner function is returned, it forms a closure, meaning: It remembers and can access variables from the outer function even after the outer function has finished execution. To modify outer variables, use the nonlocal keyword.
🌐
Python.org
discuss.python.org › python help
Nested function has an issue with a variable - Python Help - Discussions on Python.org
June 21, 2023 - I’m messing around with making some art with Turtle Graphics, and I made a nested function with a variable to create a shape when it’s called. I first tried to create a variable and assign it a value of 60 in the function, and also tried moving it out of the function, as it keeps giving me the error “defined in enclosing scope referenced before assignment” and I don’t know why.
🌐
Stack Abuse
stackabuse.com › python-nested-functions
Python Nested Functions
December 21, 2018 - The inner function is able to access the variables that have been defined within the scope of the outer function, but it cannot change them. There are a number of reasons as to why we may need to create an inner function. For instance, an inner function is protected from what happens outside it.