Sharing scope in Python between called and calling functions

python, scope

Solution

I think this is what you're looking for. If you control the inner functions, and the variable you're looking for is already in scope somewhere in the call chain, but you don't want your users to have to include the variable in the call itself. You clearly don't want the `global` keyword, because you don't want inner assignments to affect the outer scope.

Using the `inspect` module gets you access to the calling context. (But, be warned that it's somewhat fragile. You should probably use only for CPython unthreaded.)

import inspect

def calling_scope_variable(name):
  frame = inspect.stack()[1][0]
  while name not in frame.f_locals:
    frame = frame.f_back
    if frame is None:
      return None
  return frame.f_locals[name]

z = 1

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

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

b()

This does give the right answer of:

2
4
2

Problem

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.

Original source

Related problems