Override builtin/frozen module functions

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
MasterOfGizmo
Posts: 50
Joined: Sun Nov 29, 2020 8:17 pm

Override builtin/frozen module functions

Post by MasterOfGizmo » Mon Nov 22, 2021 8:44 pm

Hi,

i can easily override print in micropython when "exec"'ing user provided code:

Code: Select all

def x_print(msg):
    print(">>", msg)

exec('print("Hallo")', { "print": x_print })
This happily outputs

Code: Select all

>> Hallo
Now i'd like to do the same to time.sleep. So my plan was to import time, override sleep and then have the exec'd code use that. But I cannot even override the sleep function::

Code: Select all

import time
time.sleep = lambda x: None
unexpectedly fails with

Code: Select all

AttributeError: 'module' object has no attribute 'sleep'
Is there a way to do this in micropython?

Post Reply