Page 1 of 1

Can import random, but can't call randint

Posted: Mon Jun 01, 2020 1:22 am
by Carbon12
Hitting a weird issue. I can import the random module, but if I call any method, it fails. Two examples below. There's no file called random.py on my local system or my board. All other modules working fine so far. Stumped, anyone see something like this as well?

File name: test.py

print(random.randint(1, 10)) returns

Code: Select all

nAttributeError: \'module\' object has no attribute \'randint\'\r\n')
print(random.__file__) returns

Code: Select all

ampy.pyboard.PyboardError: ('exception', b'', b'Traceback (most recent call last):\r\n  File "<stdin>", line 3, in <module>\r\nAttributeError: \'module\' object has no attribute \'__file__\'\r\n')

Re: Can import random, but can't call randint

Posted: Mon Jun 01, 2020 7:49 am
by Christian Walther
This is expected. The urandom module (which is what you’re getting when you import random without having a random.py in the filesystem) only implements a subset of the standard Python random module. See help(random) for what is available. The rest you’ll have to implement yourself based on that, or find an implementation by someone else (such as https://github.com/micropython/micropyt ... /random.py).

Re: Can import random, but can't call randint

Posted: Mon Jun 01, 2020 12:57 pm
by Carbon12
thank you!

Re: Can import random, but can't call randint

Posted: Mon Jun 01, 2020 10:41 pm
by rpr
On my esp32 running MicroPython v1.12-421-g4371c971e, randint works.

Code: Select all

MicroPython v1.12-421-g4371c971e on 2020-05-30; ESP32 module with ESP32
Type "help()" for more information.
>>> import random
>>> help(random)
object <module 'urandom'> is of type module
  __name__ -- urandom
  getrandbits -- <function>
  seed -- <function>
  randrange -- <function>
  randint -- <function>
  choice -- <function>
  random -- <function>
  uniform -- <function>
>>> print(random.randint(1, 10))
7
I did a build from scratch but all defaults. It also works with the stable version 1.12.

Re: Can import random, but can't call randint

Posted: Tue Jun 02, 2020 5:15 am
by kevinkk525
It also works on the latest daily builds of the esp32