Pages

Saturday, January 3, 2015

Python: current time in milliseconds









import time
ms = int(round(time.time() * 1000))
print(ms)




Friday, January 2, 2015

Python: ignore all exception and proceed








try:
   ... ...
except:
   pass



Thursday, January 1, 2015

Python: overriding static method








class A:
    @staticmethod
    def m():
        print "A"

class B(A):
    @staticmethod
    def m():
        print "B"

a = A()
a.m() # A
b = B()
b.m() # B



Python: call constructor of the super class








  • Option 1:
    class A(object):
     def __init__(self):
       print "world"
    
    class B(A):
     def __init__(self):
       print "hello"
       super(B, self).__init__()
    
  • Option 2:
    class A: 
     def __init__(self): 
       print "world" 
    
    class B(A): 
     def __init__(self): 
       print "hello" 
       A.__init__(self)
    



Python: string equals ignore case








def equals_ignore_case(s1, s2):
    if s1 is None and s2 is None:
        return True
    if s1 is None and s2 is not None:
        return False
    if s1 is not None and s2 is None:
        return False
    return s1.lower() == s2.lower()



Wednesday, December 31, 2014

Python: test if a dictionary contains a specific key









def contains(dict, key):
    return key in dict

dict={}
dict['a']=1
dict['b']=2
dict['c']=3

print(contains(dict, 'a')) # True
print(contains(dict, 'd')) # False



Sunday, December 28, 2014

Python: delete a item from a list








  • remove the first matching element:
    if e in list:
        list.remove(e)
  • remove all occurrences:
    while e in list:
        list.remove(e)
  • EAFP style: remove the first occurrence:
    try:
        list.remove(e)
    except ValueError:
        # not in the list
        pass
    
  • EAFP style: remove all occurrences:
    while True:
        try:
            list.remove(e)
        except ValueError:
            break
    

EAFP

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.