pyppin.os.bulk_import¶
A function to import an entire directory; useful with registered classes!
Functions
|
Import all Python files in a given directory. |
- pyppin.os.bulk_import.bulk_import(path: Union[str, Path], recursive: bool = True, exclude: List[str] = ['\\..*', '__pycache__', '_.*'], verbose: bool = False, root: Optional[Union[str, Path]] = None) Dict[str, module] [source]¶
Import all Python files in a given directory.
This is useful if, for example, a directory contains implementations which are registered through some mechanism that lets them be accessed programmatically! For an example of this, look at the implementation of tools/lint.py in the pyppin package itself.
- Parameters
path – The file or directory path from which to start the import.
recursive – If true, recurse into subdirectories.
exclude – A list of filename regexps (not globs!) to skip.
verbose – If true, print when we import things.
root – If given, modules will be named as dotted components starting from this path. By default, it is the same as path. It is often useful to pass your repository root here, which will lead to package names that are consistent with your repository structure as a whole.
- Returns
A dict of all the modules found.
Example
Say your repository looks like this:
src/ common/ superclass.py all_types.py impls/ class1.py class2.py foo/ class3.py
Then all_types.py might find its REPO_ROOT using __file__, and call
bulk_import(f'{REPO_ROOT}/impls', root=REPO_ROOT)
. This would load the modules impls.class1, impls.class2, and impls.foo.class3. If those classes were (for example) registered usingRegisteredClass
, you would then be able to grab all of them at once, without having to maintain a directory in-code of all the implementations.