Relative imports in Python — for js people.

ACGoff
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 __init__.py

I had seen these a lot. After a quick google it seemed, in python2, a module needed a __init__.py 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 __init__.py file to be visible (such as pytest ).

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

--

--