Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 285
Mr.Sh4nnon Avatar asked May 20 '26 07:05

Mr.Sh4nnon


2 Answers

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

like image 63
grapes Avatar answered May 22 '26 01:05

grapes


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>
like image 45
Elar Avatar answered May 22 '26 02:05

Elar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!