A Quick Start Introduction to Python Programming - 3

Saturday, September 13, 2008

In this section, we will see some important built in functions like locals, globals and exception handling in python. If you want to read quick start introduction to python programming from the beginning, I would recommend you to visit "A Quickstart Introduction to Python Programming - 1".

6. Built in methods locals and globals

Put in a nutshell, the locals built in function will return a dictionary of all variables, methods and other data type names with their values as a key/value pair or all python object's and their attributes in the local namespace. Local namespace corresponds to all objects and their attributes within a python function or within a member function of a class. A global namespace corresponds to the module or all variables which are not in the local space are part of the global namespace at the module level.

The below example will make things clear.


#
# Locals Globals example
# locals_globals.py
# Author: S.Prasanna
#

import sys

def func():
""" A simple function to show locals, globals concept """
var1 = 10
print "Inside func, locals:", locals()
print "Inside func, globals:", globals()
print "Inside func, Printing the value of var1 in local namespace:", locals()["var1"]
print "Inside func, Printing the value of var1 in global namespace:", globals()["var1"]

if __name__ == "__main__":

var1 = 20
print "Inside main, locals:" ,locals()
print "Inside main, globals:" , globals()
print "\nInvoking function func...."

func()

print "\nInside main, Printing the value of var1 in global namespace:" ,var1
print "Inside main, Printing the value of var1 in local namespace:", locals()["var1"]
print "\nInside main, Invoking function func through globals:", globals()["func"]()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Output:

IDLE 1.2.2 ==== No Subprocess ====
>>>
Inside main, locals: {'var1': 20, '__builtins__': , '__file__': 'C:\\Python25\\Lib\\idlelib\\idle.pyw', 'idlelib': , 'sys': , 'func': , '__name__': '__main__', '__doc__': None}
Inside main, globals: {'var1': 20, '__builtins__': , '__file__': 'C:\\Python25\\Lib\\idlelib\\idle.pyw', 'idlelib': , 'sys': , 'func': , '__name__': '__main__', '__doc__': None}

Invoking function func....
Inside func, locals: {'var1': 10}
Inside func, globals: {'var1': 20, '__builtins__': , '__file__': 'C:\\Python25\\Lib\\idlelib\\idle.pyw', 'idlelib': , 'sys': , 'func': , '__name__': '__main__', '__doc__': None}
Inside func, Printing the value of var1 in local namespace: 10
Inside func, Printing the value of var1 in global namespace: 20

Inside main, Printing the value of var1 in global namespace: 20
Inside main, Printing the value of var1 in local namespace: 20

Inside main, Invoking function func through globals: Inside func, locals: {'var1': 10}
Inside func, globals: {'var1': 20, '__builtins__': , '__file__': 'C:\\Python25\\Lib\\idlelib\\idle.pyw', 'idlelib': , 'sys': , 'func': , '__name__': '__main__', '__doc__': None}
Inside func, Printing the value of var1 in local namespace: 10
Inside func, Printing the value of var1 in global namespace: 20
None
>>>

Explanation:


Inside main, lines 18 - 22

It has to be noted that inside main, locals() = globals(), therefore both would return the same elements and attributes as shown in the output, both locals() and globals() prints all imported modules (sys), built-in functions, the name and value of var1 inside main, the function name func and its function object.

Then the function func is invoked, note that we have var1 in both main and in the function func.

Lines 8 - 15

Inside func, we invoke the locals() and globals() function, the locals() function prints all objects and their attributes in a key value pair, since the function func has only one local variable var1 = 10, it is printed. The globals() call in func would return the same as what globals() would return when invoked in global namespace (main).

We have var1 = 10 inside function func and var1 = 20 inside main, therefore inside func, both variables can be accessed using locals()["var1"] (would print 10) and globals()["var2"] (would print 20).

Lines 25 - 28

Coming back to main again, in line 25, we print the value of var1 which is 20, then we print the value of var1 through locals()["var1"] which would also print 20 because inside main locals() = globals(), therefore we cannot access var1 in function func, on the otherhand if we try to print any other variable inside func through locals (say var2 = 20 if initialized in func), an exception will be thrown if there is no similar variable in main to override.

Finally we invoke the function func again, now through globals()["func"], which would invoke the function object.

7. Exception handling

Exception handling in python is similar to that of other Object Oriented Programming languages, here we use try and except statements to execute some statements and catch exceptions if any, however the try block also has an optional else part which we can see below.

Listing 7: exceptions.py


#
# Exception handling in python
# exceptions.py
# Author: S.Prasanna
#

import sys
import traceback

try:
open("Non-existentfile.txt", "r")
except IOError:
# Handle specific exception IOError
print sys.exc_info()[1]

try:
a = 10/0 #This would result in ZeroDivisionError
b = "Hello" + 10 #This would result in TypeError
except TypeError:
# Specific exceptions should be handled first
print "TypeError in assignment."
traceback.print_exc()
except:
# Handling generic exceptions
print "An exception occured in evaluating 10/0."
traceback.print_exc()

try:
count = 10
except:
# In case of an exception, this block will execute
print "An exception occured in try block."
traceback.print_exc()
else:
# In case of no exception, the else part will execute
print "Value of count = " , count
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

Output:

IDLE 1.2.2 ==== No Subprocess ====
>>>
[Errno 2] No such file or directory: 'Non-existentfile.txt'
An exception occured in evaluating 10/0.
Traceback (most recent call last):
File "C:\Prasanna\myblogs\prasannatech.net\entries\python_TOI\exceptions.py", line 17, in
a = 10/0 #This would result in ZeroDivisionError
ZeroDivisionError: integer division or modulo by zero
Value of count = 10
>>>

Explanation:

Lines 10 - 14

Here we have two blocks, the try and the except block, in the try block we try to open a non existent file (an invalid file name is used for the same), which would throw an exception (IOErrror), which is caught in the except block, note that the except block here catches a specific exception (IOError).

The sys.exc_info() returns a 3-Element tuple with more details related to the exception, the part we are interested is sys.exc_info()[1] which prints the error code [Errno 2] and the exception details (No such file or directory: 'Non-existentfile.txt').

Lines 16 - 26

Here we introduce two statements which will cause exceptions,

a = 10/0 #This would result in ZeroDivisionError
b = "Hello" + 10 #This would result in TypeError

The first statement would throw a ZeroDivisionError and the next statement tries to append a string with an integer which would result in a TypeError. In Line 19, we handle the TypeError and Line 23 handles generic exceptions (which would catcth any type of exception). Note always that specific exceptions should be caught first and then generic exceptions. In our case since the first exception is ZeroDivisionError, it will be caught by the second except statement which catches generic exceptions, then the traceback.print_exc() statement prints the complete details about the exception (with the exact line which caused the exception at the module level). Note that the output of traceback.print_exc() is same as what would be printed if you don't handle the exception (similar to other languages like java).

The traceback module has many useful diagnostic functions related to exceptions and it should be used for getting details about exceptions more frequently than sys.exc_info() .

Lines 28 - 36

Here we have a try - except block followed by an optional else statement, the except block will be executed when an exception is caught, otherwise the else part will be executed. The try block which initializes a variable doesn't throw any exception, as a result the else part gets executed.

We will see more about object oriented programming in python in the next section.

Continued here. A Quick Start to Introduction to Python Programming - 4.

No comments:


Copyright © 2016 Prasanna Seshadri, www.prasannatech.net, All Rights Reserved.
No part of the content or this site may be reproduced without prior written permission of the author.