Python – How to Call Python Function Dynamically by Name Using a String

modulepythonpython-3.8

I have a Python function call like so:

import torchvision

model = torchvision.models.resnet18(pretrained=configs.use_trained_models)

Which works fine.

If I attempt to make it dynamic:

import torchvision

model_name = 'resnet18'
model = torchvision.models[model_name](pretrained=configs.use_trained_models)

then it fails with:

TypeError: 'module' object is not subscriptable

Which makes sense since model is a module which exports a bunch of things, including the resnet functions:

# __init__.py for the "models" module

...
from .resnet import * 
...

How can I call this function dynamically without knowing ahead of time its name (other than that I get a string with the function name)?

Best Answer

You can use the getattr function:

import torchvision

model_name = 'resnet18'
model = getattr(torchvision.models, model_name)(pretrained=configs.use_trained_models)

This essentially is along the lines the same as the dot notation just in function form accepting a string to retrieve the attribute/method.

Related Question