28

If I use the Python function random.seed(my_seed) in one class in my module, will this seed remain for all the other classes instantiated in this module?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Lyrositor
  • 383
  • 4
  • 7

1 Answers1

36

Yes, the seed is set for the (hidden) global Random() instance in the module. From the documentation:

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances ofRandom to get generators that don’t share state.

Use separate Random() instances if you need to keep the seeds separate; you can pass in a new seed when you instantiate it:

>>> from random import Random
>>> myRandom = Random(anewseed)
>>> randomvalue = myRandom.randint(0, 10)

The class supports the same interface as the module.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Does it mean that `eval( "random.random()" )` will also honour this seed? – Dilawar Dec 30 '16 at 06:58
  • @Dilawar yes, `eval()` is not special here; it still uses the same namespaces and `random` is looked up from the globals you run `eval()` in, finding the same module. – Martijn Pieters Dec 30 '16 at 09:54
  • Just for clarification: objects instantiated from this class will still yield different (for each object) values for the random variables. – Ataxias Aug 04 '18 at 03:13