Relative Import in Python

I was writing a small application which needed to be separated into modules. For it to work on any machine, I wanted to use relative imports. My directory structure was as below:

mytopdirectory/
—__init__.py
—mymainscript.py
—country/
—__init__.py
——countryfile1
——countryfile2
——countryfile3
—process/
—__init__.py
——processfile1
——processfile2
——processfile3

In mymainscript.py, I had the following imports:

from country.countryfile1 import function1a
from country.countryfile2 import function2f
from process.processfile3 import function3z

In processfile3, I had the following imports:

from .country.countryfile3 import mydictionary

But I got the following error when running the mymainscript.py file: Attempted relative import beyond toplevel package. So I started looking at what the problem was.

I assumed that .country would work for files in process directory. But I learned that that’s not how it’s supposed to work. So I restructured the directory as below:

mytopdirectory/
—mymainscript.py
—lib/
——__init__.py
——country/
———__init__.py
———countryfile1
———countryfile2
———countryfile3
——process/
———__init__.py
———processfile1
———processfile2
———processfile3

I basically added another level between mymainscript.py, and country and process directories. Now mymainscript.py, had the following imports:

from lib.country.countryfile1 import function1a
from lib.country.countryfile2 import function2f
from lib.process.processfile3 import function3z

And processfile3 had the following imports:

from .. country.countryfile3 import mydictionary

In this way, mytopdirectory becomes a package whose main file is mymainscript.py. In this package, processfile1, processfile2, processfile3, countryfile1, countryfile2, and countryfile3 are six modules.

Hat tips: Path question; Modules; Can anyone explain python’s relative imports?;

One Response to Relative Import in Python

  1. supercheetah says:

    Thank you for this. The relative imports were confusing me.

%d bloggers like this: