Modules and packages in Python

A guide to knowing how to use PyPi for installing modules and packages and also create your own ones.

Jayashree domala
Level Up Coding

--

PyPi is a repository for open-source third-party Python packages. There are many other libraries that are open-sourced and shared on PyPi. The “pip install” command is used to install these packages.

To learn about Python installation, check out my other article here.

By installing Python, we automatically install pip too. pip is a simple way to download packages at the command line directly from the PyPi repository.

How to download and install the external packages?

Let’s try installing a package “colorama” which allows you to print out colorized text in your command line. I have the package already installed but in case you don’t have it then it would install it.

Now let’s try using the package. When we have to use a package we write “import” command.

How to create your own modules and packages?

Modules are just .py scripts that are called in another .py script. Packages are a collection of such modules. Therefore we can create our custom modules and packages too.

To create .py scripts, using an editor is preferable.

We start off by creating two files namely “my_module.py” and “my_program.py”.

In “my_module.py”, we will create a basic function.

my_module.py (Source: Author)

In “my_program.py”, we will use the code from the module we just created.

my_program.py (Source: Author)

So now when we run the .py script “my_program.py” where the “func1” function is called, we will get the desired output.

So this is the basic way of creating a module. Now we will create many modules and aggregate it into a package. So now create a folder “MyPackage” and create a subfolder named “SubPackage”. Now to let python know that it has to treat these folders as packages and not mere folders we need to add a file “__init__.py” in the package folder and sub package folder. This file is left empty.

Now create two files “main_script.py” and “sub_script.py” and add it in the package and subpackage folder. Then create another file “program.py” where we will import the package. Accordingly, write the code as given.

main_script.py (Source: Author)
sub_script.py (Source: Author)

The folder directory should look something like this:

Directory Tree (Source: Author)

Beginner-level books to refer to learn Python:

Advance-level books to refer to learn Python:

Reach out to me: LinkedIn

Check out my other work: GitHub

--

--

Self-driven woman who wishes to deliver creative and engaging ideas and solutions in the field of technology.