Modules in Python
What is a Python module?
A module in Python is a collection of code that can be used in other programs. You can think of a module as being like a toolbox, where another program can import all or just a few of the tools found in the module. Here are some reasons to use modules, and some examples of their use.
Why use modules?
One reason is organization. Modules organize code the same way folders organize files. If you’re writing only small snippets of code you probably don’t need a module, just like you probably don’t need a folder to organize only a few files you’re working with on your computer. But once a program starts to get big, modules are a good way to organize code.
Another reason is convenience. If you have many programs that will use the same function, it’s best to put that shared function in a module. That way, if you want to change anything in the way that function works, you only have to change it once (in the module) as opposed to changing it in every program you ever used it in (if you didn’t use a module).
How do you make a module?
Any Python script can act as a module. You don’t have to do anything special.
How do you use a module?
To use a module in another script, you have to import the module into the script. There are a couple of ways you can do this, and the way you choose depends on how you want to refer to the contents of the module.
How about an example?
OK.
Say we have some Python code saved as the file “usefulStuff.py” in our current working directory, and usefulStuff.py has three extremely useful functions in it:
winningLotteryNumberswhatToMakeForDinnerdoSomethingToHardDrive
It looks something like this:
usefultStuff.py <-- the module
"""A module full of useful stuff."""
num = 5 # just a variable created now, to make a point later...
def winningLotteryNumbers();
# some code here
def whatToMakeForDinner():
# some code here
def doSomethingToHardDrive();
# some code here
OK, so let’s write a new script in the same directory as usefulStuff.py is saved in. For our new script, we only want to use two of those functions. To use them, we need to import them using one of the following methods:
Importing a module: Method 1 (best)
script1.py
import usefulStuff
x = usefulStuff.winningLotteryNumbers()
y = usefulStuff.whatToMakeForDinner()
numberFive = usefulStuff.num
Note that in order to access the functions, you have to specify where they are coming from: the usefulStuff module. We imported these two functions into the usefulStuff namespace of this script. The last line shows that we can access the variable num that was created in usefulStuff.py. That is, numberFive will now point to the number 5.
This is probably the best method to use. It keeps things organized and is unambiguous. The downside? Lots of typing.
Importing a module: Method 2
script2.py
import usefulStuff as u
x = u.winningLotteryNumbers()
y = u.whatToMakeForDinner()
numberFive = u.num
This is similar to above, since to access the functions you still have to specify from which namespace they are coming from. But in this case, the namespace has been renamed to u. Why? Simply to make it easier to type.
Importing a module: Method 3
script3.py
from usefulStuff import winningLotteryNumbers, whatToMakeForDinner
x = winningLotteryNumbers()
y = whatToMakeForDinner()
numberFive = num # see warning 1
Here, the only things imported are the items specified in the import statement. What namespace do they occur in? The namespace of the script, script1.py. The advantage? Less typing! For small scripts, this is probably the way to go. But if this script gets very large, and we want to make our own functions or variables with similar names within it, we might need the tighter organization of keeping namespaces separate.
By the way, if we wanted to access the doSomethingToHardDrive module, we’d have to add it to the list of things to import on the first line.
Warning 1: What does numberFive point to? Remember, we didn’t import the variable num from usefulStuff, so this script doesn’t know it exists. the result is that we’d get a NameError saying that num doesn’t exist.
Importing a module: Method 4
script4.py
from usefulStuff import *
x = winningLotteryNumbers()
y = whatToMakeForDinner()
Using this method, EVERYTHING from usefulStuff was imported into this script’s namespace, including the doSomethingToHardDrive function. For a script this small, it’s not really an issue, but for larger programs, this can introduce all kinds of annoying bugs, not to mention cluttering the namespace with unused functions and variables. Probably best to stay away from this method of importing.
Comparison to Matlab
If you’ve used Matlab before, you know that you use functions by naming the m-file after the name of the function. Then, as long as the function is in your path, Matlab will find it. This works well for small scripts. But as you start writing larger programs, you keep creating unique function names to avoid name conflicts. The Python method of using modules is to keep things organized, and is really helpful in larger programs.
Tags: Python