Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use type() information to cast values stored as strings

In my application I have generated a number of values (three columns, of type int, str and datetime, see example below) and these values are stored in a flat file as comma-separated strings. Furthermore, I store a file containing the type of the values (see below). Now, how can I use this information to cast my values from the flat file to the correct data type in Python? Is is possible or do I need to do some other stuff?

Data file:

#id,value,date
1,a,2011-09-13 15:00:00
2,b,2011-09-13 15:10:00
3,c,2011-09-13 15:20:00
4,d,2011-09-13 15:30:00

Type file:

id,<type 'int'>
value,<type 'str'>
date,<type 'datetime.datetime'>
like image 783
aweis Avatar asked Feb 23 '23 00:02

aweis


1 Answers

As I understand, you already parsed the file, you now just need to get the right type. So let's say id_, type_ and value are three strings that contain the values in the file. (Note, type_ should contain 'int' — for example —, not '<type 'int'>'.

def convert(value, type_):
    import importlib
    try:
        # Check if it's a builtin type
        module = importlib.import_module('__builtin__')
        cls = getattr(module, type_)
    except AttributeError:
        # if not, separate module and class
        module, type_ = type_.rsplit(".", 1)
        module = importlib.import_module(module)
        cls = getattr(module, type_)
    return cls(value)

Then you can use it like..:

value = convert("5", "int")

Unfortunately for datetime this doesnt work though, as it can not be simply initialized by its string representation.

like image 59
Paul Manta Avatar answered Feb 25 '23 14:02

Paul Manta