lundi 11 novembre 2019

Issues seeding PRNG when reloading moduel from iPython

When I rerun a Python 3 script in iPython (using %run), I am encountering a hard-to-describe problem when (a) there is a module that is reloaded and (b) inside such module, there are variables being generated with random numbers.

As an example of the issue I am trying to understand and solve, say I have two python files, one called test.py and another called other.py.

Here are the contents of test.py:

import importlib
import numpy.random as rng

seed = 123
myRngEngine = rng.RandomState(seed)

import other
importlib.reload(other)
from other import *

print(var)

Here are the contents of other.py:

from __main__ import *

var = myRngEngine.randint(0, 1000, 1)[0]

Now, I open an iPython console and then I enter:

%run /mypath/test.py 

The number I get printed as output is 365. If repeat the above to rerun the script, I then get 510 as output. From then on, if I repeat it, I always get 510. Now, I close the iPython console and then launch a new instance of iPython console. Again, the first time I enter the %run line above, I get 365 as the output, but in all subsequent tries, I get 510.

Questions:

(1) Why is this going on?

(2) How can I solve this such that all tries result in exactly the same output since the seed is set to be the same?

One important detail is why am I doing the following in the test.py:

import other
importlib.reload(other)
from other import *

I really need the flexibility that, whenever I run test.py, any changes I did to other.py should be reflected without having to re-launch iPython.

Another important detail is why am I assigning to "global" variables in other.py, like var. It is exactly because the file other.py is working as a config/global-variables file - so having that is currently a necessity.




Aucun commentaire:

Enregistrer un commentaire