[Tutor] Calling a number's methods

Steven D'Aprano steve at pearwood.info
Wed Jun 23 13:28:33 CEST 2010


On Wed, 23 Jun 2010 04:47:47 pm Alan Gauld wrote:
> "Mark Young" <marky1991 at gmail.com> wrote
>
> > I searched the internet, and found someone suggest adding spaces
> > after each
> > number, which indeed works properly.
> >
> >>>> answer = 6 .__sub__(7 .__neg__())
> >>>> answer
> >
> > 13
> >
> > Why does this work? I don't even understand why python recognizes
> > that I'm
> > trying to access the numbers' __sub__ and __neg__ methods, I would
> > think
> > that the spaces would cause it to not work, but obviously it works
> > just
> > fine.
>
> I assume that's a hard coded hack in python to avoid some ambiguity
> with decimal points. But I'm not sure. 

No, it seems to be by design of the syntax: whitespace within an 
expression always separates tokens, and you can use as much of it, or 
as little, as you like:

>>> "abc" . upper ()  + "XYZ".lower()
'ABCxyz'
>>> [   2   ,   3   ,   4   ]  +[5,6,7]
[2, 3, 4, 5, 6, 7]

The only time when you *must* use whitespace between tokens is to avoid 
ambiguity, e.g. around the `is` operator, or when using dot method 
access on a literal int or float.

I'm sure this wasn't added to Python specifically to allow calling 
methods on numeric literals. You can use parentheses for that:

>>> (1).__str__()
'1'

This will be a side-effect of the fact that you can always add a space 
around tokens and have them still work fine.


-- 
Steven D'Aprano


More information about the Tutor mailing list