0

I have a directory structure as follows

  • mybasedir
    • mysub1
      • foo.py
    • mysub2
      • bar.py
    • mysub3
      • mysubderp3
        • foo.py

I would like to import every module under mybasedir which has a foo.py, any not import anything else (i.e. mysub2 shouldnt get imported as it has bar.py, not foo.py)

I would then like to be able to access the module as the < the directory containing foo.py >.foo i.e. I want to use mysubderp3.foo instead of mysub3.mysubderp3.foo,

I have tried to walk the directory structure, looking for foo.py, and adding its path to __all__ in ./mybasedir/__init__.py,

i.e. __all__ = ['mysub1', 'mysub3/mysubderp3']

I would then import from some code as from mybasedir import *

This used to work in python 2.7, but doesnt seem to work in python 3.7

Does anyone have insight into how to accomplish this?

  • You could do several `sys.path.append(directory_absolute_path)`, one for every directory to search. – Guimoute Feb 12 '20 at 20:04
  • Maybe this is helpful reading [Examples in PEP420](https://www.python.org/dev/peps/pep-0420/#nested-namespace-packages) – progmatico Feb 12 '20 at 20:12

1 Answers1

0

Check out pathlib.Path.glob().

https://docs.python.org/3/library/pathlib.html

The example in the docs does a recursive search just as you describe. Once you have the file paths, you can use Path.parent to find the parent directories of each.

  • thanks, but this doesnt solve the problem of how to actually import the modules so they appear at the base namespace – austinpatrickbishop Feb 12 '20 at 22:10
  • Here is a helpful link on dynamic module imports. https://stackoverflow.com/questions/301134/how-to-import-a-module-given-its-name-as-string It looks like you can use import lib for this. – dirtAndCoffee Feb 14 '20 at 15:36