Does hashlib support a file mode?

Phlip phlip2005 at gmail.com
Wed Jul 6 23:07:47 CEST 2011


On Jul 6, 1:25 pm, Carl Banks <pavlovevide... at gmail.com> wrote:

> We already know about this violation of the least surprise principle; most of us acknowledge it as small blip in an otherwise straightforward and clean language.

Here's the production code we're going with - thanks again all:


def file_to_hash(path, hash_type=hashlib.md5):
    """
    Per: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ea1c46f77ac1738c
    """

    hash = hash_type()

    with open(path, 'rb') as f:

        while True:
            s = f.read(8192)  #  CONSIDER:  io.DEFAULT_BUFFER_SIZE
            if not s:  break
            hash.update(s)

    return hash.hexdigest()

Note the fix also avoids comparing to None, which, as usual, is also
icky and less typesafe!

(And don't get me started about the extra lines needed to avoid THIS
atrocity!

        while s = f.read(8192):
            hash.update(s)

;)



More information about the Python-list mailing list