mercredi 4 octobre 2023

Importing a random number from another module is returning the same random number

I am going to give a simple but reproducible example here (and not from my project).

I have 2 modules at the same level:- test_rand.py and test_import.py

test_rand.py has the below code:

from numpy import random
random_number = random.randint(0,1000)

test_import.py has the below code:

for i in range(5):
    from test_rand import random_number
    print(random_number)

Running test_import.py results in the same number getting printed 5 times. The behaviour I want is to print a different number every time I import random_number.

I know one option here is to import just the randint method in test_import.py and then execute it in test_import.py itself - this option is going to require a big change in the project
But is there another way where in the imported namespace can get deleted automatically while a second import happens (in the for loop)




Aucun commentaire:

Enregistrer un commentaire