Skip to content

random.choice() returning the ever same values and sequences #6347

@mirko

Description

@mirko

On my ESP32 - despite of what I/it did befpre (incl. network connectivity, keyboard input, etc.) - random.choice() always returns the ever same values and sequences:

>>> from random import choice
>>> choice('01234567890')
'6'
>>> choice('01234567890')
'8'
>>> choice('01234567890')
'3'
>>> print("foobar")
foobar
>>> choice('01234567890')
'3'
>>> choice('01234567890')
'5'
>>> from machine import reset
>>> reset()
[..]
MicroPython v1.12-170-g43c91bea2-dirty on 2020-08-10; FOOBAR DEBUG BUILD with ESP32
Type "help()" for more information.
>>> from random import choice
>>> choice('01234567890')
'6'
>>> choice('01234567890')
'8'
>>> choice('01234567890')
'3'
>>> print("SOMETHING ELSE")
SOMETHING ELSE
>>> choice('01234567890')
'3'
>>> choice('01234567890')
'5'
>>>

Apparently this doesn't only happen on the very same device, but the sequence is identical across devices.
I was even told that holds true for every port (if implemented I suppose, which e.g. is not the case for the unix-port, so I couldn't test/verify).

I was also pointed towards random.seed() which indeed changes the behaviour of random.choice() once called.

Also, I was being made aware of this being "legitimate" behaviour, as CPython handles things the same (although, random.seed() does not /require/ a seed as arg, while mpy does).

Even if all this is the case (which I have no reason to doubt):

This is... at least unexpected and I'd even generalise and say rather counter-intuitive. When calling a function called random (or being part of such a module), explicitly designed to return something random, and I do not get anything random but can't even tell so (at first glance at least) and then use it in code which quite likely /relies/ on it being random (collision avoidance, crypto, etc.), then I'd say the risk of people running into this and shooting their feet way worse than I just did, is significantly high.

Credits and big "thank you" for help, explanation, looking into the implementation(s) and research to @mattytrentini !

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions