Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

Unique seed acrossing multiple imported files with random module (python)

I have a big simulation where I set a seed value (through the random.seed) for the random module in the main file. The main file imports the random module and other files, which import random module too. When I run the simulation, I hope the setted seed is shared to imported files, but as imported files are executed first than main file, the random module in that files reset the seed every time. Below, a reproducible example.

File main.py:

# main.py

import foo 
import random

random.seed (10)
main = random.randint(1, 100)
print("main: ", main)

File foo.py:

# foo.py

import random

foo = random.randint(1, 100)
print("foo:  ", foo)

When I execute python main.py multiple times the value of the main variable is always the same, as I expected. But the value of foo variable changes every time. How can I can set the seed in the main file such that same seed will be used in imported files?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I looked at the source code for random. Each time you import random it creates a new instance of a class called Random with a new seed. This means that what you want to do is not possible, unfortunately, unless you pass around the random number generator directly.

One of the ways you could do this is:

import random
random.seed(123)
import foo
foo.random = random

though that won't affect any code that's executed when foo is loaded, only functions in foo called after the replacement foo.random = random. It also won't propagate to any imports done by foo.

Another way would be defining a helper file or function that sets up random for you, and using that throughout your codebase?— though again that won't affect any library functions that rely on random directly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...