Making function variables from imported module available in iPython interactive namespace

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-06 02:35:32

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/28432412/making-function-variables-from-imported-module-available-in-ipython-interactive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!