Bizarre arithmetic results

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Feb 24 02:15:40 CET 2010


On Tue, 23 Feb 2010 05:48:09 -0800, Mark Dickinson wrote:

> On Feb 23, 8:11 am, Steven D'Aprano
> <ste... at REMOVE.THIS.cybersource.com.au> wrote:
>> Making spaces significant in that fashion is mind-bogglingly awful.
>> Let's look at a language that does this:
>>
>> [steve at sylar ~]$ cat ws-example.rb
>> def a(x=4)
>>     x+2
>> end
>>
>> b = 1
>> print (a + b), (a+b), (a+ b), (a +b), "\n"
>>
>> [steve at sylar ~]$ ruby ws-example.rb
>> 7773
> 
> Hmm.  That's pretty nasty, all right.  Not that Python can claim to be
> immune to such behaviour:
> 
>>>> 3 .real
> 3
>>>> 3. real
>   File "<stdin>", line 1
>     3. real
>           ^
> SyntaxError: invalid syntax
> 
> 
> Though the fact that one of the cases raises an exception (rather than
> silently giving some different behaviour) ameliorates things a bit.

It ameliorates it *completely* -- you won't get silent errors in Python 
because you add or delete whitespace around a dot.


"I find it amusing when novice programmers believe their main job is 
preventing programs from crashing. ... More experienced programmers 
realize that correct code is great, code that crashes could use 
improvement, but incorrect code that doesn't crash is a horrible 
nightmare."

http://www.pphsg.org/cdsmith/types.html


The edge case occurs because dot does double-duty as an operator and as 
part of float literals. However, float literals never include whitespace:

>>> 1.5
1.5
>>> 1 . 5
  File "<stdin>", line 1
    1 . 5
        ^
SyntaxError: invalid syntax

and likewise for 1. 5 and 1 .5 -- the only way to get a float literal 
with a decimal point is by not including whitespace in it. So there is 
never any ambiguity about floats. You can even do this:

>>> 1.5.__str__()
'1.5'


And since . is an operator outside of float literals, you can do this:

>>> import sys
>>> sys . platform
'linux2'


although why you'd want to escapes me :)

This actually is a feature, since it is useful when calling methods on 
int literals. However this is a very rare thing to do.



-- 
Steven



More information about the Python-list mailing list