Oles Savluk Oles Savluk - 2 months ago 7
Python Question

Python share global variable only for functions inside of function

I have a function which will recursively execute another function inside and I want to share variable for all execution of that function.

Something like that:

def testglobal():
x = 0
def incx():
global x
x += 2
incx()
return x
testglobal() # should return 2


However, I'm getting error
NameError: name 'x' is not defined


There is hacky solution to make list and use first value of that list as
x
. But this is so ugly.

So how can I share
x
with
incx
function ? Or should I use completely different approach ?

Answer

You want to use the nonlocal statement to access x, which is not global but local to testglobal.

def testglobal():
  x = 0
  def incx():
    nonlocal x
    x += 2
  incx()
  return x
assert 2 == testglobal() 

The closest you can come to doing this in Python 2 is to replace x with a mutable value, similar to the argument hack you mentioned in your question.

def testglobal():
  x = [0]
  def incx():
    x[0] += 2
  incx()
  return x[0]
assert 2 == testglobal()

Here's an example using a function attribute instead of a list, an alternative that you might find more attractive.

def testglobal():
  def incx():
    incx.x += 2
  incx.x = 0
  incx()
  return inc.x
assert 2 == testglobal() 
Comments