import module by name

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
cookie
Posts: 3
Joined: Fri Mar 26, 2021 2:59 pm

import module by name

Post by cookie » Fri Mar 26, 2021 3:22 pm

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.

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

Re: import module by name

Post by kevinkk525 » Fri Mar 26, 2021 4:12 pm

See how I'm doing that in my project using __import__(): https://github.com/kevinkk525/pysmartno ... nts.py#L66
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

cookie
Posts: 3
Joined: Fri Mar 26, 2021 2:59 pm

Re: import module by name

Post by cookie » Fri Mar 26, 2021 6:02 pm

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

Post Reply