Skip to content Skip to sidebar Skip to footer

Smart Type Casting In Python

I am making api calls and receive a response back in json like so result = {'foo': '123.456', 'bar': '23', 'donald': 'trump', 'time': '2016-04-07T05:31:49.532124Z'} Although resul

Solution 1:

And what is the appropriate type? I am asking this to underline that sometimes also for humans it is not clear what the type is: are you sure that "42" is always an int or sometimes it has to be considered just as a string?

Anyway, as you did, you can build your solution with your rules that makes sense in your context.

In your case, you can simplify your code with a simple loop

from dateutil.parser import parse

tests = [int, float, parse]

defsmartcast(value):
     for test in tests:
         try:
             return test(value)
         except ValueError:
             continue# No matchreturn value

Solution 2:

what about using ast.literal_eval()?

https://docs.python.org/2/library/ast.html#ast.literal_eval

voting up Francesco's answer. You need an exception raised.

Post a Comment for "Smart Type Casting In Python"