我在 Python 和 Julia 中做了一个项目,并且在诸如(Julia 版本)之类的函数中有代码:
function foo(a,b)
c = a+b
#more code here
end
Run Code Online (Sandbox Code Playgroud)
或(Python 版本)
def foo(a,b):
c=a+b
#more code here
Run Code Online (Sandbox Code Playgroud)
然后我需要通过检查变量的值来测试这些函数(在函数范围内)。我想避免写print(variables)或return variables每次。有什么方法可以帮助我自动将所有变量传递到外部作用域,以便开发环境可以轻松检查它们?
在 Julia 中,您可以使用Base.@locals宏,例如:
function foo(a,b)
c = a+b
@show Base.@locals
end
Run Code Online (Sandbox Code Playgroud)
Base.@locals返回Dict带有所有局部变量的 a ,我在这里@show用来展示它。让我们运行一个测试:
julia> foo(10,15)
#= REPL[2]:3 =# Base.@locals() = Dict{Symbol, Any}(:a => 10, :b => 15, :c => 25)
Dict{Symbol, Any} with 3 entries:
:a => 10
:b => 15
:c => 25
Run Code Online (Sandbox Code Playgroud)
在 Python 中有一个非常相似的locals()函数,例如:
def foo(a,b):
c=a+b
print(locals())
Run Code Online (Sandbox Code Playgroud)
现在让我们测试一下:
>>> foo(10,15)
{'a': 10, 'b': 15, 'c': 25}
Run Code Online (Sandbox Code Playgroud)
如果您想将变量导出到 Julia 中的全局范围,您可以执行以下操作:
function foo(a,b)
c = a+b
Main.eval.(:($key = $value) for (key,value) in Base.@locals)
end
Run Code Online (Sandbox Code Playgroud)
这会将 的值复制a,b,c到Main范围:
julia> foo(200,300);
julia> a,b,c
(200, 300, 500)
Run Code Online (Sandbox Code Playgroud)
Python 没有元编程,但你可以这样做(@MisterMiyagi 建议):
globals().update(locals())
Run Code Online (Sandbox Code Playgroud)