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.
that would be best:
type(foo)(bar)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With