-1

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'.
Greg
  • 8,175
  • 16
  • 72
  • 125
  • Possible duplicate of [Import a file from a subdirectory?](https://stackoverflow.com/questions/1260792/import-a-file-from-a-subdirectory) – ricristian Aug 29 '17 at 09:17
  • No this is regarding an installable project (which can be imported using `import project`) – Greg Aug 29 '17 at 09:35

2 Answers2

0

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.

-1

this will solve your issue

import tools.common as COMMON
COMMON.function()
ricristian
  • 466
  • 4
  • 17
  • Result: `ModuleNotFoundError: No module named 'tools'` – Greg Aug 29 '17 at 09:09
  • in which file did you put my code ? this should be put in your main script (core or cli.py) – ricristian Aug 29 '17 at 09:10
  • `project/__init__.py` – Greg Aug 29 '17 at 09:11
  • This should be put in your main script (core or cli.py) '__init__.py' file should pe empty – ricristian Aug 29 '17 at 09:11
  • `AttributeError: module 'project' has no attribute 'tools'`. `project` is an installable project and not a script/folder – Greg Aug 29 '17 at 09:16
  • yes i already use it in one of my projectts and it works perfectly but you have alternative like https://stackoverflow.com/questions/1260792/import-a-file-from-a-subdirectory + https://ibb.co/hJ5Gu5 loog at controllers.CRUD and you will see that this code is perfectly working. – ricristian Aug 29 '17 at 09:17
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/153108/discussion-between-cristianr-and-dave). – ricristian Aug 29 '17 at 09:17
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/153114/discussion-between-dave-and-cristianr). – Greg Aug 29 '17 at 10:03