0

I would like to ask whether it is possible to change the scope of a function form the environment in which it was created to the environment where it is being called.

Example:

a = 1
def func():
    print(a)

func() returns 1. Now if I create the following function:

def exe():
    a = 3
    func()

exe() returns 1. I want to know whether it is possible to make exe() return 3 (without passing a as an argument).

Sandu Ursu
  • 1,181
  • 1
  • 18
  • 28
  • 3
    Yes, it's possible: you use the OS functions to look at the call stack, back up one frame, and fetch the variable `a` from there, instead of the from the semantic context. I don't recommend this, as it violates the basic design assumptions of the language. – Prune Sep 24 '19 at 21:34
  • 1
    Python is a lexically scoped language, it seems like you want dynamic scope. As stated by Prune, you can manually inspect the stack and do all sorts of black magic, but it is certainly not recommendable. – juanpa.arrivillaga Sep 24 '19 at 21:37
  • 1
    Related question [How to create dynamical scoped variables in Python?](https://stackoverflow.com/q/2001138/4996248). I thought that the most interesting answer there was in terms of `thread-local storage` -- not that I fully understood it. – John Coleman Sep 24 '19 at 22:51

0 Answers0