使变量有条件地全局化

时间:2017-08-16 19:18:03

标签: python python-2.7 global-variables

假设我需要运行一个带循环的函数,直到遇到条件。为了使函数正常工作,我只允许在函数中返回一个值,但是一旦条件清除,我想将我执行的一些计算带入全局范围。我不允许使用return命令来执行此操作,因此我决定全局化变量 in post 。这提出了一个警告,但似乎工作正常。这是最好的做事方式吗?

以下是一个例子:

def check_cond(x,cond):
    return (x - cond,3)

def loop(x,func):
    relevant_value = 0
    while x > 0:
        local_expensive_calculation = 1 #use your imagination
        x = func(x,local_expensive_calculation)[0]
        relevant_value += func(x,local_expensive_calculation)[1]
        if x == 0:
            global local_expensive_calculation
    return relevant_value

x = 4
loop(x,check_cond)

#then do stuff with local_expensive_calculation, which is now global

2 个答案:

答案 0 :(得分:1)

这可能会略微滥用系统,但您可以将变量设置为函数的属性,然后通过该命名空间访问它:

def check_cond(x,cond):
    return (x - cond,3)

def loop(x,func):
    relevant_value = 0
    while x > 0:
        local_expensive_calculation = 1 #use your imagination
        x = func(x,local_expensive_calculation)[0]
        relevant_value += func(x,local_expensive_calculation)[1]
        if x == 0:
            loop.local_expensive_calculation = local_expensive_calculation
    return relevant_value

x = 4
loop(x,check_cond)

print loop.local_expensive_calculation

答案 1 :(得分:0)

如果你绝对坚持将其作为一种全球性的方式,你可以通过改变这条线来实现这一目标:

global local_expensive_calculation

为:

globals()['local_expensive_calculation'] = local_expensive_calculation

它使你的SyntaxWarning消失。

我对上下文了解不多,看起来你想要Python 2.7答案(Python 3?)有nonlocal

请记住while statement can also have a else clause

你可以写:

while x>0:
    # do calculation and stuff
else:
    # make calculation result global

PS:您在x的作业中输入了一个拼写错误:(calcuation - > calculation