A Smooth Refresher on Python’s Modules
February 26, 2016 - Uncategorized
This will be the last tutorial in the Python refreshers series. Of course, I cannot conclude this series unless I move you to the next level in programming, that is, working with modules, which are considered fundamental when handling non-trivial programming tasks.
Nontrivial programming tasks most of the time mean long programs with many lines of code. Modules come in handy as they attempt to break such complex programs into manageable chunks and enable code reuse. This way, you will also be able to use the code at any time by importing that module. You can also solve the issue of copying some function many times in different programs by managing it through modules.
Let’s go ahead to the meat of the tutorial, and see how we can work with modules in Python.
Modules in Python
When you created Python programs, you used to put them in some source file ending with
.py. Modules in Python are simply created that way. That is, they are source files ending with
.py, and located in a directory where Python is able to find them (i.e. the current working directory or listed in sys.path).
Modules normally contain statements that are related to each other. As mentioned above, we can use modules at any time. Using a module means using the code (i.e. variables, functions) stored in that module. The process of bringing up and using such code is called importing.
Creating a module in Python is very simple. Let’s say we wanted to create a module that would print someone’s name. Type the following code using your favorite editor, and save it as
myname.py. This will be your module name excluding the
.py part, which will be assigned to the global variable
def print_name(n): print 'Hi', n
If you have another Python file where you are interested in using the code in the module defined above, we will import the module using the
import keyword, as follows:
import myname name.print_name('Abder')
The output of this script will be:
Be sure that Python is able to find the imported file. For instance, put it in the same directory as the Python file where you used
As you can see, importing a module enables us to enhance our program by adding new functionality to it from external files (i.e. modules).
But, what is happening here behind the scenes? When you
import a module, Python compiles that module and generates a
.pyc file, and a program is only recompiled if the
.py is newer than the
Let’s take another example, but this time with a Python built-in module. Let’s choose the math module. In this example, for a number we pass we want to find the ceiling (the smallest integer value greater than or equal to the number), floor (largest integer value less than or equal to the number), and the absolute value of that number. The Python script for this program looks as follows:
import math x = 4.7 print 'The ceiling of ' + str(x) + ' is: ' + str(math.ceil(x)) print 'The floor of ' + str(x) + ' is: ' + str(math.floor(x)) print 'The absolute value of ' + str(x) + ' is: ' + str(math.fabs(x))
If you run this script, the output should look as follows:
The ceiling of 4.7 is: 5.0 The floor of 4.7 is: 4.0 The absolute value of 4.7 is: 4.7
So, we were able to apply different operations on our number without writing code for each operation, but rather by reusing already available functions in the
math module. That helps a lot, doesn’t it?
You might be wondering, should we always use the
math.function() notation? Can’t we use the function immediately without preceding it with the module name (i.e.
math)? Yes, you can do that by using the following syntax for the
from math import *
This way, you can call the previous functions (
fabs(x)) without the need to precede them with the module name,
Modules as Scripts
Let’s come back to our simple module,
def print_name(n): print 'Hi', n
Can we treat this module as a standalone (main) script that we can directly run and pass arguments to from the command line? For instance, what will happen if you typed the following in your command line?
python myname.py 'Abder'
Nothing! Try it—you will not get any output.
In order to be able to run the module as a script, we have to set
__name__ = '__main__‘. So, the module
myname will now look as follows:
def print_name(n): print 'Hi', n if __name__ == '__main__': import sys print_name(sys.argv)
If you run this command in your terminal:
python myname.py 'Abder', you should get the following output:
An important concept that comes hand in hand with modules is that of packages. A package is a collection of modules. In other words, while a module is a file, a package is a directory/folder. It is a way by which we structure the modules by using dotted module names. So if you see an
import statement that looks like:
This means we have a module called
department in the package
As we can see, using modules enables us to split a complex program into manageable chunks, making it easier to track any errors in the program, understanding its functionality better, and enabling reusability.
With this, we come to the end of the Python refreshers series. In this series, we have learned the basics and necessary concepts one needs to grasp in order to move further in the Python programming language. We have learned the concepts of lists, dictionaries, and tuples. We have also learned how to make decisions through conditions (link to Python conditions), and repeat through loops (link to Python loops). We have also learned how to work with functions, create classes and instantiate them (i.e. objects), and package our work in modules.
Source: Photoshop | Tuts