Making modules in python3

Photo by Pavel Nekoranec on Unsplash

Learning python is very fun and especially when after a working on a language which looks highly inspired by python. Having said reusability a prime part in code writing, let’s learn on how to make modules in python and let it reuse in our code.

Landing on this article i assume that we have python installed in our system. Let’s create a file in a pwd (= working directory).

Save this file in your pwd, open terminal and now check the code we wrote.

type ‘python3’

>>> dir()

This will give the current list of module available to use, Now lets import using ‘import mymodule’ and again use dir(), we must now be seeing mymodule available to use, this way we have mymodule available to use in pwd.

now lets move out of the python interpreter using quit().

and change the directory from where we save to some other and re-start python interpreter using ‘python3’ and import mymodule

This time as were not in the same directory where we save the .py file interpreter is now giving error ‘ModuleNotFoundError: No module named ‘mymodule’’

Its because is not reachable by python, as python is looking for files in current directory and then in python site-packages.

So either we move or copy the file or move the file in python site-packages.

What is better ??? site-packages right ?? So lets start with…..

We will use setuptool provided in python3

save this in a file name called and save it in same folder where we saved also make sure to add a README.txt file in the folder.

Creating the Distribution File:

At this stage, you should have three files, which we have put in working folder:,, and README.txt. Now we are ready to create distribution file.

python3 sdist

run this in terminal, this will created the dist folder in your working folder and a file named mymodule-1.0.tar.gz

lets move this file to site-packages.

sudo python3 -m pip install mymodule-1.0.tar.gz

That’s it, if all goes well !!!

Now move to any location, use import mymodule and then dir() we can see mymodule is available to use.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store