18 Jul 2014

Intresting bits from source code

It has been really exciting to dig into the source code of a language  or framework. I have been going through te souce code of python2.7 and Django1.6 from quite a while. Digging the source code certainly enrich his understanding of the system and learn new things right under the hood.

In this post i'm going to share some of those things.

Python2.7: module 'keyord'
Finding an element in a list.
daylist = ["sun", "mon", "tue", "wed", "thrus", "fri", "sat"] 
isday = frozenset(daylist).__contains__

isday("fri")  >> True
isday("abc") >> False
isday is a function object which can be for a string to check if it is present in list or not.


Using logical operators to do if.. else..
>>truth_value = 6 > 33
>>truth_value and "yeah, its true"  or "its a big fat lie"
"its a big fat lie"
This is how its working:
exp1 and exp2
'and' returns a exp1 if exp1 is evaluated to False otherwise evaluates exp2 and return it.
>>truth_value and "yeah, its true"  
False
now the expression becomes like
>>False or "its a big fat lie"
>>"its a big fat lie"
 'or' returns a exp1 if exp1 is evaluated to True otherwise evaluates exp2 and return it.



In Django shell auto completion for python keywords, modules and other imported objects works using rlcompleter module.
>>import rlcompleter
>>import readline
>>readline.parse_and_bind("tab: complete")
>>readline. <TAB PRESSED>
readline.__doc__          
readline.get_line_buffer(  
readline.read_init_file(
readline.__file__         
readline.insert_text(      readline.set_completer(
readline.__name__         
readline.parse_and_bind(

code module provides facilities to interact with the interpreter.
Running python interpreter using python code:
>>import code
>>code.interact()

Similarly if you have ipython or bpython installed
>>import ipython
>ipython.embed()

If you want the interpreter to have some objects at start , try this
>>code.interact(local={'hack': 'hack is fun'})
>>hack
'hack is fun'


So that's it for this post, will post more interesting stuff.