user1630350
user1630350

Reputation: 79

running functions via import in python

I have the following scripts:

the first is test1.py

x = 1

def test():

    globx = x
    print(globx)
    globx += 1
    return globx

x = test()

and the second is test2.py

import test1

z=3
while z != 0:
    if __name__=='__main__':
        test1.test()
        z -= 1
    else: 
        pass

I'm using these to learn and play about with calling functions from other scripts, what I want is the output:

1
2
3

but I get:

1
2
2
2

when I replace the

    globx = x
    print(globx)
    globx += 1
    return globx

x = test()

in test1.py with

global x 
print(x) 
x += 1

I do get the desired outcome but apparently you shouldn't use global variables so it's a habit I'd like to break.

I have 2 questions.

  1. Why do I get the wrong output and
  2. Why are there 4 outputs when I use the globx = x version of test1.py instead of 3?

Upvotes: 1

Views: 74

Answers (2)

Uriel
Uriel

Reputation: 16174

Why do I get the wrong output?

When you import test1 is runs for the first time, executing test for the first time and assigning it to x, printing 1 and incrementing x.

Then you execute test another 3 times inside test2, but without updating x, so test will set globx with x, print x and update globx, yet leaving x untouched (stuck on 2).

Why are there 4 outputs?

You set z to 3, then count to 0. z = 3, 2, 1, 0 OVER!. So you execute for z = 1..3, resulting in 3 times + the time that executes inside test1 itself, when loaded.

How to fix?

On test1.py:

Use global x for all actions. Don't run test:

x = 1

def test():
    global x
    print(x)
    x += 1

On test2.py:

Iterate 3 times with range. Your else: pass would trigger infinite loop if the module was run by another one:

import test1

if __name__ == '__main__':
    for _ in range(3):
        test1.test()

Upvotes: 2

DYZ
DYZ

Reputation: 57033

When you import test1, the whole script is executed. The function test() is called for the first time. It prints 1 and changes x to 2. Then you call test1.test() three times in the loop. globx is a local variable. It is printed three times (2) and changed three times to 3, but the changes are not saved.

Upvotes: 0

Related Questions