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 mymodule.py 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 mymodule.py 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 mymodule.py is not reachable by python, as python is looking for mymodule.py 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 setup.py and save it in same folder where we saved mymodule.py 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: mymodule.py, setup.py, and README.txt. Now we are ready to create distribution file.

python3 setup.py 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.