Python: modifying enclosing variable in function
Are there any ways to modify the enclosing variables with functions written outside of the main function?
I want to do this:
def modify_a():
nonlocal a
a =+ 1
def process_abc(some_criteria):
a, b, c = generate(some_criteria)
modify_a()
return a, b, c
a, b, c = process_abc()
I tried the following, but I wonder if there's a way to make the above work. If there's any, is it bad coding practice?
def modify_a(a=a):
a =+ 1
def process_abc(some_criteria):
a, b, c = generate(some_criteria)
a = modify_a(a)
return a, b, c
a, b, c = process_abc()
Solution 1:
The only way to do it is by modifying the parent frame.
Either way, this is a very bad idea. Functions are a form of encapsulation.
If you wish to modify the parent data, you can pass a mutable structure like so:
def modify_a(a=a):
a[0] =+ 1
def process_abc(some_criteria):
a, b, c = generate(some_criteria)
a= [a]
a = modify_a(a)[0]
return a, b, c
a, b, c = process_abc()
It is generally frowned upon though.