Coercing one object to type of another

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Feb 9 22:11:44 CET 2013


Vijay Shanker 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. 

How do you propose to handle the exception?

If arg1 is a dict, and arg2 is an int, what do you think should happen?

convert({}, 45)
=> returns what?


If arg1 is a HTTP connection object, and arg2 is a function object, what do
you think should happen?

import urllib2
conn = urllib2.urlopen("http://www.python.com/")
convert(conn, lambda x: len(x) + 1)
=> returns what?


You cannot convert arbitrary objects of one type into some other arbitrary
type, it simply doesn't make sense. So first of all you need to decide:

- what kinds of objects do you care about?

- when given some other kind of object, how do you propose to deal with it?

The usual answer to the second question is "raise an exception".



> 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 ?

Because '2' is a string, not a number, and coerce only operates on numbers.
What would you expect coerce("three", 2) to return? How about
coerce("apple", 2)?


Why do you think you need coerce? What are you actually trying to
accomplish? If you have two numbers, normally you would just do arithmetic
on them and let Python do any coercion needed. And if you have a number and
something else, you can't magically turn non-numbers into numbers.



-- 
Steven




More information about the Python-list mailing list