Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...