As we write more and more functions to accomplish specific cryptography tasks, copying/pasting each function into each new notebook will get cumbersome. Instead, we can save our commonly used functions into a Python file that we can import into each notebook as needed. These files are referred to as modules.
To create a module you need to create a Python script file. A script file ends in
.py and contains only Python code without all the Markdown and structure that a Jupyter Notebook provides. To do this in your Jupyter Notebook, perform the following steps from your Home Directory:
- Click on
untitled.txtto rename the file
- Rename the file so it ends in
- Copy / Paste all Python code into your module that you'll want to access in other Notebooks.
- Save your file before closing the tab or window.
In this example, the functions
caesarEncipher() have been copied into the file
Now that you have your module file saved, you can import the contents into any other notebook that is stored in the same folder as the module. There are a few ways you can import the module depending on how you want to use it:
This method is the easiest to understand. Use
import followed by the name of your module file (without the
.py). To use the objects found inside the module, the general structure is
moduleName.objectName. So, to use the
textClean() function inside module
print( toolkit.textClean('Test Message') )
Trying to directly call
textClean() will result in an error, since it won't know where to find that function without the
print( textClean('Test Message') )
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-10-f66b8a0326dc> in <module> ----> 1 print( textClean('Test Message') ) NameError: name 'textClean' is not defined
import toolkit as tk
print( tk.caesarEncipher('Test', 7) )
from toolkit import textClean, caesarEncipher
print( textClean('This is Pretty Lazy, but it works') )
from toolkit import *
Don't do this! Doing so will import everything inside the module including functions, objects, etc into your Notebook. This is bad because:
- It could take a long time or use up a lot of memory
- It could overwrite variables or functions of the same name in your Notebook
- If you didn't write the module, you don't know what it's importing
Over time people have developed really powerful modules that can do tasks far beyond what a novice programmer could accomplish. Collections of modules can be grouped together in what are known as packages. Instead of keeping these modules to themselves, the Python Software Foundation has set up a publicly accessible database of packages, found at https://pypi.org. We'll use a few of these packages in this course to generate bar charts, generate random numbers, and apply hash functions.