[Python-ideas] duck typing for io write methods

Terry Reedy tjreedy at udel.edu
Fri Jun 14 18:30:40 CEST 2013


On 6/14/2013 5:00 AM, Wolfgang Maier wrote:

> this is what str(int).encode() does, but is quite complicated, since it
> actually generates a full-blown Python string object first,  then encodes
> this to bytes again.

In 3.3+, it is not a complicated as you seem to think since the string 
of ascii digit chars uses one byte per char and the 'encoding' is just a 
copy. On my machine, with i = 123456, the two calls take about .3 and .2 
microseconds. The extra call is noise compared to time to read, split 
into 4 bytes, convert 2 bytes to ints, subtract, and after the 
conversion of the difference to bytes, join and write the line.

from timeit import repeat

def f():
   b = b'somelinedescriptor\t100\t500\tmorestuffhere\n'
   b = b.split(b'\t')
   i = int(b[2]) - int(b[1])
   b'\t'.join((b[0], str(i).encode(), b[3]))

print(repeat('f()', 'from __main__ import f'))

 >>>
[2.584412482335259, 2.614494724632941, 2.6133167166162155]
+ read/write time


-- 
Terry Jan Reedy



More information about the Python-ideas mailing list