0

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()
1
  • a is in no sense an "enclosing variable" here. You'd have to actually put the definition of modify_a inside the definition of process_abc() for that to be true. Commented Jan 17, 2022 at 16:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.