Python Imports#

There is some fundamentals we should understand:

A Python module is just a file with Python code

A Python package is a folder containing a file


The problem usually comes in when you are calling python modules or scripts from a subfolder.

For example, a project of this form:


If you want to import apples from red_grapes you will struggle when calling your script like this:


You can’t just from my_package import apples, as that package is not on the python path.

Traceback (most recent call last):
  File "", line 1, in <module>
    from my_package import apples
ModuleNotFoundError: No module named 'my_package'

You can’t just do a relative import from ..my_package import apples for the same reason, the parent directory is not added to the python path

Traceback (most recent call last):
  File "", line 1, in <module>
    from ..my_package import apples
ValueError: attempted relative import beyond top-level package

You can run it as a package, not as a file:

python -m red_grapes

But you will get the same errors:

ModuleNotFoundError: No module named 'my_package'


ImportError: attempted relative import with no known parent package

The Solution#

You have to add the parent folder to the sys.path


Even better is to structure your project of the form: