1

I want to know how to make variables from functions in imported modules available in the IPython interactive namespace.

I have some example code which I want to run from another script so I set it up as run_test.py:

def run_test():
    a = 5

if __name__ == "__main__":
    run_test()

I import the module as follows and call the function:

import run_test
run_test.run_test()

How do I make variable 'a' available in the interactive namespace? The only way I can do it is to make 'a' a global and run run_test.py directly rather than importing it and calling the function.

Any pointers appreciated.

srossy
  • 11
  • 2
  • 1
    You can't - `a` is a local variable inside `run_test`, and is released as soon as that function ends. If you want `a` to be available outside `run_test`, you will need to *make that explicit* (e.g. with `global`). – jonrsharpe Feb 10 '15 at 13:06
  • Thanks @jonrsharpe that makes sense. I think I need to just run the script separately (execfile?) rather than incorporating it in to a function. – srossy Feb 10 '15 at 13:40
  • Why do you *want* to be able to access `a`? If you need the value after the function completes, `return` it. – jonrsharpe Feb 10 '15 at 13:41
  • I am reading multiple economic/market data series into csv files using several scripts. I have been running these scripts individually during development and also found it useful to have each series available in the IPython interactive namespace for testing/review. Now I want to save time by running one script which calls all the data reading scripts but still have each series available in the namespace. – srossy Feb 10 '15 at 22:42
  • Related/nearly identical question: http://stackoverflow.com/questions/26830141/dump-function-variables-to-workspace-in-python-ipython/41861891#41861891 – keflavich Jan 25 '17 at 21:24

1 Answers1

0

I believe this can be accomplished by returning locals and then updating locals.

def main():
    # do things
    return locals()

if __name__ == '__main__':
    new_locals = main()
    locals().update(new_locals)

This seems to work, though it feels like a hack, so perhaps it won't always.

A reasonable example of where you want this: If you want access to all the variables in a function's namespace, but don't want that function's variables accessible to other parts of a script (i.e., other function definitions).

keflavich
  • 18,278
  • 20
  • 86
  • 118