Search code examples
pythonlist

Convert a list of strings to conversion functions


Currently I can create a list of conversion functions like the following:

casts = [float, float, int, str, int, str, str]

but I would like to do it in the following manner:

casts = input("Enter the casts: ") # this would be str str int int float

I tried just doing cast.split() but that only outputs a list of strings and not the conversion functions. How would I go about achieving my objective?


Solution

  • A function is not a name. The blessed way is to use a dictionary to map names to functions:

    casts={'int': int, 'float': float, 'str': str}
    cast = casts[input('Enter the cast name')]
    

    An anti-pattern allows to search for names in a module:

    import builtins
    cast = getattr(builtins, input('Enter the cast name)]
    

    But beware, although it is allowed by the language, this breaks the separation between the user code and the internals of the language. You should avoid it if you can...


    From your comments, what you are looking for is something close to:

    cast_ref = {'int': int, 'float': float, 'str': str}
    casts = [cast_ref[src] for src in input('Enter the casts: ').split()]