Damian Brunold

Python Bits in tarfile.py

2010-02-18 21:27 Programmieren, Python

Ich lese manchmal Python Code und versuche daraus zu lernen. Momentan bin ich an tarfile.py aus Python 2.6. Folgendes habe ich mir notiert:

divmod liefert Quotient und Rest als Tupel. Gebraucht zum Beispiel im blockweisen Lesen-Idiom:

BUFSIZE = 16 * 1024
blocks, remainder = divmod(length, BUFSIZE)
for b in xrange(blocks):
    buf = src.read(BUFSIZE)
    if len(buf) < BUFSIZE:
        raise IOError("end of file reached")
    dst.write(buf)

if remainder != 0:
    buf = src.read(remainder)
    if len(buf) < remainder:
        raise IOError("end of file reached")
    dst.write(buf)

Aufbau eines Strings über eine Liste und join:

perm = []
for table in filemode_table:
        for bit, char in table:
            if mode & bit == bit:
                perm.append(char)
                break
            else:
                perm.append("-")
return "".join(perm)

Definieren einer Standardfunktion im aktuellen Module mit Spezialisierung:

if os.sep != "/":
    normpath = lambda path: os.path.normpath(path).replace(os.sep, "/")
else:
    normpath = os.path.normpath

@classmethod und @staticmethod war mir bisher unbekannt. Es handelt sich um function decorators. Konkret wird

@decorator
def decoree():
    pass

zu

def decoree():
    pass
decoree = decorator(decoree)

gewandelt. Damit kann man also Funktionen noch dekorieren. Vordefinierte Dekorationen sind @classmethod welches bewirkt, dass eine Methode statt self die class als ersten Parameter bekommt, und @staticmethod welches bewirkt, dass eine Methode weder self noch class als ersten Parameter bekommt.