Create function variables from an imported module in the iPython interactive namespace

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

I have an example code that I want to run from another script, so I set it 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 to make the variable 'a' available in the interactive namespace? The only way to do this is to make "a" global and run run_test.py directly, rather than importing it and calling the function.

Any pointers appreciated.

+1
source share
1 answer

I believe this can be achieved by returning locals and then updating the local networks.

 def main(): # do things return locals() if __name__ == '__main__': new_locals = main() locals().update(new_locals) 

This seems to work, although it seems to be hacking, so perhaps it is not always.

A reasonable example of where you want it: If you want to access all the variables in the function namespace, but do not want these function variables to be accessible to other parts of the script (i.e. other function definitions).

0
source

Source: https://habr.com/ru/post/1208189/


All Articles