0% found this document useful (0 votes)
15 views

Unit V

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Unit V

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

142

UNIT V
FILES, MODULES, PACKAGES
Files and exception: text files, reading and writing files, format operator; command
line arguments, errors and exceptions, handling exceptions, modules, packages;
Illustrative programs: word count, copy file.
5. FILES
5.1 PRINTING TO THE SCREEN
The simplest way to produce output is using the print statement where you can
pass zero or more expressions separated by commas. This function converts the
expressions you pass into a string and writes the result to standard output as
follows

#!/usr/bin/python

print "Python is really a great language"

5.1.1 READING KEYBOARD INPUT


Python provides two built-in functions to read a line of text from standard input,
which by default comes from the keyboard. These functions are −

 raw_input

 input

5.1.2 THE RAW_INPUT FUNCTION
The raw_input([prompt]) function reads one line from standard input and returns
it as a string (removing the trailing newline).

#!/usr/bin/python

str = raw_input("Enter your input: ");


print "Received input is : ", str
This prompts you to enter any string and it would display same string on the
screen. When I typed "Hello Python!", its output is like this −
143

Enter your input: Hello Python


Received input is : Hello Python
The input Function
The input([prompt]) function is equivalent to raw_input, except that it assumes
the input is a valid Python expression and returns the evaluated result to you.

#!/usr/bin/python

str = input("Enter your input: ");


print "Received input is : ", str
This would produce the following result against the entered input −

Enter your input: [x*5 for x in range(2,10,2)]


Recieved input is : [10, 20, 30, 40]
Opening and Closing Files
Until now, you have been reading and writing to the standard input and output.
Now, we will see how to use actual data files.

Python provides basic functions and methods necessary to manipulate files by


default. You can do most of the file manipulation using a file object.

The open Function
Before you can read or write a file, you have to open it using Python's built-
in open() function. This function creates a file object, which would be utilized to
call other support methods associated with it.

Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details:

 file_name: The file_name argument is a string value that contains the name


of the file that you want to access.

 access_mode: The access_mode determines the mode in which the file has


to be opened, i.e., read, write, append, etc. A complete list of possible
144

values is given below in the table. This is optional parameter and the default
file access mode is read (r).

 buffering: If the buffering value is set to 0, no buffering takes place. If the


buffering value is 1, line buffering is performed while accessing a file. If
you specify the buffering value as an integer greater than 1, then buffering
action is performed with the indicated buffer size. If negative, the buffer
size is the system default(default behavior).

Here is a list of the different modes of opening a file −

Mode Description
s

R Opens a file for reading only. The file pointer is


placed at the beginning of the file. This is the
default mode.

Rb Opens a file for reading only in binary format.


The file pointer is placed at the beginning of the
file. This is the default mode.

r+ Opens a file for both reading and writing. The


file pointer placed at the beginning of the file.

rb+ Opens a file for both reading and writing in


binary format. The file pointer placed at the
beginning of the file.

W Opens a file for writing only. Overwrites the file


if the file exists. If the file does not exist, creates
a new file for writing.

Wb Opens a file for writing only in binary format.


Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.

w+ Opens a file for both writing and reading.


145

Overwrites the existing file if the file exists. If


the file does not exist, creates a new file for
reading and writing.

wb+ Opens a file for both writing and reading in


binary format. Overwrites the existing file if the
file exists. If the file does not exist, creates a
new file for reading and writing.

A Opens a file for appending. The file pointer is at


the end of the file if the file exists. That is, the
file is in the append mode. If the file does not
exist, it creates a new file for writing.

Ab Opens a file for appending in binary format.


The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If
the file does not exist, it creates a new file for
writing.

a+ Opens a file for both appending and reading.


The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the
file does not exist, it creates a new file for
reading and writing.

ab+ Opens a file for both appending and reading in


binary format. The file pointer is at the end of
the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates
a new file for reading and writing.

5.1.3 THE FILE OBJECT ATTRIBUTES


Once a file is opened and you have one file object, you can get various
information related to that file.

Here is a list of all attributes related to file object:


146

Attribute Description

file.closed Returns true if file is closed, false


otherwise.

file.mode Returns access mode with which file was


opened.

file.name Returns name of the file.

file.softspac Returns false if space explicitly required


e with print, true otherwise.

Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
This produces the following result −

Name of the file: foo.txt


Closed or not : False
Opening mode : wb
Softspace flag : 0
The close() Method
The close() method of a file object flushes any unwritten information and closes
the file object, after which no more writing can be done.

Python automatically closes a file when the reference object of a file is reassigned
to another file. It is a good practice to use the close() method to close a file.
147

Syntax
fileObject.close();
Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name

# Close opend file


fo.close()
This produces the following result −

Name of the file: foo.txt

5.1.4 READING AND WRITING FILES


The file object provides a set of access methods to make our lives easier. We
would see how to use read() and write() methods to read and write files.

The write() Method
The write() method writes any string to an open file. It is important to note that
Python strings can have binary data and not just text.

The write() method does not add a newline character ('\n') to the end of the string

Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.

Example
#!/usr/bin/python
148

# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");

# Close opend file


fo.close()
The above method would create foo.txt file and would write given content in that
file and finally it would close that file. If you would open this file, it would have
following content.

Python is a great language.


Yeah its great!!
The read() Method
The read() method reads a string from an open file. It is important to note that
Python strings can have binary data. apart from text data.

Syntax
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file.
This method starts reading from the beginning of the file and if count is missing,
then it tries to read as much as possible, maybe until the end of file.

Example
Let's take a file foo.txt, which we created above.

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
149

This produces the following result −

Read String is : Python is


5.1.5 FILE POSITIONS
The tell() method tells you the current position within the file; in other words, the
next read or write will occur at that many bytes from the beginning of the file.

The seek(offset[, from]) method changes the current file position.


The offsetargument indicates the number of bytes to be moved.
The from argument specifies the reference position from where the bytes are to be
moved.

If from is set to 0, it means use the beginning of the file as the reference position
and 1 means use the current position as the reference position and if it is set to 2
then the end of the file would be taken as the reference position.

Example
Let us take a file foo.txt, which we created above.

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str

# Check current position


position = fo.tell();
print "Current file position : ", position

# Reposition pointer at the beginning once again


position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
150

# Close opend file


fo.close()
This produces the following result −

Read String is : Python is


Current file position : 10
Again read String is : Python is
5.1.6 RENAMING AND DELETING FILES
Python os module provides methods that help you perform file-processing
operations, such as renaming and deleting files.

To use this module you need to import it first and then you can call any related
functions.

The rename() Method


The rename() method takes two arguments, the current filename and the new
filename.

Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt:

#!/usr/bin/python
import os

# Rename a file from test1.txt to test2.txt


os.rename( "test1.txt", "test2.txt" )
The remove() Method
You can use the remove() method to delete files by supplying the name of the file
to be deleted as the argument.

Syntax
os.remove(file_name)
151

Example
Following is the example to delete an existing file test2.txt −

#!/usr/bin/python
import os

# Delete file test2.txt


os.remove("text2.txt")
5.1.7 DIRECTORIES IN PYTHON
All files are contained within various directories, and Python has no problem
handling these too. The os module has several methods that help you create,
remove, and change directories.

The mkdir() Method
You can use the mkdir() method of the os module to create directories in the
current directory. You need to supply an argument to this method which contains
the name of the directory to be created.

Syntax
os.mkdir("newdir")
Example
Following is the example to create a directory test in the current directory −

#!/usr/bin/python
import os

# Create a directory "test"


os.mkdir("test")
The chdir() Method
You can use the chdir() method to change the current directory. The chdir()
method takes an argument, which is the name of the directory that you want to
make the current directory.

Syntax
152

os.chdir("newdir")
Example
Following is the example to go into "/home/newdir" directory −

#!/usr/bin/python
import os

# Changing a directory to "/home/newdir"


os.chdir("/home/newdir")
The getcwd() Method
The getcwd() method displays the current working directory.

Syntax
os.getcwd()
Example
Following is the example to give current directory −

#!/usr/bin/python
import os

# This would give location of the current directory


os.getcwd()
The rmdir() Method
The rmdir() method deletes the directory, which is passed as an argument in the
method.

Before removing a directory, all the contents in it should be removed.

Syntax:
os.rmdir('dirname')
Example
153

Following is the example to remove "/tmp/test" directory. It is required to give


fully qualified name of the directory, otherwise it would search for that directory
in the current directory.

#!/usr/bin/python
import os

# This would remove "/tmp/test" directory.


os.rmdir( "/tmp/test" )
5.1.8 FILE & DIRECTORY RELATED METHODS
There are three important sources, which provide a wide range of utility methods
to handle and manipulate files & directories on Windows and Unix operating
systems. They are as follows −

 File Object Methods: The file object provides functions to manipulate files.

 OS Object Methods: This provides methods to process files as well as


directories.

5.2 EXCEPTION
Python provides two very important features to handle any unexpected error in
your Python programs and to add debugging capabilities in them −

 Exception Handling: This would be covered in this tutorial. Here is a list


standard Exceptions available in Python: Standard Exceptions.

 Assertions: This would be covered in Assertions in Python tutorial.

List of Standard Exceptions −

EXCEPTION DESCRIPTION
NAME

Exception Base class for all exceptions

StopIteration Raised when the next() method


of an iterator does not point to
154

any object.

SystemExit Raised by the sys.exit() function.

StandardError Base class for all built-in


exceptions except StopIteration
and SystemExit.

ArithmeticError Base class for all errors that


occur for numeric calculation.

OverflowError Raised when a calculation


exceeds maximum limit for a
numeric type.

FloatingPointError Raised when a floating point


calculation fails.

ZeroDivisionError Raised when division or modulo


by zero takes place for all
numeric types.

AssertionError Raised in case of failure of the


Assert statement.

AttributeError Raised in case of failure of


attribute reference or
assignment.

EOFError Raised when there is no input


from either the raw_input() or
input() function and the end of
file is reached.

ImportError Raised when an import statement


fails.
155

KeyboardInterrupt Raised when the user interrupts


program execution, usually by
pressing Ctrl+c.

LookupError Base class for all lookup errors.

IndexError Raised when an index is not


found in a sequence.
KeyError
Raised when the specified key
is not found in the dictionary.

NameError Raised when an identifier is not


found in the local or global
namespace.
UnboundLocalError Raised when trying to access a
local variable in a function or
EnvironmentError method but no value has been
assigned to it.

Base class for all exceptions


that occur outside the Python
environment.

IOError Raised when an input/ output


operation fails, such as the print
IOError statement or the open() function
when trying to open a file that
does not exist.

Raised for operating system-


related errors.

SyntaxError Raised when there is an error in


Python syntax.
IndentationError
Raised when indentation is not
156

specified properly.

SystemError Raised when the interpreter finds


an internal problem, but when
this error is encountered the
Python interpreter does not exit.
SystemExit Raised when Python interpreter
is quit by using the sys.exit()
function. If not handled in the
code, causes the interpreter to
exit.
TypeError Raised when an operation or
function is attempted that is
invalid for the specified data
type.
ValueError Raised when the built-in
function for a data type has the
valid type of arguments, but the
arguments have invalid values
specified.
RuntimeError Raised when a generated error
does not fall into any category.
NotImplementedError Raised when an abstract method
that needs to be implemented in
an inherited class is not actually
implemented.
5.2.1ASSERTIONS IN PYTHON
An assertion is a sanity-check that you can turn on or turn off when you are done
with your testing of the program.

The easiest way to think of an assertion is to liken it to a raise-if statement (or to


be more accurate, a raise-if-not statement). An expression is tested, and if the
result comes up false, an exception is raised.

Assertions are carried out by the assert statement, the newest keyword to Python,
introduced in version 1.5.
157

Programmers often place assertions at the start of a function to check for valid
input, and after a function call to check for valid output.

The assert Statement
When it encounters an assert statement, Python evaluates the accompanying
expression, which is hopefully true. If the expression is false, Python raises
an AssertionError exception.

The syntax for assert is −

assert Expression[, Arguments]


If the assertion fails, Python uses ArgumentExpression as the argument for the
AssertionError. AssertionError exceptions can be caught and handled like any
other exception using the try-except statement, but if not handled, they will
terminate the program and produce a traceback.

Example
Here is a function that converts a temperature from degrees Kelvin to degrees
Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if
it sees a negative temperature −

#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
When the above code is executed, it produces the following result −

32.0
451
Traceback (most recent call last):
File "test.py", line 9, in
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
158

AssertionError: Colder than absolute zero!

An exception is an event, which occurs during the execution of a program that


disrupts the normal flow of the program's instructions. In general, when a Python
script encounters a situation that it cannot cope with, it raises an exception. An
exception is a Python object that represents an error.

When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.

5.2.2 HANDLING AN EXCEPTION


If you have some suspicious code that may raise an exception, you can defend
your program by placing the suspicious code in a try: block. After the try: block,
include an except: statement, followed by a block of code which handles the
problem as elegantly as possible.

Syntax
Here is simple syntax of try....except...else blocks −

try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Here are few important points about the above-mentioned syntax −

 A single try statement can have multiple except statements. This is useful
when the try block contains statements that may throw different types of
exceptions.

 You can also provide a generic except clause, which handles any exception.
159

 After the except clause(s), you can include an else-clause. The code in the
else-block executes if the code in the try: block does not raise an exception.

 The else-block is a good place for code that does not need the try: block's
protection.

Example
This example opens a file, writes content in the, file and comes out gracefully
because there is no problem at all −

#!/usr/bin/python

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
This produces the following result −

Written content in the file successfully


Example
This example tries to open a file where you do not have write permission, so it
raises an exception −

#!/usr/bin/python

try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
160

print "Error: can\'t find file or read data"


else:
print "Written content in the file successfully"
This produces the following result −

Error: can't find file or read data


The except Clause with No Exceptions
You can also use the except statement with no exceptions defined as follows −

try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using
this kind of try-except statement is not considered a good programming practice
though, because it catches all exceptions but does not make the programmer
identify the root cause of the problem that may occur.

The except Clause with Multiple Exceptions


You can also use the same except statement to handle multiple exceptions as
follows −

try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
161

else:
If there is no exception then execute this block.
The try-finally Clause
You can use a finally: block along with a try: block. The finally block is a place
to put any code that must execute, whether the try-block raised an exception or
not. The syntax of the try-finally statement is this −

try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
You cannot use else clause as well along with a finally clause.

Example
#!/usr/bin/python

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
If you do not have permission to open the file in writing mode, then this will
produce the following result:

Error: can't find file or read data


Same example can be written more cleanly as follows −

#!/usr/bin/python
162

try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
When an exception is thrown in the try block, the execution immediately passes to
the finally block. After all the statements in the finally block are executed, the
exception is raised again and is handled in the exceptstatements if present in the
next higher layer of the try-except statement.

5.2 .3 ARGUMENT OF AN EXCEPTION


An exception can have an argument, which is a value that gives additional
information about the problem. The contents of the argument vary by exception.
You capture an exception's argument by supplying a variable in the except clause
as follows −

try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow
the name of the exception in the except statement. If you are trapping multiple
exceptions, you can have a variable follow the tuple of the exception.

This variable receives the value of the exception mostly containing the cause of
the exception. The variable can receive a single value or multiple values in the
form of a tuple. This tuple usually contains the error string, the error number, and
an error location.

Example
163

Following is an example for a single exception −

#!/usr/bin/python

# Define a function here.


def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument

# Call above function here.


temp_convert("xyz");
This produces the following result −

The argument does not contain numbers


invalid literal for int() with base 10: 'xyz'
5.2.4 RAISING AN EXCEPTIONS
You can raise exceptions in several ways by using the raise statement. The general
syntax for the raise statement is as follows.

Syntax
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError)
and argument is a value for the exception argument. The argument is optional; if
not supplied, the exception argument is None.

The final argument, traceback, is also optional (and rarely used in practice), and if
present, is the traceback object used for the exception.

Example
An exception can be a string, a class or an object. Most of the exceptions that the
Python core raises are classes, with an argument that is an instance of the class.
Defining new exceptions is quite easy and can be done as follows −
164

def functionName( level ):


if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...
5.2.5 USER-DEFINED EXCEPTIONS
Python also allows you to create your own exceptions by deriving classes from the
standard built-in exceptions.

Here is an example related to RuntimeError. Here, a class is created that is


subclassed from RuntimeError. This is useful when you need to display more
specific information when an exception is caught.

In the try block, the user-defined exception is raised and caught in the except
block. The variable e is used to create an instance of the class Networkerror.

class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise the exception as follows −

try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
165

5.3 COMMAND LINE ARGUMENTS


Python provides a getopt module that helps you parse command-line options and
arguments.

$ python test.py arg1 arg2 arg3


The Python sys module provides access to any command-line arguments via
the sys.argv. This serves two purposes −

 sys.argv is the list of command-line arguments.


 len(sys.argv) is the number of command-line arguments.

Here sys.argv[0] is the program ie. script name.

Example
Consider the following script test.py −

#!/usr/bin/python

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'


print 'Argument List:', str(sys.argv)
Now run above script as follows −

$ python test.py arg1 arg2 arg3


This produce following result −

Number of arguments: 4 arguments.


Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
NOTE: As mentioned above, first argument is always script name and it is also
being counted in number of arguments.

Parsing Command-Line Arguments


Python provided a getopt module that helps you parse command-line options and
arguments. This module provides two functions and an exception to enable
command line argument parsing.
166

getopt.getopt method
This method parses command line options and parameter list. Following is simple
syntax for this method −

getopt.getopt(args, options, [long_options])


Here is the detail of the parameters −

 args: This is the argument list to be parsed.


 options: This is the string of option letters that the script wants to recognize,
with options that require an argument should be followed by a colon (:).
 long_options: This is optional parameter and if specified, must be a list of
strings with the names of the long options, which should be supported.
Long options, which require an argument should be followed by an equal
sign ('='). To accept only long options, options should be an empty string.
 This method returns value consisting of two elements: the first is a list
of (option, value) pairs. The second is the list of program arguments left
after the option list was stripped.
 Each option-and-value pair returned has the option as its first element,
prefixed with a hyphen for short options (e.g., '-x') or two hyphens for long
options (e.g., '--long-option').

5.3.1 EXCEPTION GETOPT.GETOPTERROR


This is raised when an unrecognized option is found in the argument list or when
an option requiring an argument is given none.

The argument to the exception is a string indicating the cause of the error. The
attributes msg and opt give the error message and related option

Example
Consider we want to pass two file names through command line and we also want
to give an option to check the usage of the script. Usage of the script is as follows

usage: test.py -i <inputfile> -o <outputfile>


Here is the following script to test.py −

#!/usr/bin/python
167

import sys, getopt

def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print 'Input file is "', inputfile
print 'Output file is "', outputfile

if __name__ == "__main__":
main(sys.argv[1:])
Now, run above script as follows −

$ test.py -h
usage: test.py -i <inputfile> -o <outputfile>

$ test.py -i BMP -o
usage: test.py -i <inputfile> -o <outputfile>
168

$ test.py -i inputfile
Input file is " inputfile

5.4 MODULES AND PACKAGES


A module allows you to logically organize your Python code. Grouping related
code into a module makes the code easier to understand and use. A module is a
Python object with arbitrarily named attributes that you can bind and reference.

Simply, a module is a file consisting of Python code. A module can define


functions, classes and variables. A module can also include runnable code.

Example
The Python code for a module named aname normally resides in a file
named aname.py. Here's an example of a simple module, support.py

def print_func( par ):


print "Hello : ", par
return
The import Statement
You can use any Python source file as a module by executing an import statement
in some other Python source file. The import has the following syntax:

import module1[, module2[,... moduleN]


When the interpreter encounters an import statement, it imports the module if the
module is present in the search path. A search path is a list of directories that the
interpreter searches before importing a module. For example, to import the
module support.py, you need to put the following command at the top of the script

#!/usr/bin/python

# Import module support


import support
169

# Now you can call defined function that module as follows


support.print_func("Zara")
When the above code is executed, it produces the following result −

Hello : Zara
A module is loaded only once, regardless of the number of times it is imported.
This prevents the module execution from happening over and over again if
multiple imports occur.

The from...import Statement
Python's from statement lets you import specific attributes from a module into the
current namespace. The from...import has the following syntax −

from modname import name1[, name2[, ... nameN]]


For example, to import the function fibonacci from the module fib, use the
following statement −

from fib import fibonacci


This statement does not import the entire module fib into the current namespace; it
just introduces the item fibonacci from the module fib into the global symbol table
of the importing module.

The from...import * Statement:
It is also possible to import all names from a module into the current namespace
by using the following import statement −

from modname import *


This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.

5.4.1 LOCATING MODULES


When you import a module, the Python interpreter searches for the module in the
following sequences −

 The current directory.


170

 If the module isn't found, Python then searches each directory in the shell
variable PYTHONPATH.

 If all else fails, Python checks the default path. On UNIX, this default path
is normally /usr/local/lib/python/.

The module search path is stored in the system module sys as


the sys.pathvariable. The sys.path variable contains the current directory,
PYTHONPATH, and the installation-dependent default.

The PYTHONPATH Variable:
The PYTHONPATH is an environment variable, consisting of a list of directories.
The syntax of PYTHONPATH is the same as that of the shell variable PATH.

Here is a typical PYTHONPATH from a Windows system:

set PYTHONPATH=c:\python20\lib;
And here is a typical PYTHONPATH from a UNIX system:

set PYTHONPATH=/usr/local/lib/python
5.4.2 NAMESPACES AND SCOPING
Variables are names (identifiers) that map to objects. A namespace is a dictionary
of variable names (keys) and their corresponding objects (values).

A Python statement can access variables in a local namespace and in the global


namespace. If a local and a global variable have the same name, the local variable
shadows the global variable.

Each function has its own local namespace. Class methods follow the same
scoping rule as ordinary functions.

Python makes educated guesses on whether variables are local or global. It


assumes that any variable assigned a value in a function is local.

Therefore, in order to assign a value to a global variable within a function, you


must first use the global statement.

The statement global VarName tells Python that VarName is a global variable.


Python stops searching the local namespace for the variable.
171

For example, we define a variable Money in the global namespace. Within the


function Money, we assign Money a value, therefore Python assumes Moneyas a
local variable. However, we accessed the value of the local variable Moneybefore
setting it, so an UnboundLocalError is the result. Uncommenting the global
statement fixes the problem.

#!/usr/bin/python

Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1

print Money
AddMoney()
print Money
The dir( ) Function
The dir() built-in function returns a sorted list of strings containing the names
defined by a module.

The list contains the names of all the modules, variables and functions that are
defined in a module. Following is a simple example −

#!/usr/bin/python

# Import built-in module math


import math

content = dir(math)

print content
When the above code is executed, it produces the following result −
172

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',


'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
Here, the special string variable __name__ is the module's name, and __file__is
the filename from which the module was loaded.

The globals() and locals() Functions −
The globals() and locals() functions can be used to return the names in the global
and local namespaces depending on the location from where they are called.

If locals() is called from within a function, it will return all the names that can be
accessed locally from that function.

If globals() is called from within a function, it will return all the names that can be
accessed globally from that function.

The return type of both these functions is dictionary. Therefore, names can be
extracted using the keys() function.

The reload() Function
When the module is imported into a script, the code in the top-level portion of a
module is executed only once.

Therefore, if you want to reexecute the top-level code in a module, you can use
the reload() function. The reload() function imports a previously imported module
again. The syntax of the reload() function is this −

reload(module_name)
Here, module_name is the name of the module you want to reload and not the
string containing the module name. For example, to reload hello module, do the
following −

reload(hello)
5.4.3 PACKAGES IN PYTHON
173

A package is a hierarchical file directory structure that defines a single Python


application environment that consists of modules and subpackages and sub-
subpackages, and so on.

Consider a file Pots.py available in Phone directory. This file has following line of


source code −

#!/usr/bin/python

def Pots():
print "I'm Pots Phone"
Similar way, we have another two files having different functions with the same
name as above −

 Phone/Isdn.py file having function Isdn()

 Phone/G3.py file having function G3()

Now, create one more file __init__.py in Phone directory −

 Phone/__init__.py
To make all of your functions available when you've imported Phone, you need to
put explicit import statements in __init__.py as follows −

from Pots import Pots


from Isdn import Isdn
from G3 import G3
After you add these lines to __init__.py, you have all of these classes available
when you import the Phone package.

#!/usr/bin/python

# Now import your Phone Package.


import Phone

Phone.Pots()
174

Phone.Isdn()
Phone.G3()
When the above code is executed, it produces the following result −

I'm Pots Phone


I'm 3G Phone
I'm ISDN Phone
In the above example, we have taken example of a single functions in each file,
but you can keep multiple functions in your files. You can also define different
Python classes in those files and then you can create your packages out of those
classes.

You might also like