convert.py
def ounces_to_grams(weight):
= weight * 28.3495
new_weight return new_weight
= ounces_to_grams(12)
weight_in_grams
print(f"{weight_in_grams} g")
In the last chapter we saw how we can take sections of code and make them reusable in different contexts without having to copy and paste the code every time we want to use it in your script. By using functions we give the code block a name and define what it needs in order to do its job.
Functions are a step in the right direction but they still have the problem that to use functions from one script in another you will have to copy and paste them over. The answer to this is to move the functions to a common location which both scripts can access. The Python solution for this is modules. Just like we used modules from The Python Standard Library earlier, we can create our own modules too.
Continuing with the example of the ounces_to_grams
function from the last section, let’s see how we can use the function in other code, outside of that one script.
convert.py
def ounces_to_grams(weight):
= weight * 28.3495
new_weight return new_weight
= ounces_to_grams(12)
weight_in_grams
print(f"{weight_in_grams} g")
There are two main categories of code in this file:
ounces_to_grams
is the sort of code which is useful in many different situations.We will need to create a new file to hold the function. Let’s call it convert.py
. Make sure this is in the same directory as your notebook. A .py
file is a file containing Python code. Let’s put the function we wrote in the last section into that file:
convert.py
def ounces_to_grams(weight):
= weight * 28.3495
new_weight return new_weight
Now, we want to try and run our function. Go back to your notebook and make a new code cell.
= ounces_to_grams(12)
weight_in_grams
print(f"{weight_in_grams} g")
You will notice, that you get an error that it doesn’t know what ounces_to_grams
is:
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[3], line 1 ----> 1 weight_in_grams = ounces_to_grams(12) 3 print(f"{weight_in_grams} g") NameError: name 'ounces_to_grams' is not defined
This is because that function is indeed not defined in this script. We need to tell it to load the file which contains the function we want to use, using the import
statement:
import convert
= convert.ounces_to_grams(12)
weight_in_grams
print(f"{weight_in_grams} g")
340.19399999999996 g
Here we have done a few things. First, on the first line we have imported our module. This is Python’s way of getting access to code which is inside other modules. You’ll notice that the way we do this is identical to when we were importing modules from the Standard Library (e.g. math
) earlier.
The name of a module is the same as the name of the file but without the .py
extension. So, since we saved our file above as convert.py
, the name of the module is convert
. Then, when calling the function, we need to explicily state that we’re using the ounces_to_grams
function from the convert
module using convert.ounces_to_grams
.
When you import a module that you have written (for example, import morse
) in a notebook, Python loads the module into memory. If you edit and save the module file, the notebook will not automatically reload the updated code—it will keep using the old version until you restart the notebook’s kernel.
Solutions:
Restart the kernel: You can do this by clicking the Restart Kernel button in your notebook interface (it looks like a refresh button). This will clear everything from memory and reload your module the next time you import it. This will delete all your variables and imports though, so you will need to re-run any previous cells to get your environment back to the state it was in.
Use notebook magics: You can use the %load
magic to load code from a file directly into a cell, or %run
to run a Python file and update the environment:
%load_ext autoreload
%autoreload 2
import convert
= convert.ounces_to_grams(12)
weight_in_grams print(f"{weight_in_grams} g")
So far we’ve been writing code and running it, but have you actually checked that the code is doing the right thing? Testing code is a very important part of the software development process because if you want other people to trust your work, you need to show that you’ve checked that your code does what you claim.
There are more formal methods for software testing but we’ll start with a common technique used with encoders/decoders and that is the round-trip. If we take a message, convert it to morse code and then convert it back, we should end up with the message we started with:
test_morse.py
import morse
= "sos we have hit an iceberg"
message
= morse.encode(message)
code = morse.decode(code)
decode
print(message == decode)
When you run it, you should see True
printed to the console terminal tells us that the round-trip was successful.
True
We’ll cover move on how to write tests for your Python modules in the Best Practices in Software Engineering course but for now, this round-trip will suffice.