Simplicity.
Simplicity.

Reputation: 1

Unusual problem with multiple return in Python

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) 

Upvotes: 0

Views: 120

Answers (2)

ine
ine

Reputation: 14084

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.

Upvotes: 2

Cat Plus Plus
Cat Plus Plus

Reputation: 129804

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.

Upvotes: 4

Related Questions