exrex
exrex copied to clipboard
Seed Support
It would be great if exrex can support seeding when generating a random string from pattern; something like
pattern = r'(A|N)[0-5]{3}'
string1 = exrex.getone(pattern, seed=777)
string2 = exrex.getone(pattern, seed=777)
string1 == string2 # returns True
This should be possible if standard Python's random instance is used
I was thinking that having an optional seed
argument would be useful too. But after realizing that randomint
and choice
from random
library do not also have seed arguments, I now think it is better to set the seed separately for consistency.
import exrex
import random
pattern = r'(A|N)[0-5]{3}'
random.seed(777)
string1 = exrex.getone(pattern)
random.seed(777)
string2 = exrex.getone(pattern)
string1 == string2 # returns True
Perhaps, getone
can be implemented as a method of a class derived from the base class Random
.
The functions used from the random module, in the function called by exrex.getone, could be taken from an instance of random.Random. Once this change is done, setting the seed as proposed by @ghosalya is easy.
_rng = random.Random()
def _randone(d, limit=20, grouprefs=None, seed=None):
_rng.seed(seed)
...
_rng.choice(...)
...
def getone(regex_string, limit=20, seed=None):
return _randone(parse(regex_string), limit, seed)
string1 = exrex.getone(pattern, seed=777)
It would also be easy to support the solution proposed by @vwyu in a more integrated manner.
def seed(seed):
_rng.seed(seed)
pattern = r'(A|N)[0-5]{3}'
exrex.seed(777)
string1 = exrex.getone(pattern)
exrex.seed(777)
string2 = exrex.getone(pattern)
string1 == string2 # returns True