2

I have a code piece like this:

def A():
  def B():
    c.append("hello")
    d = 8

  c = []
  d = 0

  B()

  print(c, d)

I get this output:

["hello", 0]

I want to make function B reach c and d from function A. It reaches c because it is a list but i also want to reach d from B. Is there an easy way to do this?

4
  • You could return the value from your inner function, and use it in the outer function. You could also look into variable scope. Commented Apr 29, 2020 at 14:09
  • 1
    Yes, but i want to do this as easy as possible so nonlocal is easier Commented Apr 29, 2020 at 14:12
  • @Just_Me Just not easier to understand or maintain. Especially when your functions are larger than two lines and you do this with more than one variable. Commented Apr 29, 2020 at 14:19
  • You could also use a class and make c and d attributes of this class. Then any method would be allowed to update c and d without any "magic trick". Commented Apr 30, 2020 at 6:37

2 Answers 2

2

Declare d as nonlocal. This will make the cell "writable" from within the inner function.

c works because you're mutating the object in-place, however Python's "implicit declaration" (assigning to a variable) always declares names in the local scope. So when you try to update a non-local or global variable, what happens instead is that a variable of the same name is declared as a function local.

The global and nonlocal statements override this implicit declaration, and instead declare that the variable(s) of the specified name(s) are respectively global to the module or in some enclosing function scope rather than local to the function. Assignments will then "carry over" to the proper scope rather than implicitly cause the declaration of a local variable.

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

Comments

0

One easy Python3 approach would be directly accessing the function's local variable as below.

def A():
    def B():
        c.append("hello")
        A.d = 8  # <<

    c = []
    d = 0

    B()
    print(c, A.d)  # <<
A()

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.