import hashlib


def checksum(fpath, hasher=None, asbytes=False):
    """Returns the checksum of the file at the given path as a hex string
    (default) or as a bytes literal. Uses MD5 by default.

    **Attribution**:
    Based on code from
    `Stack Overflow <https://stackoverflow.com/a/3431835/789078>`_."""
    def blockiter(fpath, blocksize=0x1000):
        with open(fpath, "rb") as afile:
            block = afile.read(blocksize)
            while len(block) > 0:
                yield block
                block = afile.read(blocksize)
    try:
        hasher = hasher or hashlib.md5()
        for block in blockiter(fpath):
            hasher.update(block)
        return (hasher.digest() if asbytes else hasher.hexdigest())
    except:
        return None