Luke Taylor Luke Taylor - 5 months ago 9
Python Question

Modify namespace of importing script in Python

I'd like a function in my module to be able to access and change the local namespace of the script that's importing it. This would enable functions like this:

>>> import foo
>>> foo.set_a_to_three()
>>> a
3
>>>


Is this possible in Python?

Answer

An answer was generously provided by @omz in a Slack team:

import inspect
def set_a_to_three():
    f = inspect.currentframe().f_back
    f.f_globals['a'] = 3

This provides the advantage over the __main__ solution that it works in multiple levels of imports, for example if a imports b which imports my module, foo, foo can modify b's globals, not just a's (I think)

However, if I understand correctly, modifying the local namespace is more complicated. As someone else pointed out:

It breaks when you call that function from within another function. Then the next namespace up the stack is a fake dict of locals, which you cannot write to. Well, you can, but writes are ignored.

If there's a more reliable solution, that'd be greatly appreciated.