Modules - Python: Programming Language for Beginners - Learn In A Day! (2015)

Python: Programming Language for Beginners - Learn In A Day! (2015)

Chapter 11. Modules

Overview

There is a wide collection or rather a wide range of modules in the standard library of Python. There are all kinds of modules present in the Python library. Each of them is designed for performing a specific task. Almost all the functions are covered in these modules. Directly or indirectly, all large programs in python use these modules. In simple words, to get the classes into various programs, we store them in modules and import them into other programs. We will learn about these modules in this chapter.

Definition of a Module

A python file which contains only definitions of variables, functions, and classes is a module. Consider an example.

Example - moduletest.py

### EXAMPLE PYTHON MODULE

numberone = 1

ageofqueen = 78

# define some functions

def printhello():

print "hello everyone"

def timesfour(input):

print input * 4

# define a class

class Piano:

def __init__(self):

self.type = raw_input("What type of sky")

self.height = raw_input("What height (in kms) ")

self.price = raw_input("How much did you pay ")

self.age = raw_input("How far it is? ")

def printdetails(self):

print "The sky is” + self.height + " foot",

print self.type, "piano, " + self.age, "years old and costs\

" + self.price + " dollars."

A module looks similar to a normal python program. The purpose of a module is to import its parts from other programs to import functions, variables and classes from moduletest.py (above written code) in another program that you are writing, you can use the import operator. Like, for importing moduletest.py into the main program, we can do something like this:

Example - mainprogram.py

### mainprogam.py

### IMPORTS ANOTHER MODULE

import moduletest

This predicts that the module is in the same directory as mainprogram.py. We can have import statement anywhere inside the program. To use all the properties in the module in your main program, try this:

Example - mainprogram.py continued

### USING AN IMPORTED MODULE

print moduletest.ageofqueen

cfcpiano = moduletest.Piano()

cfcpiano.printdetails()

Built-in Functions and Exceptions

There are two basic modules in Python. They are 1. Built-in functions and 2. Exceptions. When Python is initiated, it will import both these modules, making the content in these modules available to all programs. They are explained below.

Built-in Functions:

In this module, python has all the built-in functions. These built-in functions are available in all of the modules that are there in python. Python will automatically import the Built-in module for you, leaving you the worry of importing it every time.

Calling a function with arguments from a tuple or dictionary

In Python, you can build your own function argument list. You can do this by putting all the arguments in a tuple and calling the ‘apply’ function. This ‘apply’ function is also a built in function. Here is an example which will give you a better understanding of the ‘apply’ function.

Example: Utilizing the apply function

# File:builtin-apply-example-1.py

def function(a, b):

print a, b

apply(function, ("whither", "canada?"))

apply(function, (1, 2 + 3))

whither canada?

1 5

You can use the dictionary as the 3rd argument to ‘apply’ for passing keyword arguments to a given function. The below example will show you how to use the ‘apply’ function for passing the keyword arguments.

Example: Passing keyword arguments using the ‘apply’ function.

# File:builtin-apply-example-2.py

def function(a, b):

print a, b

apply(function, ("crunchy", "frog"))

apply(function, ("crunchy",), {"b": "frog"})

apply(function, (), {"a": "crunchy", "b": "frog"})

crunchy frog

crunchy frog

crunchy frog

The ‘apply’ function is also widely used for passing constructor arguments that are in the subclass to the base class or the parent class. This is usually done when there are a lot of arguments present in the constructor.

Here is an example showing the use of the apply function for calling the functions from the base class.

Example: Calling the base class functions using the apply function.

# File:builtin-apply-example-3.py

class Rectangle:

def __init__(self, color="white", width=10, height=10):

print "create a", color, self, "sized", width, "x", height

class RoundedRectangle(Rectangle):

def __init__(self, **kw):

apply(Rectangle.__init__, (self,), kw)

rect = Rectangle(color="green", height=100, width=100)

rect = RoundedRectangle(color="blue", height=20)

create a green <Rectangle instance at 8c8260> sized 100 x 100

create a blue <RoundedRectangle instance at 8c84c0> sized 10 x 20

Python 2.0 provides an alternate syntax. Instead of apply, you can use an ordinary function call, and

use * to mark the tuple, and ** to mark the dictionary.

The following two statements are equivalent:

result = function(*args, **kwargs)

result = apply(function, args, kwargs)

Loading and reloading modules

Any professional Python programmer will know that with the import statement, he can call external modules. But you should also know that the import is used to delegate the work to a built-in function called ‘import’.

Here is an example program using the import function.

Example: Using the __import__ function to load named modules

# File:builtin-import-example-1.py

import glob, os

modules = []

for module_file in glob.glob("*-plugin.py"):

try:

module_name, ext = os.path.splitext(os.path.basename(module_file))

module = __import__(module_name)

modules.append(module)

except ImportError:

pass # ignore broken modules

# say hello to all modules

for module in modules:

module.hello()

example-plugin says hello

Here are a few more examples where the ‘import’ function is used.

Example: Implementing the lazy-import using the import function

# File:builtin-import-example-3.py

class LazyImport:

def __init__(self, module_name):

self.module_name = module_name

self.module = None

def __getattr__(self, name):

if self.module is None:

self.module = __import__(self.module_name)

return getattr(self.module, name)

string = LazyImport("string")

print string.lowercase

abcdefghijklmnopqrstuvwxyz

For reloading the modules that are already imported, Python provides the users with some basic support. Here is an example given below, where hello.py file will be loaded three times. Python provides some basic support for reloading modules that you've already imported. The following example loads the hello.py file three times.

Example: Implementing the reload function

# File:builtin-reload-example-1.py

import hello

reload(hello)

reload(hello)

hello again, and welcome to the show

hello again, and welcome to the show

hello again, and welcome to the show

reload will not be using the variable name, but the module name which the module object is associated with. With this, ‘reload’ will still be able to find the module (original), even if the module is renamed.

You should note that, in the module dictionary, the old module will be replaced by the new one after being recompiled. But there are instances of the class are in that particular module, they will continue to use the old implementation. Similarly, when you use ‘from-import’ function for creating module members for other modules, those references will remain the same and they won’t be updated.

More modules

Using the from operator helps you import only the required objects into the program.

Example - importing individual objects

### IMPORT ITEMS DIRECTLY INTO YOUR PROGRAM

# import them

from moduletest import ageofqueen

from moduletest import printhello

# now try using them

print ageofqueen

printhello()

Using * operator we can import all objects of the module into the program.

File I/O

We use open() function to open a new text file. The mode of opening a file can be passed as a parameter like ‘r’ for read, ‘w’ for write etc.

Example -Opening a file

openfile = open('pathtofile', 'r')

openfile.read()

To set the location of the cursor, use the seek() function.

Syntax: seek(offset, whence).

whence is an optional program, and it determines where you should seek from. When the value of whence is 0; counting is done from the beginning, if it is 1, the bytes are counted from the current present cursor position and if it is 2, counting is done from the bottom of the file.

Offset describes just how far should your cursor move from whence.

Example:

openfile.seek(4,0) would move the cursor to 4 letters after the beginning of the file.

openfile.seek(1,1) would move the cursor to 1 letters after the current cursor position.

openfile.seek(-7,2) would move the cursor to 7 letters before the end of the file.

Other I/O Functions

There are a lot of functions, which help you do many things and make things really easy. Let us take a look at the various functions like tell(), readline(), readlines(), write() and close().

tell() returns the position of cursor on the file. It has no specific parameters. It is useful to know what is being referred to, where it is, and simple controlling of the cursor. Type fileobjectname.tell(), where fileobjectname is the name of the file object that is created when the file gets opened.

readline() reads the file from the point of the cursor till the end of the row. A new row starts after you press the enter tab. No parameters have to be passed to readline().You have an option of giving the maximum bytes to read. Use it with the fileobjectname.readline().

readlines() is similar to readline(), but it reads multiple lines at a time and returns with a list each holding lines of code. Use it with fileobjectname.readlines().

Example - example text file

Line 1

Line 3

Line 4

Line 6

then the returned list from readlines() would be:

Table 1 - resulting list from readlines

Index

Value

0

'Line 1'

1

''

2

'Line 3'

3

'Line 4'

4

''

5

'Line6'

The write() helps to write in a file. It writes beginning from the spot where the cursor is placed and overwrites the text ahead of it. e.g. fileobjectname.write('this is a string').

Close(),is used to close a file. E.g. fileobjectname.close().

Pickles

Pickles are the objects that are saved to a file. An object could be a variable, like in case of a class, list, dictionary, tuple. The objects can be restored later. In short we save the objects in pickles.Objects can be saved using dump() in the module of the pickle. Then open any empty file, and use pickle.dump() to drop the objects in the file.

Example - pickletest.py

### pickletest.py

### PICKLE AN OBJECT

import pickle

picklelist = ['one',2,'three','four',5,'can you count?']

file = open('filename', 'w')

pickle.dump(picklelist,file)

file.close()

The code for this is: pickle.load(object_to_pickle, file_object) where:

object_to_pickle is the object that you want to pickle.

file_object is the file object that you want to write to.

Now to open your file again, to do this, we will use pickle.load():

Example - unpickletest.py

### unpickletest.py

### unpickle file

import pickle

unpicklefile = open('filename', 'r')

unpickledlist = pickle.load(unpicklefile)

unpicklefile.close()

for item in unpickledlist:

print item

Limitations:

Only one object is possible to be created for a file.

Exceptions and exception handling

It is common for a programmer to encounter errors. Errors are of different severities. Some errors are recoverable, which means they’ll let the program run, while some of them can even crash the program. These errors can be spotted with the help of programming technologies which ‘throw’ an ‘exception’. These are called ‘exception handlers’.

Catching an Exception

Python, like several other programming languages, has its own ‘exception handlers’. It will spot when there is an exception thrown, so that when that happens you can write a piece of code which will avoid it. This is known as ‘exception catching’ or ‘catching an exception’. And the code which you write to avoid or rather ‘handle’ such exceptions is called as an ‘exception handler’. With these ‘exception handlers’ in your code, it’ll be easy to spot and avoid errors that may interfere with your program’s execution. These handlers avoid flaky programs from crashing. These will let you know when some error is thrown.

Consider the below given error prone code:

def menu(list, question):

for entry in list:

print 1 + list.index(entry),

print ") " + entry

return input(question) - 1

# running the function

# remember what the backslash does

answer = menu(['A','B','C','D','E','F','H','I'],\

'Which letter is your favourite? ')

print 'You picked answer ' + (answer + 1)

Bugs - The Human Errors:

It is to be noted that many errors are because of the carelessness of the programmer. There are many code listings and files for single errors, since the error might have occurred with the interaction between the two lines of code.

Example - calling the menu function

answer = menu(['A','B','C','D','E','F','H','I'],\

'Which letter is your favourite? ')

Example -Where it went wrong

return raw_input(question) – 1

raw_input always returns a string, so it is a setback. Let's change it to input(), that returns a number when you give number as an input:

Example -Fixing it

return input(question) – 1

Exceptions – The Limitations of Code

In the code what if we type some random text instead of std datatype to be given. That’s when exceptions come into picture. We can overcome these exceptions using ‘try.’

Example -The try operator

try:

function(world, parameters)

except:

print world.errormsg

Now let’s put the error prone part in the ‘try’ block and check what happens. The menu is:

Example -testing our fix

def menu(list, question):

for entry in list:

print 1 + list.index(entry),

print ") " + entry

try:

return input(question) - 1

except NameError:

print "Enter a valid number”

Let’s have a look at another error.

Example -Yet another error message

Traceback (most recent call last):

File "/home/steven/errortest.py", line 12, in -toplevel-

print 'You picked answer', (answer + 1)

TypeError:unsupported operand type(s) for+: 'NoneType' and 'int'

The solution to the above error.

Example - yet another solution

answer = menu(['A','B','C','D','E','F','H','I'],\

'Which letter is your favourite? ')

try:

print 'You picked answer', (answer + 1)

except:

print '\nincorrect answer.'

Endless Errors:

Problems we face by using many except statement is that no error will be detected.

Example -The Problem We Face

print 'Subtraction program, v0.0.1 (beta)'

a = input('Enter a number to subtract from> ')

b = input('Enter the number to subtract> ')

print a – b

It works only if you give two numbers. If you give an alphabet, it will show NameError:

Example - Dealing With NameError

print 'Subtraction program, v0.0.2 (beta)'

loop = 1

while loop == 1:

try:

a = input('Enter a number to subtract from > ')

b = input('Enter the number to subtract > ')

except NameError:

print "\n Subtraction of a letter isn’t possible”

continue

print a - b

try:

loop = input('1 to try again')

except NameError:

loop = 0

If there are any syntax errors they are to be dealt as given below:

Example – SyntaxErrors to be dealt with

print 'Subtraction prog, v00.3 (alpha)'

loop = 1

while loop == 1:

try:

a = input('Enter a number to subtract from > ')

b = input('Enter the number to subtract > ')

except NameError:

print "\nYou cannot subtract a letter"

continue

except SyntaxError:

print "\nDo not enter anything other than number”

continue

print a - b

try:

loop = input('Press 1 to try again > ')

except (NameError,SyntaxError):

loop = 0

Here the multiple excepts deal with different problems. Instead we can write all exceptions in a single except statement using parenthesis.

Conclusion

So, we are done with the basics of python starting from the simplest concept of variables and constants to the moderate concept i.e. the object oriented programming which can also be called as the heart of programming and finally to the complex concepts like file I/O, errors handling, exceptions etc.

The fundamental of loops, modules and conditional statements will be of great help in building a standalone application without much difficulty. The nature of the language being simple, interpreted and object oriented separates it from the other scripting languages. The ease of coding and developing applications in python adds glitters to this scripting language.

I hope you get inspired and try out new things and bring a new revolution in the era of scripting languages.

Good Luck!