Floating point bug?
Duncan Booth
duncan.booth at invalid.invalid
Thu Feb 14 13:58:56 EST 2008
Jeff Schwab <jeff at schwabcenter.com> wrote:
> Christian Heimes wrote:
>> Dennis Lee Bieber wrote:
>>> What's wrong with just
>>>
>>> str(0.3)
>>>
>>> that's what "print" invokes, whereas the interpreter prompt is using
>>>
>>> repr(0.3)
>>>
>>
>> No, print invokes the tp_print slot of the float type. Some core types
>> have a special handler for print. The tp_print slot is not available
>> from Python code and most people don't know about it. :]
>
> Why does print use the tp_print slot, rather than str()? Are the two
> effectively redundant? If (non-repr) string representations are
> frequently needed for a given type, could str() be implemented as a
> reference to tp_slot, via a C-language extension?
The tp_print slot is used only when printing to a C file descriptor. In
most cases where it is used it simply duplicates the str and repr
functionality but avoids building the entire output in memory. It also
takes a flag argument indicating whether it should output the str or repr,
the latter being used when rendering the content inside an object such as a
dict or list.
So for example a dict's repr builds a list containing the repr of each
key/value pair and then joins the list using a comma separator. The
tp_print simply outputs the '{', then uses tp_print to output the repr of
the key and repr of the value with appropriate separators and finally the
closing '}'. It would not suprise me if by replacing the output of a single
large string with a lot of small calls to fputs 'print x' could be slower
than 'print str(x)'.
More information about the Python-list
mailing list