简体   繁体   中英

python casting variables with type as argument

Is there a casting function which takes both the variable and type to cast to? Such as:

cast_var = cast_fn(original_var, type_to_cast_to)

I want to use it as an efficient way to cycle through a list of input parameters parsed from a string, some will need to be cast as int, bool, float etc...

All Python types are callable

new_val = int(old_val)

so no special function is needed. Indeed, what you are asking for is effectively just an apply function

new_val = apply(int, old_val)

which exists in Python 2, but was removed from Python 3 as it was never necessary; any expression that could be passed as the first argument to apply can always be used with the call "operator":

apply(expr, *args) == expr(*args)

Short answer: This works:

>>> t = int
>>> s = "9"
>>> t(s)

Or a full example:

def convert(type_id, value):
    return type_id(value)

convert(int, "3")  # --> 3
convert(str, 3.0)  # --> '3.0'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM