views:

1859

answers:

2

In Python, functions like str(), int(), float(), etc. are generally used to perform type conversions. However, these require you to know at development time what type you want to convert to. A subproblem of some Python code I'm trying to write is as follows:

Given two variables, foo and bar, find the type of foo. (It is not known at development time, as this is generic code.) Then, attempt to convert bar to whatever type foo is. If this cannot be done, throw an exception.

For example, let's say you call the function that does this conv. Its signature would look like

def conv(foo, bar) :
    # Do stuff.

It would be called something like:

result = conv(3.14, "2.718")  # result is now 2.718, as a float.
+6  A: 

Use foo.__class__ to get the type of foo. Then call it to convert bar to the type of foo:

def conv(foo, bar) :
    return foo.__class__(bar)

Of course, this only works if the type of foo has a constructor that knows how to convert bar.

oefe
Impressive. I would have never thought it would be that incredibly easy. Also surprising (I'm new to Python and used to closer to the metal languages) is that it works with builtins.
dsimcha
Partially incorrect. foo.__class__ is only the type of foo if foo is a new-style object. Otherwise, it's only the class.
Devin Jeanpierre
Only incorrect inasmuch I said 'type' when class would be more precise. But he needs the class for this conversion. And in Python 3, the difference is gone anyway.
oefe
+10  A: 

that would be best:

type(foo)(bar)
nosklo
Only in Python 3.0. In Python 2.x, this will work only for "new-style classes" and builtins.
oefe