Search code examples
pythonrandom-seed

How does the random.seed function in python work for words? What number is it converted to?


I realized that if I choose

random.seed("hello world!")

it actually works, i.e. it does not give me any error and it works like a normal seed; So for example choosing

random.seed("hello world!")
random.choices([1,2,3,4,5,6,7], k = 10)

keeps giving me the same output; But it would be actually interesting, to what number a string is converted to??


Solution

  • The code in random.py looks like this:

    
    # more code here
    
    # Note there is a entirely different algorithm for "version 1"
    
    elif version == 2 and isinstance(a, (str, bytes, bytearray)):
        if isinstance(a, str):
            a = a.encode()
        seed = int.from_bytes(a + _sha512(a).digest())
    
    # some more irrelevant conditions
    
    super().seed(seed)
    

    So basically the number will be the "input string + sha512 of the input string" interpreted as one very big integer. Python integers have no max value so this always works.