Jared
Jared

Reputation: 3

Python global variable is not working as expected

I'm just starting out with Python and experimenting with different solutions. I was working with global variables and I ran into something but don't know why it's doing what it's doing.

To start, I have two modules: test1 and test2. test1 is as follows:

import test2
num = 0
def start():
    global num
    num = num + 5
    print 'Starting:'
    print num
    test2.add()
    print 'Step 1:'
    print num
    test2.add()
    print 'Step 2:'
    print num

And test2 is this:

import test1
def add():
    test1.num = test1.num + 20

When I run test1.start() the output is:

Starting:
5
Step 1:
25
Step 2:
45

Why doesn't test2 need the global declaration to modify the variable in test1? Line 5 in test1 requires it at line 4, but if I remove both it still works (0, 20,40). I'm just trying to figure out why it's not working as I expected it to.

Thanks.

Upvotes: 0

Views: 677

Answers (2)

Ryan N
Ryan N

Reputation: 669

From test2's perspective, test1.num is a variable belonging to the module test1.

The global keyword only specifics that the scoping for that variable is module-level (i.e. not local).

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798666

The global declaration is not for modifying the name, it's for rebinding it. Since you are accessing the name via its module what you are doing is modifying the module.

Upvotes: 4

Related Questions