简体   繁体   English

捕获并返回功能范围

[英]Capture and return function scope

Question

How do I automate a function to return all variables defined inside its scope? 如何使函数自动化以返回其作用域内定义的所有变量?

Motivation 动机

When using Python for scientific work my scripts tend to be very linear (algorithm like) but quite long. 当使用Python进行科学工作时,我的脚本往往非常线性(类似于算法),但是很长。 When working interactively with the script I want to keep the calculated variables to further explore or use them. 与脚本交互工作时,我想保留计算出的变量以进一步探索或使用它们。

I could just skip using a main() function inside my scripts and do everything globally. 我可以跳过在脚本中使用main()函数的操作,然后全局执行所有操作。 However that would prohibit behavior like in the example below and prohibit me from modifying the script from an interactive python console prior to execution. 但是,这将禁止以下示例中的行为,并禁止我在执行之前从交互式python控制台修改脚本。

Example

Inside script.py : 内部script.py

def main(c):
    a, b = 1, 2
    # long function body with lots of variables...
    return parse_scope()

Inside the interactive console: 在交互式控制台中:

>>> import script
>>> script.main(c=3)
{'a': 1, 'b': 2, 'c': 3}

parse_scope() captures the function scope and returns it as a dict, list,... parse_scope()捕获函数范围,并将其作为字典,列表等返回。

Ideas 思路

def main(c):
    a, b = 1, 2
    # long function body with lots of variables...
    return {name: eval(name) for name in dir()}

Gives NameError: name 'a' is not defined . 给出NameError: name 'a' is not defined

After writing this question I found the answer: 写下此问题后,我找到了答案:

def main(c):
    a, b = 1, 2
    # long function body with lots of variables...
    return locals()

seems to do the trick. 似乎可以解决问题。

My previous example doesn't work because eval(expression, globals=None, locals=None) would need to be given a scope with a , b , c . 我的上一个示例不起作用,因为eval(expression, globals=None, locals=None)需要使用abc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM