Is there a way to declare that a function should use the scope of the caller?

Archop :

is there a feautre similar to C macros which lets you reuse code in an inline manner, without creating a seperate scope for that piece of code?

for example:

a=3
def foo():
    a=4
foo()
print a

will print 3, however i want it to print 4.

i am aware of solutions involving objects like classes or a global dict, however i'm looking for a more primitive solution (like a function decorator for example) that would simply let me make changes inside the scope of the caller instead.

thank you very much

edit:any solution that requires declaring which variables i'm going to use OR declaring a "namespace" like mutabale objects beforehand is not a solution i'm looking for.

jsbueno :

In this case, just use the global keyword:

a=3
def foo():
    global a
    a=4
foo()
print (a)

That modifies the outer scope, if it is global.

If the outer scope is a function, that is done with the nonlocal keyword instead - which was introduced with Python 3.0.

dynamic scoping

Changing the scope of the caller function however, is not a premise of Python, and is a language characteristic.

It can be done. But just by calling private C api's (to bake 'locals' values back into the fast local variables) and is definettely not a good practice.

DOing it through a magic decorator would also be possible, but the decorator would have to rewrite the bytecode in the inner function - by replacing each access to a 'nonlocal' variable by retrieving and updating the value on the caler locals, and, at the end of the function - https://programtalk.com/python-examples/ctypes.pythonapi.PyFrame_LocalsToFast/

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=397555&siteId=1