Caching Node Lookups

Monday, August 3rd, 2009

def loadGrammar(self, grammar): 
    self.grammar = self._load(grammar) 
    self.refs = {}                                 
    for ref in self.grammar.getElementsByTagName("ref"):     
        self.refs[ref.attributes["id"].value] = ref          

           
       

Looping through dictionaries

Monday, August 3rd, 2009

#the key and corresponding value can be retrieved at the same time using the 
#iteritems() method.

knights = {‘Key 1‘: ’value 1‘, ’key 2‘: ’value 2‘}
for k, v in knights.iteritems():
     print k, v

           
       

ZeroDivisionError Demo

Friday, July 31st, 2009

try: 1/0
except ZeroDivisionError: 
   print "caught divide-by-0 attempt"

           
       

Reflection: Find the data type

Sunday, July 26th, 2009

from types import *
 
def what (x):
     if type(x) == IntType:
             print "This is an int."
     else:
             print "This is something else."
 
what(4)
what("4")

           
       

List: less,equal,greater: tuple of results

Sunday, July 19th, 2009

L1 = [1, ('a', 3)]
L2 = [1, ('a', 2)]
print L1 < L2, L1 == L2, L1 > L2     # less,equal,greater: tuple of results