Skip to content
Advertisement

How to access Aʟʟ global variables in a function?

I’m trying to mimic the matlab load and save functions. I’m following this thread: Shelve Code gives KeyError

It is smart. However, if I write that code in a separate module, and try to import that module and invoke that function, then it can’t access the global variables.

Specifically, I write a happy.py and have the functions inside:

JavaScript

and when I try

JavaScript

It would not give save a and b.

Is this because global() would not give the objects outside the module? How can I do what I want to do then?

Advertisement

Answer

You can use inspect to look at the stack. This silly (poorly named function) that I’ve defined seems to do an OK job of picking up the global variables from the calling namespace although I haven’t tested it extensively. I am also unsure about whether it will work with different python implementations. (I mention this because the inspect.currentframe function is definitely implementation dependent). It seems to work OK with Cpython for what it’s worth.

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement