Pages

Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

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.




Saturday, December 27, 2014

Python: del or assign None?








>>> x=1
>>> print x
1
>>> del x
>>> print x
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'x' is not defined
>>> x=1
>>> print x
1
>>> x=None
>>> print x
None

see also




Tuesday, December 23, 2014

synchronized method in python








Java code

class AClass {
    private int count =0;

    public synchronized inc(){
        count++;
    }

    public synchronized dec(){
        count--;
    }
}

Python code

import threading

class AClass(object):
    def __init__(self):
        self.__count = 0;
        self.__lock = threading.RLock()

    def inc(self):
        with self.__lock:
            self.__count += 1

    def dec(self):
        with self.__lock:
            self.__count -= 1


see also




synchronized static method in python








Java code

class AClass {
    private static int _count = 0;

    public static synchronized inc(){
        _count ++;
    }
    
    public static synchronized dec(){
        _count --;
    }
}

Python code

import threading

class AClass(object):
    __count = 0
    __lock = threading.RLock()

    @classmethod
    def inc(cls):
        with cls.__lock:
            cls.__count += 1

    @classmethod
    def dec(cls):
        with cls.__lock:
            cls.__count -= 1



Tuesday, October 21, 2014

Python: check if file or directory exists








  • os.path.exists to check if file or directory exists.
    import os
    os.path.exists('/tmp/1.txt')
    os.path.exists('/tmp')
    
  • os.path.isfile to check if file exists.
    import os
    os.path.isfile('/tmp/1.txt')
    



Python: Get file absolute path








Use os.path.abspath function:
import os
os.path.abspath('abc/abc.txt')



Python: get the index of a char in a string








find and index method are available. The difference is that find returns -1 when what you're looking for isn't found, index throws an exception.
s='abc'
print(s.index('b')) # 1
print(s.find('b'))  # 1
print(s.find('d'))  # -1
print(s.index('d')) # exception



Python: string types in 2.x and 3.x








  • In Python 2.x, basestring is the base class for both str and unicode, while types.StringType is str. If you want to check if something is a string, use basestring. If you want to check if something is a ascii (bytestring), use str and forget about types.
  • Since Python 3.x, types not longer has StringType; str is always unicode. basestring no longer exists.



python: return inside with block








if returns value inside with statement, will the file be closed eventually?
The answer is YES
with open('myfile.txt') as f:
    return [line for line in f if len(line)>80]



Tuesday, October 14, 2014

python: iterables and iterators








A class with __iter__() method or __getitem__() method is iterable. The __iter__() method returns an iterator. A iterator object has a next() method (or __next__() method in python 3.0).
class Iterator(object):
    def next(self):
        pass

class Iterable(object):
    def __iter__(self):
        return Iterator()

see also




python: len() function and __len__() method








len is a function to get the length of a collection. It works by calling an object's __len__ method.
class AClass(object):
    def __init__(self):
        self._list = [1,2,3]

    def __len__(self):
        return len(self._list)

a=AClass()
print(a.__len__()) # 3
print(len(a))      # 3



Monday, September 1, 2014

Python: int to hex string








print(hex(255))
Result:
'0xff'
hex(255)[2:]
Result:
'ff'



Python: generates crc32 and adler32 checksum for big files








import zlib
import sys
import urllib2

def __zlib_csum(url, func):
    if isinstance(url, basestring if sys.version_info[0] < 3 else str):
        url = urllib2.Request(url)
    f = urllib2.urlopen(url)
    csum = None
    try:
        chunk = f.read(1024)
        if len(chunk)>0:
            csum = func(chunk)
            while True:
                chunk = f.read(1024)
                if len(chunk)>0:
                    csum = func(chunk, csum)
                else:
                    break
    finally:
        f.close()
    if csum is not None:
        csum = csum & 0xffffffff
    return csum
    

def crc32(url):
    return __zlib_csum(url, zlib.crc32)

def adler32(url):
    return __zlib_csum(url, zlib.adler32)

if __name__ == '__main__':
    print(hex(crc32('file:/tmp/111.zip')))
    print(hex(adler32('file:/tmp/111.zip')))



Thursday, July 17, 2014

Enum in python








  • Before Python 3.4 (PEP 435),
    class Animal:
        DOG = 1
        CAT = 2
    
    x = Animal.DOG
    
    or
    class Animal:
        DOG, CAT = range(2)
    
    x = Animal.DOG
    
  • Since Python 3.4 (PEP 435),
    class Animal(Enum):
        DOG = 1
        CAT = 2
    
    x = Animal.DOG
    
    or equivalently:
    from enum import Enum
    
    Animal = Enum('Animal', 'DOG CAT')
    
    x = Animal.DOG