[Tutor] Convert values in a list back and forth from ints and time

bob gailer bgailer at gmail.com
Tue Jan 6 04:38:03 CET 2009


Sander Sweers wrote:
> Hello Tutors,
>
> I use the csv module to read and write a csv file. When I read the
> file into a new list I convert the ints and the dates to int and time
> objects so I can do calculations. I use the below function which
> works.
>
> def convertValue(value, dateformat, reverse=False):
>     if reverse:
>         try:
>             return strftime(dateformat, value)
>         except TypeError:
>             return str(value)
>     else:
>         try:
>             return int(float(value))
>         except ValueError:
>             try:
>                 return strptime(value, dateformat)
>             except:
>                 return value
>
> When writing the lines back to a csv file I loop over the lists and
> convert the values back with the same function but in reverse but....
>
> I was just wondering if there is another way of dealing with this.
> Should I pass the strings to the calculation function (not written
> yet), do my calculations and have it return strings? 

I prefer separation of tasks. Let the calculation routines expect and 
return numbers.

I also suggest splitting convertValue into two functions, one that takes 
strings and one that takes numbers. A lot easier to read and maintain.

FWIW you could dispense with reverse in convertValue by testing the type 
of value for int or str.

-- 
Bob Gailer
Chapel Hill NC 
919-636-4239



More information about the Tutor mailing list