Creating a Python Module

45 minutes
  • 3 Learning Objectives

About this Hands-on Lab

Being able to reuse code is incredibly useful, but to make our code even more useful, we need to bundle it up so that it can be used from other programs. The primary way this is done in Python is by using modules. In this hands-on lab, we’ll define and use our custom module and built-in modules to ensure the `using_modules.py` file can execute properly.

The following are prerequisites for feeling comfortable completing this lab:

– Creating and importing modules. Watch the “Creating and Using Python Module” video from the [Certified Associate in Python Programming Certification][1] course.
– Using different import styles. Watch the “Using Imports” video from the [Certified Associate in Python Programming Certification][1] course.

[1]: https://linuxacademy.com/cp/modules/view/id/470

Learning Objectives

Successfully complete this lab by achieving the following learning objectives:

Import the `math` Module within `using_modules.py`

To get started, let’s run the using_modules.py file to see what our first issue is.

$ python3.7 using_modules.py
Traceback (most recent call last):
  File "using_modules.py", line 7, in <module>
    assert math.ceil(14.11) == 15, f"Expected 15, but got {math.ceil(14.11)}"
NameError: name 'math' is not defined

We’re attempting to use the math module, but it has not been imported. Let’s import the math module now.

~/using_modules.py

# 1) Import the built-in `math` module
import math

# 2) Import the `reverse` and `str_shuffle` as `shuffle` from the custom `strhelpers` module (Needs to be created)

name = "Kevin Bacon"

assert math.ceil(14.11) == 15, f"Expected 15, but got {math.ceil(14.11)}"
assert (
    reverse(name) == "nocaB niveK"
), f"Expected 'nocaB niveK', but got {reverse(name)}"
assert type(shuffle(name)) == str, f"Expected a string, but got {type(shuffle(name))}"
assert sorted(shuffle(name)) == sorted(
    name
), f"Expected [' ', 'B', 'K', 'a', 'c', 'e', 'i', 'n', 'n', 'o', 'v'], but got {sorted(shuffle(name))}"

We’ve imported the whole math module, so now we should be able to run the file and see a different error.

$ python3.7 using_modules.py
Traceback (most recent call last):
  File "using_modules.py", line 10, in <module>
    reverse(name) == "nocaB niveK"
NameError: name 'reverse' is not defined
Create the `strhelpers` Module and Implement the `reverse` Function

We’re going to be creating a module called strhelpers that will contain two functions we need: reverse and str_shuffle. For now, we’re going to just focus on the reverse function. From the previous error, we saw this function needs to take a string and return that string in reverse. Let’s create our module by creating a strhelper.py file right next to the using_modules.py file, and then define a reverse function.

~/strhelpers.py

def reverse(str_value):
    return str_value[::-1]

We’ve used string slicing with a negative step value to reverse the string. Now we need to import this function from this module using a from ... import statement.

~/using_modules.py

# 1) Import the built-in `math` module
import math

# 2) Import the `reverse` and `str_shuffle` as `shuffle` from the custom `strhelpers` module (Needs to be created)
from strhelpers import reverse

name = "Kevin Bacon"

assert math.ceil(14.11) == 15, f"Expected 15, but got {math.ceil(14.11)}"
assert (
    reverse(name) == "nocaB niveK"
), f"Expected 'nocaB niveK', but got {reverse(name)}"
assert type(shuffle(name)) == str, f"Expected a string, but got {type(shuffle(name))}"
assert sorted(shuffle(name)) == sorted(
    name
), f"Expected [' ', 'B', 'K', 'a', 'c', 'e', 'i', 'n', 'n', 'o', 'v'], but got {sorted(shuffle(name))}"

Running this again, we should see a new error.

$ python3.7 using_modules.py
Traceback (most recent call last):
  File "using_modules.py", line 13, in <module>
    assert type(shuffle(name)) == str, f"Expected a string, but got {type(shuffle(name))}"
NameError: name 'shuffle' is not defined
Implement `str_shuffle` and Import It as `shuffle`

Our final task is to implement a function called str_shuffle in the strhelpers module. This function needs to take a string and return a shuffled version of it. Thankfully, the standard library includes a way to shuffle a list, and we can convert strings to lists and back again. Let’s implement the str_shuffle function using the random.shuffle function.

~/strhelpers.py

from random import shuffle as l_shuffle

def reverse(str_value):
    return str_value[::-1]

def str_shuffle(str_value):
    str_list = list(str_value)
    l_shuffle(str_list)
    return "".join(str_list)

A thing to note here is that random.shuffle doesn’t return a new list. It modifies the existing list. Next, let’s import this function into using_modules.py, giving it the identifier shuffle.

~/using_modules.py

# 1) Import the built-in `math` module
import math

# 2) Import the `reverse` and `str_shuffle` as `shuffle` from the custom `strhelpers` module (Needs to be created)
from strhelpers import reverse, str_shuffle as shuffle

name = "Kevin Bacon"

assert math.ceil(14.11) == 15, f"Expected 15, but got {math.ceil(14.11)}"
assert (
    reverse(name) == "nocaB niveK"
), f"Expected 'nocaB niveK', but got {reverse(name)}"
assert type(shuffle(name)) == str, f"Expected a string, but got {type(shuffle(name))}"
assert sorted(shuffle(name)) == sorted(
    name
), f"Expected [' ', 'B', 'K', 'a', 'c', 'e', 'i', 'n', 'n', 'o', 'v'], but got {sorted(shuffle(name))}"

Finally, let’s run using_modules.py one last time to ensure there are no more errors.

$ python3.7 using_modules.py
$

Additional Resources

We already have a file called using_modules.py that we need to add imports to so that we can run it without error by running the following:

$ python3.7 using_modules.py
$

We need to use the built-in math module and create the strhelpers module that contains a few different functions. By running the using_modules.py file, we'll see the errors preventing the file from running and that can guide us towards the changes we need to make. To implement the functions in strhelpers, we'll want to use the random.shuffle function.

Logging In

There are a couple of ways to get in and work with the code. One is to use the credentials provided in the hands-on lab overview page, log in with SSH, and use a text editor in the terminal.

The other is using VS Code in the browser. For this route, navigate to the public IP address of the workstation server provided in the hands-on lab overview page. Make sure to access the link on port 8080 (e.g. http://PUBLIC_IP:8080). Your password will be the same password that you'd use to connect over SSH.

What are Hands-on Labs

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Get Started
Who’s going to be learning?

How many seats do you need?

  • $499 USD per seat per year
  • Billed Annually
  • Renews in 12 months

Ready to accelerate learning?

For over 25 licenses, a member of our sales team will walk you through a custom tailored solution for your business.


$2,495.00

Checkout
Sign In
Welcome Back!

Psst…this one if you’ve been moved to ACG!