0
a = 4
b = float(a)
c = 'float'

Now, the doubt comes when the target type is stored in another variable.

b = c(a)

This would raise error.

aviral sanjay
  • 953
  • 2
  • 14
  • 31
  • Python has no type casting. You simply have a `float()` callable that you apply to another variable. You want dynamic variable lookups here. – Martijn Pieters Dec 03 '18 at 13:12
  • You currently store the string `'float'` in c. You _can_ store `float` in it, but you need to get rid of the quotes: `c = float`. Then `b = c(a)` should work. – L3viathan Dec 03 '18 at 13:13
  • So how to do dynamic variable lookups? – aviral sanjay Dec 03 '18 at 13:14
  • @L3viathan I have the datatype stored as a string in another variable and that is the limitation. How can I still typecast it? – aviral sanjay Dec 03 '18 at 13:16
  • 1
    See the duplicate. Built-in names such as `float` live in `builtins`, so `import builtins` then `getattr(builtins, c)` gives you the `float` object to call. – Martijn Pieters Dec 03 '18 at 13:16
  • You can also pre-define your own dictionary: `types = {'float': float, 'str': str, ...}` then `types[c]` to get the callable. – Martijn Pieters Dec 03 '18 at 13:16

0 Answers0