Is it possible to modify a variable in python that is in an outer (enclosing), but not global, scope?
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]
Accessing a variable from outer scope via global keyword in Python
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
How to change variable in function scope from inner function
Use nonlocal to modify variables outside the scope of the function.
def sample():
a = False
def sample2():
nonlocal a
a = True
sample2()
return a
Modify variable in scope of a function in another function in the same scope (Python)
You must replace global
to nonlocal
.
global variable in python that doesn't make change in sub function
The global result was outside the scope.
number = int(input("enter your first num: "))
operation = input("enter your operation: ")
second_number = int(input("enter your second num: "))
def cal(num1, op, num2):
def add():
result = num1+num2
return result
def multiply():
result = num1 * num2
return result
def devide():
if not num2 == 0:
result = num1 / num2
return result
else:
result = 'num2 can\'t be zero'
return result
def default():
print("Incorrect option")
switch = {
'+': add,
'*': multiply,
'/': divide
}
return switch.get(op, default)()
print(cal(number, operation, second_number))
Python program that uses global
def method():
# Change "value" to mean the global variable.
# ... The assignment will be local without "global."
global value
value = 100
value = 0
method()
# The value has been changed to 100.
print(value)
100`
Python program that uses nonlocal
def method():
def method2():
# In nested method, reference nonlocal variable.
nonlocal value
value = 100
# Set local.
value = 10
method2()
# Local variable reflects nonlocal change.
print(value)
# Call method.
method()
100
Python - Change variable outside function without return
Here's a simple (python 2.x) example of how to 1 not use globals and 2 use a (simplistic) domain model class.
The point is: you should first design your domain model independently from your user interface, then write the user interface code calling on your domain model. In this case your UI is a Tkinter GUI, but the same domain model should be able to work with a command line UI, a web UI or whatever.
NB : for python 3.x, replace Tkinter
with tkinter
(lowercase) and you can get rid of the object
base class for Model
.
import random
from Tkinter import *
class Model(object):
def __init__(self):
self.currentMovie = 0
def UpdateCurrentMovie(self):
self.currentMovie = random.randint(0, 100)
print(self.currentMovie)
def UpdateWatched(self):
print(self.currentMovie)
def ExampleWithArgs(self, arg):
print("ExampleWithArg({})".format(arg))
def main():
model = Model()
root = Tk()
root.title("MovieSelector9000")
root.geometry("900x600")
app = Frame(root)
app.grid()
canvas = Canvas(app, width = 300, height = 75)
canvas.pack(side = "left")
button1 = Button(canvas, text = "SetRandomMovie", command=model.UpdateCurrentMovie)
button2 = Button(canvas, text = "GetRandomMovie", command=model.UpdateWatched)
button3 = Button(canvas, text = "ExampleWithArg", command=lambda: model.ExampleWithArgs("foo"))
button1.pack(anchor = NW, side = "left")
button2.pack(anchor = NW, side = "left")
button3.pack(anchor = NW, side = "left")
root.mainloop()
if __name__ == "__main__":
main()
keep a variable not-local but not global in python 3
You are assigning to x
, which means that Python defaults to x
being a local.
Explicitly tell Python it is nonlocal
instead:
def bam(x):
def paw():
nonlocal x
x+=1
print(x)
def bang():
nonlocal x
x+=1
print(x)
return paw, bang
Related Topics
Typeerror: Can Only Concatenate Str (Not "Float") to Str
What Is the Fastest Way to Open Urls in New Tabs via Selenium - Python
Fill Username and Password Using Selenium in Python
Writing to Existing Workbook Using Xlwt
Why Does This Not Work as an Array Membership Test
How to Get a Complete List of Object's Methods and Attributes
How to Manage Third-Party Python Libraries with Google App Engine? (Virtualenv? Pip)
Get Name of Current Script in Python
How to Implement the Softmax Function in Python
Pandas Index Column Title or Name
Configuring So That Pip Install Can Work from Github
How to Implement a Binary Tree
How to Handle a Broken Pipe (Sigpipe) in Python
Plotting 3D Polygons in Python-Matplotlib
How to Import Members of All Modules Within a Package