Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing scope in Python between called and calling functions

Tags:

python

scope

Is there a way in Python to manage scope so that variables in calling functions are visible within called functions? I want something like the following

z = 1

def a():
    z = z * 2
    print z

def b():
    z = z + 1
    print z
    a()
    print z

b()

I would like to get the following output

2
4
2

The real solution to this problem is just to pass z as a variable. I don't want to do this.

I have a large and complex codebase with users of various levels of expertise. They are currently trained to pass one variable through and now I have to add another. I do not trust them to consistently pass the second variable through all function calls so I'm looking for an alternative that maintains the interface. There is a decent chance that this isn't possible.

like image 618
MRocklin Avatar asked Feb 04 '13 17:02

MRocklin


1 Answers

This is a bit ugly, but it avoids using globals, and I tested it and it works. Using the code from the selected answer found here, the function getSetZ() has a "static" variable that can be used to store a value that is passed to it, and then retrieved when the function is called with None as the parameter. Certain restrictions are that it assumes None is not a possible value for z, and that you don't use threads. You just have to remember to call getSetZ() right before each call to a function that you want the calling function's z to be available in, and to get the value out of getSetZ() and put it in a local variable in that function.

def getSetZ(newZ):
    if newZ is not None:
        getSetZ.z = newZ
    else:
        return getSetZ.z

def a():
    z = getSetZ(None)
    z = z * 2
    print z

def b():
    z = getSetZ(None)
    z = z + 1
    print z
    getSetZ(z)
    a()
    print z

getSetZ.z = 0
getSetZ(1)
b()

I hope this helps.

like image 78
jonhopkins Avatar answered Oct 07 '22 07:10

jonhopkins