Inconsistency in Python?

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Aug 29 04:23:43 EDT 2002


dance_code at hotmail.com (lion) wrote in 
news:e895ad50.0208290000.51f842ec at posting.google.com:

>>>> 2.__abs__()
> SyntaxError: invalid syntax
>>>> a=2
>>>> a.__abs__()
> 2
> 
> It reports a syntax error! Though I know the code upside is useless,
> is it inconsistency in Python?

This really should be in the FAQ, but since I can't find it anywhere.

>>> 2.__abs__()
 SyntaxError: invalid syntax
>>> a=2.
>>> a __abs__()
SyntaxError: invalid syntax
>>> 

You see, it is perfectly consistent. '2.' is a floating point constant. Two 
names or values without an intervening operator is a syntax error.

You will notice that I had to insert a space between 'a' and '__abs__' 
otherwise I would have got a name error because the compiler couldn't tell 
I meant two separate symbols. You wouldn't be surprised at this, so why 
should you be surprised if you have to insert a space between '2' and '.' 
to make the compiler see them as separate symbols?

>>> 2 .__abs__()
2
>>> 

works fine for those rare occasions when you want the absolute value of a 
literal positive integer.

There is another trap here for the unwary:

>>> -2 .__abs__()
-2
>>> 

The dot operator binds more tightly than the unary minus, so you need 
parentheses if you want to use it on literal negative integers.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list