How to import a project subfolder so that it is available once the installed project has been imported?

132 views Asked by At

How to import a project subfolder so that it is available once a project has been imported?

For example how to import the contents of project.tools so that after importing the project using import project, project.tools.common.function() is available?

project
|
|--tools
|  |--__init__.py
|  \--common.py
|
|--__init__.py
|--core.py
\--cli.py

I've tried the following:

  1. from . import tools in project/__init__.py and from . import * in project/tools/__init.py which resulted in: ImportError: cannot import name 'tools'.
  2. from .tools import * in project/__init__.py and from . import * in project/tools/__init.py which resulted in: ModuleNotFoundError: No module named 'project.tools'.
  3. from .tools import common in project/__init__.py and from . import * in project/tools/__init.py which resulted in: ModuleNotFoundError: No module named 'project.tools'.
2

There are 2 answers

0
catchingPatterns On BEST ANSWER

Use import tools in your .py script directly. Then use tools.common.function() in the function call.

When you place init.py in your folder, the folder becomes callable. Hence you can import that folder and its scripts directly into your scripts.

8
ricristian On

this will solve your issue

import tools.common as COMMON
COMMON.function()