Page 1 of 1

import module by name

Posted: Fri Mar 26, 2021 3:22 pm
by cookie
Hello! I'm working on porting some python code to micropython and I'm stuck on a certain point. I'd like to import a module by its name as string.

In python :

Code: Select all

module = import_module(moduleName)
So there's no obvious import_module equivalent in upy that I've found. Do you have any ideas for functions I can investigate to do the same? My goal in importing the module by name was to instantiate a class in the module afterwards (and to prevent needless imports).

Code: Select all

class_ = getattr(module, className)
instance = class_()
There are holes in my knowledge so if my reasoning is wrong, please let me know. I'm here to learn and eventually to share what I've learned.

Re: import module by name

Posted: Fri Mar 26, 2021 4:12 pm
by kevinkk525
See how I'm doing that in my project using __import__(): https://github.com/kevinkk525/pysmartno ... nts.py#L66

Re: import module by name

Posted: Fri Mar 26, 2021 6:02 pm
by cookie
Perfect, that helped me! Thank you!

For future searchers, here's what it is in generic form:

Code: Select all

module = __import__(moduleName)  # for import_module
class_ = getattr(module, className)  # to import a class in a module by name