import typing
import hashlib
import json


def do_hash(dat: typing.Any) -> str:
    """Calculate a hash function of a data structure.

    This routine works by converting a data structure to a json string,
    then applying the SHA1 algorithm.
    Finally, the hexdigest is returned.

    Attention:
       Because conversion to json is involved, only serialisable data structures
       can be input.
    Note:
       In this routine, crucially,  keys are sorted in dicts when converting
       to json.  This ensures that identical dicts created
       differently (adding elements in a different order)
       produce the same hash.

    Args:
       dat: A serialisable python data structure to calculate the hash of.
    Returns:
       A string representing a hash function.
    """
    return hashlib.sha1(json.dumps(dat, sort_keys=True).encode('utf-8')).hexdigest()