Coercing one object to type of another

Vijay Shanker deontics at gmail.com
Sat Feb 9 06:23:38 EST 2013


On Saturday, February 9, 2013 4:13:28 PM UTC+5:30, Chris Angelico wrote:
> On Sat, Feb 9, 2013 at 9:29 PM, Vijay Shanker <deontics at gmail.com> wrote:
> 
> > Hi
> 
> > Inside a function i get a two arguments, say arg1 and arg2, how can i convert arg2 to same type as arg1 ?
> 
> > I dont know type of arg1 or arg2 for that matter, I just want to convert arg2 to type of arg1 if possible and handle the exception if raised.
> 
> > Also:
> 
> >>>> int('2')
> 
> > 2
> 
> >>>> float('2.0')
> 
> > 2.0
> 
> >>>> coerce(2,2.0)
> 
> > (2.0,2.0)
> 
> > but coerce('2',2) fails.If int('2') equals 2, why should it fail ?
> 
> 
> 
> You can get the type of any object, and call that:
> 
> 
> 
> def coerce(changeme,tothis):
> 
>     return type(tothis)(changeme)
> 
> 
> 
> ChrisA

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 ! 
thanks



More information about the Python-list mailing list