So I'd like to share the knowledge we gathered for anyone who's interested, struggling with the same problem or just to prevent the same questions from being asked again.
All tests were done on an esp8266 with micropython 1.9.4.
1) Project structure:
Let's assume you have a project with a structure like this:
Code: Select all
- rootpackage
--- package
----- subpackage
------- module
2) Importing and unloading the module:
2.1) Now you can import your module and normally you would do it like this:
Code: Select all
from rootpackage.package.subpackage import module
Code: Select all
del module
del sys.modules["rootpackage.package.subpackage.module"]
2.1. A) Delete all package references to the module in sys.modules
Code: Select all
del sys.modules["rootpackage.package.subpackage"]
del sys.modules["rootpackage.package"]
del sys.modules["rootpackage"]
This solution however should not be used at all, as removing packages from sys.modules that might be used somewhere else, can result in problems.
2.1. B) Delete the module reference in the root package:
For this you have to import the root package "rootpackage" so that it is visible in "dir()".
Code: Select all
import rootpackage
del rootpackage.package.subpackage.module
2.2) Alternative method of importing a module:
Code: Select all
import rootpackage.package.subpackage.module
Unloading this module however is a lot easier and works as expected:
Code: Select all
del rootpackage.package.subpackage.module
del sys.modules["rootpackage.package.subpackage.module"]
3) Testing it:
If you want to test this, make sure to run this command between every other command:
Code: Select all
gc.collect();gc.mem_free();dir();sys.modules
4) Warnings:
- Depending on your module it might not be possible to release any RAM. A simple function designed to consume some RAM like this resulted in no released RAM in most of the tests, so check your modules first (this is however not a function you'd use in a module):
Code: Select all
def b():
b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b();b(); return 0
- Always prefer method 2.2. of this How-To as this is the most reliable and "non-hacky" way to import and unload a module.