mrmaxguns / wonderwordsmodule

Generate random words and sentences with ease in Python. Be on the lookout for bugfixes and speed improvements in 2.3
https://wonderwords.readthedocs.io
MIT License
53 stars 11 forks source link

Add seed control. #17

Open Myridium opened 1 year ago

Myridium commented 1 year ago

Is your feature request related to a problem? Please describe. It's not possible for me to produce consistent output because there's no option to include a seed. My use-case is hashing serializable objects, and using their hash as a random seed to give them a human-readable alias which is generated using wonderwords.

Describe the solution you'd like I'd like an option to set the seed/random state in wonderwords.

Describe alternatives you've considered It appears that using Python's random.seed(...) affects the random state of wonderwords. However it isn't enough. It does work during a Python session (i.e. it produces consistent results), but not across different sessions.

For example, consider this function:

import random
import wonderwords

def random_noun(seed : int):
    rstate = random.getstate()
    random.seed(seed)
    noun      = wonderwords.RandomWord().word(include_parts_of_speech=["nouns"])
    random.setstate(rstate)
    return noun

This allows me to produce consistent output when using random_noun(seed) during a program. It's a 'pure function', in the sense that it gives the same output for the same input, with no (known) side effects. However, if I quit Python and run a program again, the results of random_noun(seed) are changed. This means I cannot reproduce behaviour across different runs of the program.

mrmaxguns commented 7 months ago

I didn't even think about that use-case. I think the issue might be that internally in some places Wonderwords uses sets which have no guaranteed ordering. Setting the seed is definitely a valid concern, so I am looking for ways around that

mrmaxguns commented 7 months ago

I implemented a fix where the filter function always returns a sorted list of words. That makes word deterministic if the seed is specified.