Chapter 9: Libraries

Example 9.1, page no. 250

In [1]:
'''
This requires python version 2.6 or greater.....
'''


import sys


class x:
    a=0
    b=0
    c=0
        

try:
    print sys.getsizeof(x.a) - sys.getsizeof(x.b)
except AttributeError:
    print "sys.getsizeof exists in Python 2.6 or greater..."
0

Example 9.2, page no. 252

In [2]:
'''
This program wont give any output.
'''


def func():
    c = 0
    assert(c!=0)
    c = raw_input("enter value.. :")

Example 9.3, page no. 264

In [3]:
#place=jmp_buf() # this is outside class that we don't have
def func():
    '''
    /*
    * Return to main.
    * Looks like a second return from setjmp,
    * returning 4!
    */
    '''
    #longjmp(place, 4) # This function belongs to outside class file. we don't have it.
    print "What! longjmp returned!\n"





retval = 0
'''
/*
* First call returns 0,
* a later longjmp will return non-zero.
*/
'''

#if(setjmp(place) != 0): #setjmp function is imported from outside. we don't have it in this file. so for compiling make comment on this two lines.
#   print "Returned using longjmp\n"
func()
print "What! func returned!\n"
What! longjmp returned!

What! func returned!

Example 9.4, page no. 267

In [ ]:
'''
Example 9.4
This shows misuse of loop. i.e. infinite loop.
This prints infinitely ready... in console.
'''


temp_file = None
def leave(sig):
    temp_file.write("\nInterrupted..\n")
    temp_file.close()
    

temp_file = open("tmp","w");
while(True):
    '''
    /*
    * Do things....
    */
    '''
    print "Ready...\n"
    a = raw_input("Enter character.. ")

    #/* can't get here ... */

Example 9.5, page no. 268

In [4]:
def f(*args):
    pass

f(1,2,3)

Example 9.6, page no. 270

In [5]:
def maxof(*args):
    max = 0
    a = 0
    for i in args:
        if i > max:
            max = i
    return max


def f():
    i = 5
    j = 24
    print "%d\n" %(maxof(3, i, j, 0))



f()
24

Example 9.7, page no. 287

In [ ]:
#Since we do not have 'testfile', this program will give an error

import sys
class xx:
    xx_int = 0
    xx_float = 0

ar = []


fp = open("testfile", "w")
if(fp.write("Hello")):
    print "Error writing\n"
    sys.exit(0)

for i in fp.readlines():
    print i

fp.close()

Example 9.8, page no. 290

In [7]:
f = open("anfile","w")
try:
    if(f):
        f.write("What - no error!\n")
except Exception:
    print "Bad File"