Coercing one object to type of another

Chris Angelico rosuav at gmail.com
Sat Feb 9 06:31:01 EST 2013


On Sat, Feb 9, 2013 at 10:23 PM, Vijay Shanker <deontics at gmail.com> wrote:
> well it will always return me this:
> <type 'str'>
>
> what i want is if i know arg1 is of string type(and it can be of any type, say list, int,float) and arg2 is of any type, how can i convert it to type of arg1,
> if arg1='hello world', type(arg1).__name__ will give me 'str', can i use this to convert my arg2 to this type, w/o resorting to if-elif conditions as there will be too many if-elif-else and it doesn really sounds a great idea !

Oh, okay. Then switch the order of the arguments in what I posted:

def coerce(target,convertme):
    return type(target)(convertme)

You don't need to worry about the actual name of the type. It's
telling you that it's <type 'str'>; that's an actual callable object
(the same as the builtin name str, in this case). You can then call
that to coerce the other argument to that type.

ChrisA



More information about the Python-list mailing list