Python Modules & Packages for Absolute Beginners

Python modules and packages play a crucial part in modern development. As the application grows, it becomes difficult to manage the code. Therefore the code becomes more and more complicated. This increases the size of our program.

Also Read: Building a Web App with Python – Getting Started With Flask

Check out this cheat sheet for reference if you need a little refresher on Python:

A solution to that is using Python modules and packages. A module can manage and reuse complex codes. So in this article, we will discuss how to use Python modules and packages.

Video tutorials on Python modules and packages are also available. Check out the following course:

Python Modules

Think of Python modules as .py files with definitions and statements. There are several in-built modules in Python, but we can also create our own modules.

First, let’s start by understanding how we can import modules.

Importing Modules

Let’s start with a built-in module called random.

The random module has several methods in it that can generate random numbers.

To start, we need to import the random module in the file. We can do it using the import keyword.

Type the following statement:

import random

Since we imported the random module, we can now use its method random() to generate a floating-point number between 0 and 1.

Go ahead and add the following:

x = random.random()
print("My Random Number", x)

Output:

My Random Number 0.6550652579348203

First, we have the module name itself, which is random. After that, we have a dot followed by the method random() itself.

Other than that, we can also import only the method instead of the whole module. Therefore, we can use the keyword from.

Here’s what I mean:

from random import choice

x = choice([1, 2, 3, 4, 5])
print("Random Choice:", x)

Output:

Random Choice: 5

So instead of importing the whole module, I only imported the method choice() from the module random.

In addition to that, Python also allows us to rename modules when we import them. Therefore, we can use the as keyword to rename them.

For example:

import random as rd

x = rd.random()
print("My Random Number:", x)

Output:

My Random Number: 0.3968261023008156

As we use the alias rd, we don’t have to use module by its name anymore.

Writing Modules

In this part, we will see how to write our modules. Think of it as you are creating a .py file with its function and methods. 

As a result, you can import this Python module into a separate .py file and use its methods. 

Go ahead and create a .py file. You can call it whatever you want. I am going to name it mod.py.

After that, type the following inside your file:

def sayHello():
  return "Hello World!"

Save your file and close it.

Now we have a module called mod.py, and we are going to import it into a separate file and call its method. 

On separate .py file, type the following and run it:

import mod

x = mod.sayHello()
print(x)

Output:

Hello World!

Additionally, you can create multiple methods inside your module file and use them as you wish.

So we are going to follow the same process again. First, create our methods inside the mod.py file.

def sayHello():
	return "Hello World!"

def whatsUp():
	return "Nothing much"
	
def howAreYou():
	return "I am good"

Now again on a separate .py file, type the following:

from mod import sayHello, whatsUp, howAreYou

print(sayHello())
print(whatsUp())
print(howAreYou())

Output:

Hello World!
Nothing much
I am good

Let’s say you want to import every single method from a module file. There’s a way to perform that operation using the asterisk (*) symbol.

Here’s how we do that:

from mod import *

print(sayHello())
print(whatsUp())
print(howAreYou())

Output:

Hello World!
Nothing much
I am good

We can also pass parameters to our methods when creating a module. Let’s see how that works.

Add the following method to your module file:

def addNumbers(x, y):
  return x + y

The addNumbers() will accept two parameters and return their summation.

On your main .py file, let’s import our mod.py and call the addNumbers() method.

from mod import *

x = 10
y = 20

print("x + y: ", addNumbers(x,y))

Output:

x + y:  30

Most importantly, a module can hold variables, definitions, and anything which Python allows.

So, let’s make our mod.py a bit complex with different variations:

def sayHello():
	return "Hello World!"

def whatsUp():
	return "Nothing much"
	
def howAreYou():
	return "I am good"
	
def addNumbers(x, y):
	return x + y
	
list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c']

string1 = "String1"
string2 = "String2"

Again, now import them on your separate .py file:

from mod import *

print("list1:", list1)
print("list2:", list2)

print("string1:", string1)
print("string2:", string2)

Output:

list1: [1, 2, 3, 4, 5]
list2: ['a', 'b', 'c']
string1: String1
string2: String2

In short, think of a module as a Python file that contains code that you can import and reuse on a separate file.

Next, we are going to talk about packages.

Python Packages

Python modules are critical in managing and reusing code. But as the application grows, the number of modules also grows.

Thus the question arises, where should we put all these modules?

We cannot put everything into one module as we build our program. It will not only just make the program more complex but also cause a tremendous amount of confusion.

Therefore, Python packages come into play. In short, think of Python packages as directories with specific modules.

Let’s take a look how packages work. First, create the following new directories:

  • packageOne
  • packageTwo

Inside the packageOne directory, we will create two module files with some code in them.

The first one is mod1.py:

def sayHello():
	return "Hello World!"

def whatsUp():
	return "Nothing much"
	
def howAreYou():
	return "I am good"

After that, we will create the mod2.py:

def addNumbers(x, y):
	return x + y

Notice how all the methods inside mod1.py return only strings

On the other hand, mod2.py returns numbers. 

Now we are going to create two more modules and place them inside the directory packageTwo. So head over to that directory.

We will create two modules here as well. Let’s start by creating mod3.py:

list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c']

And for the mod4.py:

string1 = "String1"
string2 = "String2"

To sum up, we created 4 modules and placed them inside two different directories.

What we will do next is try to import these modules from their respective packages using the from keyword.

Let’s see how that works:

from packageOne import mod1, mod2
from packageTwo import mod3, mod4

print("Using mod1 from packageOne")
print(mod1.sayHello())

print("Using mod2 from packageOne")
print(mod2.addNumbers(10,20))


print("Using mod3 from packageTwo")
print(mod3.list1)

print("Using mod4 from packageTwo")
print(mod4.string1)

Output:

Using mod1 from packageOne
Hello World!
Using mod2 from packageOne
30
Using mod3 from packageTwo
[1, 2, 3, 4, 5]
Using mod4 from packageTwo
String1

Moreover, a package can also contain sub-packages. It’s similar to creating a directory and then placing the other packages inside that directory.

Go ahead and create a directory called mainPackage. Now move the other two packages that we created before inside this directory. 

We will import our sub-packages into our main Python file. Remember that the main Python file exists on the parent directory. Not inside any of the packages folders.

Here’s what our files and directory structure look like:

~/Python Modules & Packages Tutorial
     | -- main.py
     | -- /mainPackage
          | -- /packageOne
          | -- /packageTwo 

So inside your main Python file, type the following:

from mainPackage.packageOne import mod1, mod2
from mainPackage.packageTwo import mod3, mod4

print("Using mod1 from packageOne")
print(mod1.sayHello())

print("Using mod2 from packageOne")
print(mod2.addNumbers(10,20))


print("Using mod3 from packageTwo")
print(mod3.list1)

print("Using mod4 from packageTwo")
print(mod4.string1)

Output:

Using mod1 from packageOne
Hello World!
Using mod2 from packageOne
30
Using mod3 from packageTwo
[1, 2, 3, 4, 5]
Using mod4 from packageTwo
String1

As you can see, Python allows us a great deal of flexibility when it comes to organizing and structuring the Python modules and packages.

Conclusion

In conclusion, Python modules are just files that hold reusable codes. We can use use the import keyword to import a module.

If you want to import specific methods, then you can use the from keyword along with import.

Moreover, to import every method and function from a module, you can use the asterisk (*).

We also talked about packages. Packages are directories where you can place your modules. Besides, they can also have sub-packages.

Python modules and packages help programmers to simplify their code. Not only that, but it also allows us to share code and utilize them to integrate it into our own programs.

Read:

Interested in learning through video? Then check out this Python tutorial from LinkedIn Learning for FREE:

Do you think using Python modules makes our lives easier? What’s your understanding of packages? 

Leave a Reply