import string


def substitute(template, safe=True, **kwargs):
    """Substitute parameters in a template string.

    Template substitution makes use of Python string templates (described in
    `PEP 292 <https://www.python.org/dev/peps/pep-0292/>`_).

    Args:
        template (str): The template string.
        safe (bool): If ``True``, missing parameters will be ignored and some
            template parameters may remain in the return value.
        **kwargs: Template parameters.

    Returns:
        The substituted template string.
    """

    template = string.Template(template)

    if safe:
        # Raise errors on invalid template even when ``safe == True``.
        try:
            template.substitute()
        except KeyError:
            pass

        return template.safe_substitute(kwargs)
    else:
        return template.substitute(kwargs)