rp0 rp0 - 1 year ago 51
Python Question

Making a variable conditionally global

Suppose that I'm required to run a function with a loop in it until I meet a condition. For the function to work right, I'm only allowed to return one value in the function, but once the condition clears, I want to bring some of the calculations I performed into the global scope. I'm not allowed to use the return command to do this, so I decided to globalize the variables in post. This raises a warning, but seems to work alright. Is this the best way to do things?

Here's an example:

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

Answer Source

This may be slightly abusing the system but you can set your variable as an attribute of the function, and then access it later through that namespace:

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download