Question

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.
Was it helpful?

Solution

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.

OTHER TIPS

that would be best:

type(foo)(bar)
type(foo)

is definitely the best, if you want to check a type then "type" is the best method, and I am on python 2.7 - 3.2.2, type() works perfectly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top