On Python 3, use the nonlocal keyword:
The
nonlocalstatement 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 OverflowOn Python 3, use the nonlocal keyword:
The
nonlocalstatement 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]
You can use an empty class to hold a temporary scope. It's like the mutable but a bit prettier.
def outer_fn():
class FnScope:
b = 5
c = 6
def inner_fn():
FnScope.b += 1
FnScope.c += FnScope.b
inner_fn()
inner_fn()
inner_fn()
This yields the following interactive output:
>>> outer_fn()
8 27
>>> fs = FnScope()
NameError: name 'FnScope' is not defined
Is it possible to modify variable in python that is in outer, but not global, scope? - Stack Overflow
What is the better way to change a variable from outside a function in a function?
Creating or modify function variable from outer scope python - Stack Overflow
scopes in nested functions
Can nested functions modify global variables
How can an inner function change a variable from its parent function in Python
What are the advantages of using a class to manage scope for nested functions
On Python 3, use the nonlocal keyword:
The
nonlocalstatement 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]
You can use an empty class to hold a temporary scope. It's like the mutable but a bit prettier.
def outer_fn():
class FnScope:
b = 5
c = 6
def inner_fn():
FnScope.b += 1
FnScope.c += FnScope.b
inner_fn()
inner_fn()
inner_fn()
This yields the following interactive output:
>>> outer_fn()
8 27
>>> fs = FnScope()
NameError: name 'FnScope' is not defined
def generic_function(x, y):
x += 1 y += 1
x = 1
y = 2
generic_function(x, y)
print(x, y)
Above the variables x and y do not change because generic_function creates local variables x and y.
But I learned I could do that this way:
def generic_function():
list\[0\] += 1 list\[1\] += 1
list = [1, 2]
generic_function()
print(list[0], list[1])
A list can be used as parameters to the function, so the generic_function will modify the list that the name list refers to. And so no unwanted local variables are created.
But it seems strange to make your program search in a list for a value so many times, is there any other way to do it? Why couldn't I change which value the name x refers to directly?
uisng non local params
def main():
def egg():
nonlocal a
print(a)
#egg() # NameError: name 'a' is not defined **As excepted**
a = 50
egg()
main()
output
50
Callable class can be used to replicate this sort of behaviour without breaking the encapsulation of a function.
class Egg:
def __init__(self, a):
self.a = a
def __call__(self):
print(self.a)
egg = Egg(50)
egg() # 50
egg.a = 20
egg() # 20
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()
global only works within the module it's used in. You also don't use global to declare a global variable at the global scope (ie. the module scope). You would use global within the scope of a function to indicate that you want to use a variable in the global scope and not in the local scope.
In python 3, there is also the nonlocal keyword that allows you to indicate you want to modify a variable in an outer scope that isn't the global/module scope.
global
A = 1
def global_func():
global A
A = 2
def func():
A = 3
print(A)
# 1
global_func()
print(A)
# 2
func()
print(A)
# 2
nonlocal
def outside():
a = 1
def inside_nonlocal():
nonlocal a
a = 2
def inside():
a = 3
print(a)
# 1
inside_nonlocal()
print(a)
# 2
inside()
print(a)
# 2
I am not clear what your problem actually is. Is it not possible to do the following?
import backend
if __name__ == "__main__":
# parse arguments
backend.argreceive(arguments)
As Daniel Roseman suggested, if there are many backend functions requiring access to these variables then you should consider using a class, and class properties, to store the variables.
class argreceive():
def __init__(self,args):
self.args = args
Define the variables outside of the functions and use the global keyword.
s, n = "", 0
def outer():
global n, s
n = 123
s = 'qwerty'
modify()
def modify():
global n, s
s = 'abcd'
n = 456
Sometimes I run across code like this. A nested function modifies a mutable object instead of assigning to a nonlocal:
def outer():
s = [4]
def inner():
s[0] = 5
inner()