2

I'm having an issue with the import statement in Python 3. I'm following a book (Python 3 Object Oriented) and am having the following structure:

parent_directory/
       main.py
       ecommerce/
             __init__.py
             database.py
             products.py
             payments/
                    __init__.py
                    paypal.py
                    authorizenet.py

In paypal.py, I'm trying to use the Database class from database.py. So I tried this:

from ecommerce.database import Database

I get this error:

ImportError: No module named 'ecommerce'

so I try with both of these import statements:

from .ecommerce.database import Database

from ..ecommerce.database import Database

and I get this error:

SystemError: Parent module '' not loaded, cannot perform relative import

What am I doing wrong or missing?

Thank you for your time!

1 Answer 1

2

Add your parent_directoryto Python's search path. For example so:

import sys
sys.path.append('/full/path/to/parent_directory')

Alternatively, you can add parent_directory to the environmental variable PYTHONPATH.

Sign up to request clarification or add additional context in comments.

2 Comments

This means that if I want to move my parent_directory somewhere else or if I want to distribute the 'ecommerce' folder as a package, it won't work, right? Any other ways to import a class located in a parent directory?
Usually, if you distribute, i.e. people use pip to install, your package ends up in site-packages, which is in the PYTHONPATH by default. For development just make a directory dev or such, put it on the PYTHONPATH once and put all your projects in there.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.