mazore
mazore

Reputation: 1024

When importing random number from module in two different files, why are they the same?

If I have a file foo.py, which contains

# foo.py
from random import randint

r = randint(0, 100)

And I have 2 other files, bar.py and main.py and we run main.py

# bar.py
from foo import r  # gets random number

bars_r = r
# main.py
from bar import bars_r
from foo import r  # gets random number, equal to random number from bar.py?

print(r == bars_r)  # True

I am confused at how r and bars_r can be equal in main.py. bar.py is importing r from foo.py, so my understanding is it runs foo.py, getting a random number which we can set to bars_r. We import bars_r into main.py. Also in main.py, we import r from foo.py, so wouldn't it run foo.py again, producing a different random number? How does python seem to save the result of the randint function ran in foo.py, so that it can be imported into 2 different modules and have the same value?

Upvotes: 0

Views: 415

Answers (1)

Masklinn
Masklinn

Reputation: 42492

Also in main.py, we import r from foo.py, so wouldn't it run foo.py again, producing a different random number?

No. When a module is imported for the first time, it is loaded, executed, and the result is stored in sys.modules. The second time, the existing module object is simply retrieved from sys.modules.

In normal operations, a module's top level code is run once per Python instance / process.

This is trivial to check by adding observable side-effects e.g. just print something in foo.py.

Having every import leading to a different module object not only would be rather expensive, it would be extremely odd as e.g. the classes defined by a module would not necessarily be compatible with itself (as importing the module twice would create two completely different class objects in memory).

Upvotes: 1

Related Questions