0

I'm using Python 3.9.5.

Based on this post, I'm trying to reuse some functions from the parent directory. Here's my code hierarchy:

github_repository
    src
        base
            string_utilities.py
        validation
            email_validator.py

I also have __init__.py in all folders. In ALL of them.

Here's the string_utilities.py content:

def isNullOrEmpty(text: str):
    return text is not None and len(text) > 0

And here's the email_validator.py content:

from src.base import string_utilities

def is_email(text: str):
    if string_utilities.isNullOrEmpty(text):
        return False
    # logic to check email
    return True

Now when I run python email_validator.py, I get this error:

ModuleNotFoundError: No module named 'src'

I have changed that frustrating import statement to all of these different forms, and I still get no results:

from ...src.base import string_utilities

which results in:

ImportError: attempted relative import with no known parent package

import src.base.string_utilities

Which causes compiler to not know the isNullOrEmpty function.

import ...src.base.string_utilities

Which results in:

Relative imports cannot be used with "import .a" form; use "from . import a" instead

I'm stuck at this point on how to reuse that function in this file. Can someone please help?

  • run like this `python src/validation/email_validator.py` – Vishal Singh May 15 '21 at 14:43
  • @VishalSingh, ran `python src\validation\email_validator.py` since I'm on Windows, and got the same error: `ModuleNotFoundError: No module named 'src'` – mohammad rostami siahgeli May 15 '21 at 14:46
  • 2
    Try printing the sys.path and check if your modules are getting listed. if your module is not getting listed try adding them in either PYTHONPATH or using sys.path.insert – heretolearn May 15 '21 at 14:53
  • 1
    https://stackoverflow.com/questions/11536764/how-to-fix-attempted-relative-import-in-non-package-even-with-init-py BrenBarn's answer might hold the explanation to build some knowledge here – Shushiro May 15 '21 at 14:56
  • 1
    https://stackoverflow.com/questions/16981921/relative-imports-in-python-3/28154841#28154841 explanation I found browsing the above mentioned post – Shushiro May 15 '21 at 15:15
  • @heretolearn, thanks for that note. I printed `sys.path` and only the `validation` package is listed. But I read in many places that placing `__init__.py` file in parent directories, automatically registers them as packages. That's weird. – mohammad rostami siahgeli May 15 '21 at 15:27
  • @mohammadrostamisiahgeli, yes ideally if you add __init__.py, that tells the interpreter that the directory is a python directory. Can you put the exact directory structure including the inits. Also can you try adding the root path to the PYTHONPATH ? – heretolearn May 15 '21 at 16:16

0 Answers0