Nick
Nick

Reputation: 2970

Use reflection to load and instantiate module from package?

I have a package (a folder) named models containing __init__.py, model_a.py, model_b.py.

my __init__.py contains:

from models.model_a import ModelA
from models.model_b import ModelB

In my main.py I do

import models

model = get_model(config.use_model) #config.use_model == "ModelA"

def get_model(model):
    # This should be equivalent to models.ModelA(**config.ModelA.structure)
    return models[model](**config[model].structure)

Which throws the error TypeError: 'module' object is not subscriptable

Basically what I want to do is elegantly load the model which is set in the config. Accessing the config like this works fine.

Upvotes: 1

Views: 67

Answers (2)

ash
ash

Reputation: 5529

You're trying to do programmatic attribute access, so you need to use the getattr function:

return getattr(models, model)(**config[model].structure)

Subscripting (with square brackets, like foo[1]) is not the same as attribute access (with a dot, like foo.bar), in exactly the same way that foo[2] means something different to foo(2).

Upvotes: 2

Druta Ruslan
Druta Ruslan

Reputation: 7402

i don't know is it write but you can try this,

import models
import sys

def get_model(model):
    return getattr(models, model)


model = get_model('ModelA')
print(model())  

Upvotes: 2

Related Questions