Tuesday, 7 August 2012

Introspection -- Python code


While working on a code it is necessary to be aware of the use and purpose of functions, keywords used in python. Acoording to Wikipedia the act of introspection is ability to know and understand properties of an object at runtime.

An example code
def info(object, spacing=10, collapse=1): 
    """Print methods and doc strings.
    
    Takes module, class, list, dictionary, or string."""
    methodList = [method for method in dir(object) if callable(getattr(object, method))]
    processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
    print "\n".join(["%s %s" %
                      (method.ljust(spacing),
                       processFunc(str(getattr(object, method).__doc__)))
                     for method in methodList])
if __name__ == "__main__":                
    print info.__doc__
Here while initial properties of the above mentioned code are , it has a function info. The indented blocks indicate action to be performed inside a function. In if __name__ asks the python program to perform a action to show its working. In this case it returns the doc string of the function. It returns multi line doc string for all the properties of a given input object. Here spacing and collapse have set values hence the function works even without inputting them as arguments passed.

Type, str, dir and other built in functions

'type' function returns the type of the object it receives as input. It can also be used for comparing and returns a boolean value.It can be shown with examples-

>>>type(100) # returns the type of 100
<type 'int'>
>>>type('asdf') # returns the type of asdf
<type'str'>
>>> import fib
>>>type(fib) # returns the type of fib
<type 'module'>
>>>import types
>>>type(fib) == types.ModuleType #compares if both are same.
True

'str' function forces any object into a string type. It is possible to perform str on modules, integers, lists and strings. Given below are few examples-

>>>str('9') # returns the number as string
'9'
>>>str(fib) # returns the module as string
<module fib from fib.py>
>>>li=['hello','good','morning',1]
>>>str(li) # retuns list as string
'['hello','good','morning','1']'
>>>str(None) # returns None as string.
'None'

'dir' returns the list of methods that are possible in the object passed. It is possible to use dir on lists. Dictionary, modules etc. Eg:-

>>> fun =[]
>>>dir(fun)
['append', 'count', 'extend', 'index', 'insert','pop', 'remove', 'reverse', 'sort']
>>> d = {}
>>>dir(d)
['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'setdefault', 'update', 'values']


'callable' functions return boolean values for objects that can be called as true else false. Eg:-

>>>import string
>>>a = 'anjali'
>>>callable(string.split)
True
>>>callable(a)
false

All the above mentioned functions are classified as builtin functions in python language and are found in a special module __builtin__. It also has error classes which is returned when ever an invalid action is performed. The most common error which is returned is AttributeError when we try to access a missing attribute.

>>>import __builtin__
getattr

It returns any attribute of the object passed. The object can be a list, module anything.

>>>getattr(lis,”append”)(“Moe”)
>>>getattr(li,”pop”)
<built-in method pop of list object at 0xb76d4b6c>
>>> getattr(odb,"buildConnectionString")
<function buildConnectionString at 0xb7785ae4>

import statsout

def output(data, format="text"):
output_function = getattr(statsout, "output_%s" % format, statsout.output_text)
return output_function(data)

As you can see, getattr is quite powerful. It is the heart of introspection. In the above example any data can be passed as object to output. The program can be extended to any formats like txt, pdf,odt etc.

List filteration

It is a part of list comprehension. Filteration is nothing but applying a method to the elements of the list and only return the values which satisfy the condition specified in the method. It allows us to avoid unwanted verbose in statements. Example given below.

>>> a = ["anj","menon","s","t","s","t"]
>>> [elem for elem in a if len(elem) > 1]
['anj', 'menon']
>>> [elem for elem in a if a.count(elem) > 1]
['s', 't', 's', 't']

The very example we used ie, methodlist is nothing but a list filteration implementation.


AND and OR

The “and” and “or” are boolean logic which can be used in implementation. They return one value.
In case of null or zero values are [],{},0,””. These are considered false.
AND returns the last true value of the expression and returns the first zero value in the expression.
OR returns the first true value of the expression and returns the last zero value in the expression. OR does not check if the second value is true or not if the first value is true. Further AND and OR can be expalined through these examples.

>>> 'yes' and 'no'
'no'
>>> '' and 'no'
''
>>> 'no' and ''
''
>>> 'yes' or 'no'
'yes'
>>> '' or 'no'
'no'
>>> 'yes' or ''
'yes'
>>> '1' and 'a' or 'b'
'a'
>>> '1' and 'a' or ''
'a'
>>> '1' and '' or 'a'
'a'
>>> '' and 'b' or 'a'
'a'


Lambda function

Lambda is a functionality borrowed from Lisp. They are miniature functions which can be used anywhere as functions. Lambda function can be used as normal functions. Lambda eliminates unnecessary verbose. It also takes any number of arguments.Lambda implementations are given below:-

>>>f = lambda x: return x*2
>>>f(2)
4
>>>f = lambda x:return x+1
>>>f(2)
3

In the first example of this blog we have a lambda function,
 processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)

which joins the gaps in a given sentence. The previous “and” and “or” returns the first condition which falls true.


Summarize

The python language allows users to implement not just builtin functions but also user defined functions. The above mentioned functions help make python powerful to work with and help implement many functions.

No comments:

Post a Comment