0

When I call the function "G()" which returns two values: p_T and q_T twice (see below) but using the same style, that's, P_T, neg = G(); U, Ign = G() and print sums of P_T and U, I get two different answers! Another thing is that both answers are incorrect!

I have only included part of the code which can simply aid in explaining the idea. The block of statements within the function G() under the for loop is executed N times as the loop suggests. Is there something being compromised by global variables declaration?

Any suggestion of what is wrong and how to fix it is appreciated!

def G():
    global p_T; global q_T

    for n in range(N):
        p_T = U_T(EvolveU_T(p_T))
        q_T = V_T(EvolveV_T(q_T))

    return p_T, q_T

P_T, neg = G()
print sum(P_T)
U, Ign = G()
print sum(U) 
3
  • @Liutauras there is no reason to double space the code. Commented Aug 22, 2011 at 16:32
  • 2
    there is no way for us to help without knowing what ?_T and Evolve?_T are. Also, please rewrite your title, "Multiple return" doesn't make any sense. Commented Aug 22, 2011 at 16:33
  • in general, don't use so many global variables. why? because you end up with strange bugs like this... Commented Aug 22, 2011 at 16:41

2 Answers 2

4

You have global state. You mutate global state. Then you mutate it again, starting where you left off. So P_T is a result after N operations, and U is a result after 2N operations.

Don't use global state.

Sign up to request clarification or add additional context in comments.

Comments

2

Because p_T and q_T are globals, their scope is not local to the function. So it's no surprise that you get two different answers after calling the function twice. Here's a simple example that demonstrates what's going on:

class C:
    foo = ''

    def __repr__(self):
        return self.foo

x, y = C(), C()

def F():
    global x
    global y

    x.foo += 'x'
    y.foo += 'y'

    return (x, y)

print F()
print F()

The globals x and y maintain their values because they are not scoped to the function. If they were declared and initialized inside the function without the global modifiers, you'd see (x, y) twice. But instead you see:

(x, y)
(xx, yy)

Generally globals are considered bad programming practice as they can lead to a confusing amount of state which is not localized to the function under consideration, as you've discovered.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.