Section 5.5 Creating Modules
Youโve seen how to
use modules like
random
,
math
, and
turtle
, but how would you
create a module?
Every time youโve written a Python script youโve created a module!
A Python module is just a Python source code file. Letโs consider the Python file shown below.
"""
The coffee shop module contains functions and contains variables
important to implementing a coffee shop.
"""
# Set some variables
shop_name = "Runestone Brew House"
coffee_sizes = ["small", "medium", "large"]
coffee_roasts = ["hot chocolate", "light", "medium", "dark", "espresso"]
This is a Python script named
coffee_shop.py
that contains three variables:
shop_name
,
coffee_sizes
, and
coffee_roasts
. The
shop_name
is a string,
coffee_sizes
is a list containing strings, and
coffee_roasts
is also a list containing strings.
Checkpoint 5.5.1.
A module is another name for:
the code inside a function
The code inside a function is called a function body.
a file containing Python code
Python modules are just Python source code files.
the comments before a function
The comments just before a function are the function documentation.
a small block of Python code
Modules may be small, but there is a more accurate answer.
Thatโs so great! Weโve got the basics of a coffee shop. All you need is some roasted coffee and cups. Youโre good to go.
If you try to run that code though, it doesnโt do much thatโs visible to a userโฆ
How can we use the
coffee_shop
module? We can import it and use it in other Python source code files. Letโs consider the Python file shown below.
import coffee_shop
# Output the information we know from the module
print("Welcome to", coffee_shop.shop_name)
print("Available sizes:", coffee_shop.coffee_sizes)
print("Available roasts:", coffee_shop.coffee_roasts)
This is a Python script named
coffee_customer.py
that imports our
coffee_shop
module, then prints out the information from that module.
Checkpoint 5.5.3.
writing a new function or class
You may write a function or class inside a module, but this alone does not create one.
placing an import statement at the top of a file
Import statements permit you to use other modules, but they do not create one.
placing code in a Python file in the same directory as your other source code
Modules are Python source code files.
creating a comment block at the beginning of a file
Modules should include comment blocks at the top, but writing a comment block at the top of a file does not create a new module.
We use
dot notation to grab the
shop_name
,
coffee_sizes
, and
coffee_roasts
variables from the
coffee_shop
module. Then we print them out as parts of nice messages.
Variables arenโt the only thing we can place in modules thoughโฆ We can put any valid Python code in them.
Letโs improve our coffee shop!
"""
The coffee shop module contains functions and contains variables
important to implementing a coffee shop.
"""
# Set some variables
shop_name = "Runestone Brew House"
coffee_sizes = ["small", "medium", "large"]
coffee_roasts = ["hot chocolate", "light", "medium", "dark", "espresso"]
def order_coffee(size, roast):
"""
Take an order from a user
:param size: a string containing one of the coffee_sizes
:param roast: a string containing one of the coffee_roasts
:return: a message about the coffee order
"""
return "Here's your {} coffee roasted {}".format(size, roast)
The old file contents are present, but now thereโs also an
order_coffee
function that takes two arguments,
size
and
roast
.
Also - look at all the awesome comments in there!
Ok - so weโve got a function in our module now, letโs use it.
# Import the module with coffee_shop functionality
import coffee_shop
# Output the information we know from the module
print("Welcome to", coffee_shop.shop_name)
print("Available sizes:", coffee_shop.coffee_sizes)
print("Available roasts:", coffee_shop.coffee_roasts)
# Get some inputs from the user
order_size = input("What size coffee do you want? ")
order_roast = input("What roast do you want? ")
# Send the order to the coffee shop module
shop_says = coffee_shop.order_coffee(order_size, order_roast)
# Print out whatever it gave back to us
print(shop_says)
Checkpoint 5.5.6.
What determines the name of our import?
the first variable name in the module
This does not determine module name, and not all modules export variables.
a comment early in the module
This does not determine module name, and comments are not mandatory components of modules.
itโs called whatever we name it in the "import" statement
The import statement uses the module name to lookup the correct module, and an import statement is not used to create the module.
the filename of the module
The filename of the module determines the name of the import.
We added some lines to our
coffee_customer
scriptโฆ Now after printing data nicely,
coffee_customer
asks the user for a size and a roast. These are the parameters required by our
order_coffee
function over in the
coffee_shop
module!
Call the
order_coffee
function with
dot notation, just like retrieving variable values. The function call is the line that says
shop_says = coffee_shop.order_coffee(order_size, order_roast)
. The function returns something, so we save that off in
shop_says
. The next line prints out whatever the shop said.
Coffee shops do more than just coffee! Maybe you want some milk. We need to add some functionality to our coffee shop. Check it out below.
"""
The coffee shop module contains functions and contains variables
important to implementing a coffee shop.
"""
# Set some variables
shop_name = "Runestone Brew House"
coffee_sizes = ["small", "medium", "large"]
coffee_roasts = ["hot chocolate", "light", "medium", "dark", "espresso"]
def order_coffee(size, roast):
"""
Take an order from a user
:param size: a string containing one of the coffee_sizes
:param roast: a string containing one of the coffee_roasts
:return: a message about the coffee order
"""
return "Here's your {} coffee roasted {}".format(size, roast)
def add_milk_please(fat_content):
"""
Pretend like we're adding some milk to a coffee
:param fat_content: a string or integer containing the milkfat content
:return: a message about having added the milk
"""
return "I've added the {}% milk".format(fat_content)
The new function is called
add_milk_please
and it takes one parameter - the
fat_content
. It returns a string explaining what happened.
This is great. But the function isnโt going to do anything by itself. We have to call it. Check out the update to our
coffee_customer
script below.
# Import the module with coffee_shop functionality
import coffee_shop
# Output the information we know from the module
print("Welcome to", coffee_shop.shop_name)
print("Available sizes:", coffee_shop.coffee_sizes)
print("Available roasts:", coffee_shop.coffee_roasts)
# Get some inputs from the user
order_size = input("What size coffee do you want? ")
order_roast = input("What roast do you want? ")
# Send the order to the coffee shop module
shop_says = coffee_shop.order_coffee(order_size, order_roast)
# Print out whatever it gave back to us
print(shop_says)
# See if the user wants to add milk
add_milk_response = input("Do you want to add milk (y/n)? ")
# Convert the response to lowercase, then check for a "yes" answer
if "y" in add_milk_response.lower():
milk_fat = input("What percent milk do you want added? ")
shop_says = coffee_shop.add_milk_please(milk_fat)
# Print out whatever it gave back to us
print(shop_says)
That got fancy! We were just ordering coffee but now the user can choose to add milk! Selection is in a couple chapters, but if you read that code like english youโll see whatโs going on.
The call to
add_milk_please
happens right in there - it looks just like the other one:
shop_says = coffee_shop.add_milk_please(milk_fat)
.
Letโs wrap this coffee shop visit up. But - you better leave a tip. Weโll add another function to our coffee shop to enable that.
"""
The coffee shop module contains functions and contains variables
important to implementing a coffee shop.
"""
# Set some variables
shop_name = "Runestone Brew House"
coffee_sizes = ["small", "medium", "large"]
coffee_roasts = ["hot chocolate", "light", "medium", "dark", "espresso"]
def order_coffee(size, roast):
"""
Take an order from a user
:param size: a string containing one of the coffee_sizes
:param roast: a string containing one of the coffee_roasts
:return: a message about the coffee order
"""
return "Here's your {} coffee roasted {}".format(size, roast)
def add_milk_please(fat_content):
"""
Pretend like we're adding some milk to a coffee
:param fat_content: a string or integer containing the milkfat content
:return: a message about having added the milk
"""
return "I've added the {}% milk".format(fat_content)
def give_tip(tip_amount):
"""
Take a tip from the user, then be happy about it
:param tip_amount: the tip amount
:return: nothing
"""
print("Thank you so much! We don't make a ton of money.")
# Not having a "return" statement causes our function to return None
We added the
give_tip
function which takes one parameter, the
tip_amount
. We donโt actually do anything with that parameterโฆ But if we were getting fancier with the coffee shop we might add it to the customerโs bill, we might print it out, or we might berate the customer for being too cheapโฆ Here we just go ahead and blurt out a thanks to the user! Beinโ friendly is important.
How do we call this from our
coffee_customer
script?
# Import the module with coffee_shop functionality
import coffee_shop
# Output the information we know from the module
print("Welcome to", coffee_shop.shop_name)
print("Available sizes:", coffee_shop.coffee_sizes)
print("Available roasts:", coffee_shop.coffee_roasts)
# Get some inputs from the user
order_size = input("What size coffee do you want? ")
order_roast = input("What roast do you want? ")
# Send the order to the coffee shop module
shop_says = coffee_shop.order_coffee(order_size, order_roast)
# Print out whatever it gave back to us
print(shop_says)
# See if the user wants to add milk
add_milk_response = input("Do you want to add milk (y/n)? ")
# Convert the response to lowercase, then check for a "yes" answer
if "y" in add_milk_response.lower():
milk_fat = input("What percent milk do you want added? ")
shop_says = coffee_shop.add_milk_please(milk_fat)
# Print out whatever it gave back to us
print(shop_says)
# They better give a tip...
print("THAT'S GOOD COFFEE! Very good. Your brain is working again.")
print("You better give a tip.")
tip_amount = input("Tip amount? ")
coffee_shop.give_tip(tip_amount)
Our function call is there on the last line.
You have attempted
of
activities on this page.