Relative imports in Python — for js people.

2 min readJul 10, 2022

My background is js. It’s where I feel at home.

I am working in python lately and generally am finding it good (great number of packages — especially in data science and ML — with good tutorials) but the environment system, imports, package management etc are not as intuitive or as simple.

1st Misconception — terminology is the same

In js, you can do relative imports fairly simply — to get functions from one file into another.

In py, this isn’t quite as simple and has a terminology change. A file is known as a module, and a package is a folder.

Knowing this made it easier to Google!

2nd Misconception — wtf

I had seen these a lot. After a quick google it seemed, in python2, a module needed a file in the folder, but this is no longer needed in python3.

A little later though I found that you should still add them and their use is specific to what you are trying to do — whether you want a namespace package or a regular package. If you are reading this, you almost certainly want a regular package. In addition, some other packages still require the file to be visible (such as pytest ).

Because of this, we will need to add empty files. This then marks the directory/file it is in as being a module that can be imported, and the files around it as items it can import.

You can do more such as define alias’ and map functions in this file but that is more advanced than I need.

3rd Misconception — import logic

In node.js, importing without a relative route will go straight to your node_modules.

In python, it will look up your ‘systems’ modules, a.k.a the environment you are executing in.

Knowing which env you are in is non-trivial. If the import phrase is not found, it will look at the python standard library, and if not found will then look at the directories in sys.path.

This means imports are not relative to the file your importing in, but the location you are executing in.

One hacky way of doing this:

import sys
sys.path.append(<add your relative package path>)

Knowing this solved my problems!

I hope it does your too!