[Python-ideas] Proposal for new augmented assignment operator for method calls

Jamie Willis jw14896.2014 at my.bristol.ac.uk
Fri Mar 27 22:36:34 CET 2015


(As posted on python-list)

I would like to propose a new piece of syntax for the python language; .=

In short, the operator is form of syntactic sugar, for instance consider
the following code:

hello = "hello world              "
> hello = hello.strip()


This could be written as:

hello = "hello world              "
> hello .= strip()


In this slightly contrived example, the programmer saved (a small amount
of) time when writing the code. With code with longer variable names, or
lots of similar statements all in a row, this helps to keep code more
concise, and could cut down on potential bugs due to typos (thanks to Skip
Montanaro for pointing this out).

The operator would be constricted to one method or field on the right-hand
side, which must belong to the object on the left hand side.

To provide another example, consider this basic LinkedList class:

class LinkedList:
>
>     def __init__(self, data, head=None):
>         self.data = data
>         self.next = None
>         self.head = head if head != None else self
>


    def append(self, data):

        new_node = LinkedList(data, self.head)
>         self.next = new_node
>         return new_node
>


linked_list = LinkedList(7)
> linked_list = linked_list.append(8)
> linked_list = linked_list.append(9)
>


loop_node = linked_list.head

while loop_node != None:
>     print(loop_node.data)
>     loop_node = loop_node.next


Taking a look at "*linked_list = linked_list.append(8)*", we could write
this as:

linked_list .= append(8)


under the new syntax and then "*loop_node = loop_node.next*" could simply
become:

loop_node .= next


Would this idea get much support if submitted as a PEP? What are the
potential concerns I could consider with the syntax (Skip has already
pointed out that the "dot" is pretty invisible in the operator, so perhaps
a different character could be used)?

Thanks,

Jamie
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150327/5606b319/attachment.html>


More information about the Python-ideas mailing list