Dynamically import relative path module and instantiate class with parameter

Viewed 255

OK a possible duplicate, but if not how can I dynamically import a module and instantiate with a parameter?

I have a class module in a file food/healthyfood/fruits.py:

class Fruit(object):
    def __init__(self, kind):
        self.kind = kind

now I need to import this class dynamically by just a string 'Fruit' and instantiate it with a parameter.

Static loading method in the file located in food package folder:

from food.healthyfood import fruits
fruit = fruits.Fruit('apple')

Dynamic loading method in the file located in food package folder:

fruitClass = getattr(importlib.import_module("food.healthyfood.fruits"), "Fruit")
fruit_inst = fruitClass('apple')

I get a package not found error, what am I doing wrong? Also food & healthyfood are python package folders and has __init__.py in each.

0 Answers
Related