1

What I have tried

First let me say, I have read maybe 5 or 6 other stackoverflow questions related to this and many things have been said about this. Here's what I found and what I tried:

  1. "Do sys.path.append(<root dir>) before other imports."

    Issue: This works, but it's against PEP standard practice so I'd rather find a solution that does not require modifying sys.path.

  2. "Use the imp library to find your module."

    Issue: The solution outlined in that answer is deprecated as importlib is the new imp, and I'm not sure how to use importlib even after looking at the docs.

  3. "Add an empty __init__.py file in your root directory."

    Issue: This does not work.

Details of my problem

Here is my file structure:

Project/
  ├ subdir/
  |   └ script.py
  ├ __init__.py
  └ module.py

(Note that I left the empty __init__.py file in there just in case it's needed.)

I'm trying to import from module.py to subdir/script.py:

Contents of module.py:

def func():
    print('func was called')

Contents of subdir/script.py:

from module import func
func()

However, when I run python3 script.py in terminal (on Mac), I get this error message:

Traceback (most recent call last):
  File "script.py", line 1, in <module>
    from module import func
ModuleNotFoundError: No module named 'module'

I would appreciate a straightforward solution that does not require modifying sys.path.

SNN
  • 137
  • 1
  • 1
  • 9
  • 1
    check this , this will help you. https://stackabuse.com/python-modules-creating-importing-and-sharing/ You need to create a module that can be install as python package. and you can import from python package . – Yogesh dwivedi Geitpl Mar 25 '22 at 18:28
  • 1
    Does this answer your question? [Importing modules from parent folder](https://stackoverflow.com/questions/714063/importing-modules-from-parent-folder) – Ouroborus Mar 25 '22 at 18:29
  • 1
    I appreciate all the solutions. I've opted to use the `sys.path` hack even though it is bad practice in general, because my project is just too small to be worth all the effort of creating a setup file, a virtual env, and a pip install just so I can import one module. I thought there would be a quick AND pythonic solution, but since there isn't, I choose quick over pythonic. In the future, I will use your solutions for larger projects. Thank you. – SNN Mar 25 '22 at 22:16

2 Answers2

0

Probably the easiest way to solve your problem is to restructure your project:

Project
   ├── script.py
   └── module
         ├── __init__.py
         └── module.py
Roland Smith
  • 42,427
  • 3
  • 64
  • 94
  • This seems to be the least work and most pythonic solution, however unfortunately I'm not willing to compromise the current structure of my project. Thanks though! – SNN Mar 25 '22 at 22:17
0

I solved my issue by setting PYTHONPATH. In my case, it works with this.

PYTHONPATH=<root dir> python3 subdir/script.py