Search code examples
pythonfor-looppython-importlib

python importlib imports from wrong directory


I am trying to import dicts named 'tasks' from different python files (*.py).

The paths are stored in my array directories['code']. Not all files contain one of these tasks dicts.

The problem is, once a file with a dict was found, 'foo' will be set to that dict, but won't be reset, even if the next file does not have a dict.

However, 'foo' will be assigned correctly again, once another file was found containing a new dict.

I wonder if this is because importlib is searching an entire tree, not just the exact path?

And of course, how can I fix this?

import importlib

for i in range(len(directories['code'])):

    try:
        foo = importlib.machinery.SourceFileLoader('file', directories['code'][i]).load_module().tasks

    except:
        foo = '0'
        pass

    print(foo)

Solution

  • Your code is valid, there is one place where is something goes wrong -- directories['code'][i], -- so try to use i:

    for i in ['test/__init__.py', 'test/__init__2.py']:
        try:
            foo = importlib.machinery.SourceFileLoader('file', i).load_module().__version__
        except:
            foo = 0
        print(i, foo)
    
    # test/__init__.py 1.0.0
    # test/__init__2.py 0