Can import random, but can't call randint

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Carbon12
Posts: 2
Joined: Mon Jun 01, 2020 1:14 am

Can import random, but can't call randint

Post by Carbon12 » Mon Jun 01, 2020 1:22 am

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')

Christian Walther
Posts: 169
Joined: Fri Aug 19, 2016 11:55 am

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

Post by Christian Walther » Mon Jun 01, 2020 7:49 am

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).

Carbon12
Posts: 2
Joined: Mon Jun 01, 2020 1:14 am

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

Post by Carbon12 » Mon Jun 01, 2020 12:57 pm

thank you!

rpr
Posts: 99
Joined: Sat Oct 27, 2018 5:17 pm

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

Post by rpr » Mon Jun 01, 2020 10:41 pm

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.

kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

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

Post by kevinkk525 » Tue Jun 02, 2020 5:15 am

It also works on the latest daily builds of the esp32
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

Post Reply