Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does python allow spaces between an object and the method name after the "."

Does anyone know why python allows you to put an unlimited amount of spaces between an object and the name of the method being called the "." ?

Here are some examples:

 >>> x = []
 >>> x.            insert(0, 'hi')
 >>> print x
 ['hi']

Another example:

>>> d = {}
>>> d            ['hi'] = 'there'
>>> print d
{'hi': 'there'}

It is the same for classes as well.

>>> myClass = type('hi', (), {'there': 'hello'})
>>> myClass.            there
'hello'

I am using python 2.7 I tried doing some google searches and looking at the python source code, but I cannot find any reason why this is allowed.

like image 761
kslote1 Avatar asked Aug 13 '15 18:08

kslote1


2 Answers

The . acts like an operator. You can do obj . attr the same way you can do this + that or this * that or the like. The language reference says:

Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens.

Because this rule is so general, I would assume the code that does it is very early in the parsing process. It's nothing specific to .. It just ignores all whitespace everywhere except at the beginning of the line or inside a string.

like image 72
BrenBarn Avatar answered Oct 15 '22 13:10

BrenBarn


An explanation of how/why it works this way had been given elsewhere, but no mention is made regarding any benefits for doing so.

An interesting benefit of this might occur when methods return an instance of the class. For example, many of the methods on a string return an instance of a string. Therefore, you can string multiple method calls together. Like this:

escaped_html = text.replace('&', '&amp;').replace('<', '&lt;').replace('>'. '&gt;')

However, sometimes, the arguments passed in might be rather long and it would be nice to wrap the calls on multiple lines. Perhaps like this:

fooinstance \
    .bar('a really long argument is passed in here') \
    .baz('and another long argument is passed in here')

Of course, the newline escapes \ are needed for that to work, which is not ideal. Nevertheless, that is a potentially useful reason for the feature. In fact, in some other languages (where all/most whitespace is insignificant), is is quite common to see code formatted that way.

For comparison, in Python we would generally see this instead:

fooinstance = fooinstance.bar('a really long argument is passed in here')
fooinstance = fooinstance.baz('and another long argument is passed in here')

Each has their place.

like image 39
Waylan Avatar answered Oct 15 '22 14:10

Waylan