在iPython交互式命名空间中提供来自导入模块的函数变量 [英] Making function variables from imported module available in iPython interactive namespace
问题描述
我想知道如何从IPython交互命名空间中可用的导入模块中的函数创建变量。
I want to know how to make variables from functions in imported modules available in the IPython interactive namespace.
我有一些示例代码,我想从另一个运行脚本所以我把它设置为run_test.py:
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()
如何在交互式命名空间中使用变量'a'?我能做到的唯一方法是将'a'设为全局并直接运行run_test.py而不是导入它并调用该函数。
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.
任何指针都值得赞赏。
推荐答案
我相信这可以通过返回 locals
然后更新本地人来实现。
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).
这篇关于在iPython交互式命名空间中提供来自导入模块的函数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!