import six
import uuid


def six_uuid5(namespace, name):
    """A uuid.uuid5 variant that takes utf-8 'name' both in Python 2 and 3.

    :param namespace: A UUID object used as a namespace in the generation of a
                      v5 UUID.
    :param name: Any string (either bytecode or unicode) used as a name in the
                 generation of a v5 UUID.
    :returns: A v5 UUID object.
    """

    # NOTE(bence romsics):
    # uuid.uuid5() behaves seemingly consistently but still incompatibly
    # different in cPython 2 and 3. Both expects the 'name' parameter to have
    # the type of the default string literal in each language version.
    # That is:
    #     The cPython 2 variant expects a byte string.
    #     The cPython 3 variant expects a unicode string.
    # Which types are called respectively 'str' and 'str' for the sake of
    # confusion. But the sha1() hash inside uuid5() always needs a byte string,
    # so we have to treat the two versions asymmetrically. See also:
    #
    # cPython 2.7:
    # https://github.com/python/cpython/blob
    #        /ea9a0994cd0f4bd37799b045c34097eb21662b3d/Lib/uuid.py#L603
    # cPython 3.6:
    # https://github.com/python/cpython/blob
    #        /e9e2fd75ccbc6e9a5221cf3525e39e9d042d843f/Lib/uuid.py#L628
    if six.PY2:
        name = name.encode('utf-8')
    return uuid.uuid5(namespace=namespace, name=name)