import re
import keyword


def to_identifier(string):
    """Makes a python identifier (perhaps an ugly one) out of any string.

    This isn't an isomorphic change, the original filename can't be recovered
    from the change in all cases, so it must be stored separately.

    Examples:
    >>> to_identifier('#if') -> '_if'
    >>> to_identifier('global') -> 'global_'
    >>> to_identifier('9foo') -> 'n9foo'

    :param string: string to convert
    :returns: `string`, converted to python identifier if needed
    :rtype: string
    """
    # Not really useful to expose as a CONSTANT, and python will compile and cache
    string = re.sub(r'[^0-9a-zA-Z_]', '_', string)

    if string[0].isdigit():
        string = "n" + string
    if keyword.iskeyword(string):
        string = string + '_'

    return string