4

I have:

x = float(1.0)
y = int(2)

t1 = type(x)
t2 = type(x).__name__

If I print t1 and t2 I can see the following:

print t1
>>> <type 'float'>

print t2
>>> float

How can I use t1 or t2 to change y into type float with the least amount of code?

Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46
fredrik
  • 9,631
  • 16
  • 72
  • 132
  • Do you _need_ to do this with the type _name_, or is it ok to just use the type itself? As the answer below indicate, the latter case is more straight-forward. – PM 2Ring Jan 22 '16 at 11:19
  • 1
    Yes, I need to do this with the type _name_. – fredrik Jan 22 '16 at 11:20
  • Actually, no I don't need the name. My mistake. I'm editing the question and accepting the best answer. – fredrik Jan 22 '16 at 11:55

4 Answers4

3

You can first convert from the a string representing a type name, such as "float", to the type, using the __builtins__ module (more about here here):

def get_type_by_name(type_name):
    return getattr(__builtins__, type_name)
the_type = get_type_by_name('float')

Then, do the convertion:

y = the_type(x)

You can also use eval for that, but in general eval is (harshly) discouraged.

Community
  • 1
  • 1
shx2
  • 61,779
  • 13
  • 130
  • 153
2

You could do the following:

x = float(1.0)
y = int(2)

y = type(x)(y)
print(type(y))

Output

float

If you need to do this with the type name, just assign the type of x to a variable and use it as a function:

x = float(1.0)
y = int(2)

t = type(x)
y = t(y)
print(type(y))

Output

float
gtlambert
  • 11,711
  • 2
  • 30
  • 48
  • 1
    Where in your answer are you using the type *name*? none of your variables are strings – shx2 Jan 22 '16 at 11:32
1

For types that cast passed arguments when called (like int, list, etc.), just use a reference to the type, and then call it.

>>> x = 1.
>>> y = 2
>>> t = type(x)
>>> t(y)
2.0
>>> tup = (1,2)
>>> lst = [3,4]
>>> t2 = type(tup)
>>> t2(lst)
(3, 4)
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
0

You already have good answers, but since programming is also about playing with stuffs, here is an alternative:

y.__class__(x)
Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46