Is it possible to remove modules from the import cache?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
aivarannamaa
Posts: 25
Joined: Fri Sep 22, 2017 3:19 pm
Location: Estonia
Contact:

Is it possible to remove modules from the import cache?

Post by aivarannamaa » Tue Nov 26, 2019 5:03 pm

Thonny IDE allows testing local scripts on MicroPython devices by sending the code to the REPL.

Let's say the code imports a helper module which has been uploaded to the device. Now, if the user uploads a modified version of the helper module, and runs the main script again (by sending it to REPL), it is easy to assume that the new version of the helper module gets picked up.

Is it somehow possible to force importing certain modules from scratch? Soft reboot would do, but I'm looking for something faster.


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

Re: Is it possible to remove modules from the import cache?

Post by kevinkk525 » Tue Nov 26, 2019 6:10 pm

You might want to look at my experiences that I wrote a How-To about: viewtopic.php?f=15&t=5302&hilit=unload+module
Kevin Köck
Micropython Smarthome Firmware: https://github.com/kevinkk525/pysmartnode

User avatar
jimmo
Posts: 892
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia

Re: Is it possible to remove modules from the import cache?

Post by jimmo » Wed Nov 27, 2019 12:22 am

aivarannamaa wrote:
Tue Nov 26, 2019 5:03 pm
Is it somehow possible to force importing certain modules from scratch? Soft reboot would do, but I'm looking for something faster.
I think avoiding the risk of extremely confusing behavior due to strange side effects is probably worth the extra time taken for the soft reset. How long does a soft reset take? It's pretty much instantaneous on all the boards I'm familiar with?

We do occasionally see posts on the forum where users are very confused by their code "not working" and it almost always involves an eval(open('main.py').read()). I don't know if that's from Thonny, but it is very confusing.

User avatar
aivarannamaa
Posts: 25
Joined: Fri Sep 22, 2017 3:19 pm
Location: Estonia
Contact:

Re: Is it possible to remove modules from the import cache?

Post by aivarannamaa » Thu Nov 28, 2019 7:29 am

jimmo wrote:
Wed Nov 27, 2019 12:22 am
I think avoiding the risk of extremely confusing behavior due to strange side effects is probably worth the extra time taken for the soft reset.
I guess you're right -- automatic soft reset would be good default choice. I didn't remember correctly how fast it is (provided there is nothing time consuming in boot.py).

I'm thinking of adding 3 options for what to do before each run:
  • soft reboot (default)
  • remove changed files from module cache (for cases where boot.py does something heavy, eg. connecting to WiFi)
  • do nothing


Post Reply