Pages

Tuesday, October 21, 2014

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



python: call another static method








class AClass(object):
    def __init__(self):
        pass

    @staticmethod
    def a():
        AClass.b()

    @staticmethod
    def b():
        pass

see also




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')))