Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Reflection and Type Conversion

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.
like image 990
dsimcha Avatar asked Mar 07 '09 17:03

dsimcha


2 Answers

that would be best:

type(foo)(bar)
like image 157
nosklo Avatar answered Sep 22 '22 04:09

nosklo


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.

like image 20
oefe Avatar answered Sep 21 '22 04:09

oefe