Mr.Sh4nnon
Mr.Sh4nnon

Reputation: 337

Importing an arbitrary amount of python files

I have different python files containing Neural Networks. Each python file has associated weights.h5 file.

Now I'd like to make a python evaluation file, which loads all networks / python files and their weights, creates one instance of each and compares their performance.

So far I tried to import as package but then I'm unable to access the modules by an index. How could I import all of the models and put one instance of them in a list, such that I can access them by an index?

An example

from evaluation.v03 import DQNSolver as DQN1
from evaluation.v04 import DQNSolver as DQN2
from evaluation.v05 import DQNSolver as DQN3
...

this works, but I have to hard code each import. Additionally I was not able to create instances by an index or access them by an index to make comparisons between all of the them.

Upvotes: 3

Views: 155

Answers (2)

grapes
grapes

Reputation: 8646

Use __import__() function instead of import statement. Like this:

modules = []
for i in range(10):
  modules.append( __import__('evaluation.v{:>02}'.format(i)) )

Then you can access them like modules[x].DQNSolver

Upvotes: 3

Elar
Elar

Reputation: 896

Making use of import_module(), which is recommended over using __import__() directly:

from importlib import import_module

solvers = [getattr(import_module(f'evaluation.v{i:02d}'), 'DQNSolver') for i in range(5)]

solver = solvers[1]()
# solver -> <evaluation.v01.DQNSolver object at 0x7f0b7b5e5e10>

Upvotes: 2

Related Questions