'How to dynamically import a class by instance type in Python

I want to insert multiple models into a table in a single transaction. I have a function that receives a parameter of type SqlAlchemy model

class Customer(BaseModel):
    __tablename__ = 'customer'

    id = Column(TEXT, primary_key=True, nullable=False)
    name = Column(TEXT, nullable=True)


def save_multiple_models_to_db(self, models):
    ?? can i get the class object by an instance type()
    model = models[0]
    mod = __import__('model_module', fromlist=['model_class'])
    class_type = getattr(mod, 'Class')  
    ??
    statement = insert(model_type).values(model.to_dict())
    res = session.execute(statement)
    session.commit()    

How can I get the class object to pass to the insert statement? do I have to do string manipulations to extract the module and class name although I have an instance type already?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source