This lecture will span around the modules and packages in Python.
They are a way to organize your code in the form of files and are really important if you intend to build web applications with Python
Modules
A module in Python is basically a file with some python code which we use to organize our code into files. Think of it like sections in a supermarket. When you go to a supermarket there are different sections for fruits, vegetables, cleaning products etc. You don’t see one section with all the products.
It’s the same concept in programming. Instead of writing all our code with all functions and classes in main.py, we break up our code into multiple files. Each file is referred to as a module. With this, not only is our code better organized and structured, but we also have the ability to reuse our code. Let’s see it through an example.
Let’s define two functions for converting weight from pounds to kilograms and vice versa.
def lbs_to_kg(weight):
return weight * 0.45
def kg_to_lbs(weight):
return weight / 0.45
Now, we can take these two functions and put them in a separate module called “converters”, and then it can be imported into any program that needs these converter functions. Let me show you how to do this.
Let’s open up our project panel and right-click the project and add a new file. We’re going to call this file “Converters.py”.
Now copy the code from the default file and paste it into the “Converters.py”.
With this, we have cleaned up our main module and it’s not bloated with different functions. As we write more functions with classes, we put them in their corresponding modules. A module should contain all the related functions and classes. Now, we want to import the converters module into our app module. To do this, write import converters
on the top without the extension “.py”.
We can access the members of a module by using a dot operator similar to methods.
Let’s convert 70 kg into pounds:
There is also another syntax for importing modules. Instead of importing the entire module, we can import specific functions from that module. We can type from Converters import
and press “control + space to show the list of available functions. With this, we can directly call this function.
Exercise
Here is your exercise.
This is related to an exercise from the lecture where we discussed “for loops” where we wrote a program to find out the largest number from a list
numbers = [8, 3, 6, 10, 5]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(max)
This code currently has no organization. We don’t have any functions or modules and the program is written in a single file. That is okay for small programs but as your programs grow, you need to properly organize your code into classes and modules. Therefore, as part of this exercise, I want you to write a function, call it find_max
. This function should take a list and return the largest number in that list. After that go ahead and put this function in a separate module, extract it from here and put it in a module called utils
. This module should contain a bunch of utility functions. Import the utils
module into the current module and call find_max
function. Finally, get the result and print it on the terminal.
This exercise is a little challenging but easily doable.
Solution
Start by defining a function find_max
and add a parameter called numbers. Inside this function, write the algorithm for finding the largest number in a list.
def find_max(numbers):
max = numbers[0]
for number in numbers:
if number > max:
max = number
return max
Save this code in a file “utils.py” as a module.
Back to our main program, just import the module by either of the two syntaxes and simply execute the logic.
One thing, I need to bring your attention to is the undermined max
. The reason for that is the max
is a built-in function in Python and we are redefining it. So this is a warning from the Python compiler that we can no longer use max as its built-in function.
Built-in Modules in Python
Python comes with a standard library that contains several modules for common tasks such as sending emails, working with date and time, generating random values and passwords and so on. There are so many modules already built into Python which means there is already lots of functionality that we can reuse. You can find these modules here.
Packages
Packages are basically another way to organize our code on top of the modules. A real project can contain hundreds or even thousands of modules and over time our directory will get bloated with so many files. Therefore, a better approach is to organize related modules inside of a package which makes the package a container for multiple modules.
A new directory is added to the project and all the related modules are added to that directory. As an example, think of a mall. There are different sections for men, women and kids’ apparel in a mall which are like packages. Each section has different areas for different kinds of products like shoes, t-shirts and jackets. Think of these as modules.
Let’s see, how to create and use packages in Python.
First, add a new directory from the project panel. Let’s call it “eCommerce”. This package will contain all the modules related to an eCommerce application.
It’s still an empty directory and to convert it into a package, we need to create a special file in it. Add a new python file in this directory and name that file “__init__”. It’s a special convention in Python and when the Python interpreter sees a file with this name in a directory, it treats this directory as a package.
We also have an alternate and concise method to create a package. Just right-click the project panel and create a Python package from the list. Name it “eCommerce” and that’s it. It will automatically create a directory with a Python file named “__init__”.
Now, let’s create a module in the package and name it “shipping”. In this module, let’s create a simple function for calculating shipping costs.
def calc_shipping():
print("calc_shipping")
To access this function in our main module, we have to access it through the e-commerce package. Once again we have two methods to import this module.
In the first method, we can import the whole module and then call a function independently like this:
import eCommerce.shipping
eCommerce.shipping.calc_shipping()
However, with this approach, calling one of the functions to this module requires prefixing it with eCommerce.shipping.
That is very verbose. So, when working with packages we often use the second approach and use the from
statement.
from eCommerce.shipping import calc_shipping
calc_shipping()
If you have multiple functions in one module you can import them all in a single line by using commas between them. Let’s say there is another function for calculating tax in our shipping module. That will be imported like this:
from eCommerce.shipping import calc_shipping, calc_tax
You can also import individual modules and leave functions to be called at a later stage in the program. Let’s import the module shipping and then use a dot operator to call the function calc_shipping.
from eCommerce import shipping
shipping.calc_shipping()
Wrap Up!
Packages and Modules are extremely important in Python. Especially, when you want to work with a framework like Django which is used for building web applications with Python. We will look into Django during another Python course.
This was the last conventional lecture in this series. The next lecture will deviate from our usual format and we will learn some important use cases in Python. That will mark the end of this series and we will move on to our next Python series. Stay tuned for that.
Leave a Reply