Vaibhav Jain
Vaibhav Jain

Reputation: 5507

Import Class from a python package at runtime

I am trying to write a function which will take class name a argument and import that class and perform some task.

  def search(**kwargs):
    """
    :return:
    """

    try:
        model = __import__('girvi.models', globals(), locals(),  kwargs['model_name'], -1)
       # Do some task
       return results
    except Exception:
        raise Exception('Model not found')

But thing is model has the class which is in kwargs['model_name'] imported successfully but how do i access it. Please can someone help me.

Upvotes: 0

Views: 231

Answers (1)

User
User

Reputation: 14873

I would try the following:

import importlib
import sys

def import_class(class_name, module_name = "girvi.models"):
    module = importlib.import_module(module_name)
    class_object = getattr(module, class_name) # does not work for nested classes
    return class_object

According to __import__ one should rather use importlib.import_module.

Upvotes: 1

Related Questions