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:


In, 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 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:


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

from import function1a
from 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 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: