import string


def _ensure_identifier(name):
    """Convert ``name`` to a valid Python identifier

    Returns a valid Python identifier in the form ``[A-Za-z_][0-9A-Za-z_]*``.
    Any invalid characters are stripped away. Then all numeric leading
    characters are also stripped away.

    :raises NameError: if a valid identifier cannot be formed.
    """
    # Note: the identifiers generated by this function must be safe
    # for use with eval()
    identifier = "".join(char for char in name
                       if char in string.ascii_letters + string.digits + "_")
    try:
        while identifier[0] not in string.ascii_letters + "_":
            identifier = identifier[1:]
    except IndexError:
        raise NameError(
            "Cannot form valid Python identifier from {!r}".format(name))
    return identifier