[Python-ideas] Proposal for new augmented assignment operator for method calls
Andrew Barnert
abarnert at yahoo.com
Sat Mar 28 02:31:12 CET 2015
On Mar 27, 2015, at 14:36, Jamie Willis <jw14896.2014 at my.bristol.ac.uk> wrote:
>
> (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
This is a pretty weird variation on the linked list data structure that's hard to imagine anyone actually using. And it seems like it's only because you've made it so weird that you need an append function that (unpythonically) mutates self and returns some other but related object. And it's only because you've made that append function that you need this new syntax at all.
It's certainly possible that a more reasonable class would also give you a use case for this feature, but it's hard to guess without seeing one.
Also, a much more Pythonic way to write your loop would be to write a list iterating function (whether an __iter__ method, or an external function) and just loop over that, which means the ugly "node = node.next" would either never appear, or appear only once inside that iterator rather than all over user code.
Your improved version is only marginally better:
loop_node = linked_list.head
while loop_node != None:
print(loop_node.data)
loop_node .= next
While doing it right gives you:
for loop_node in linked_list:
print(loop_node.data)
(Also, as a side note, you shouldn't compare to None with !=; use is not.)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150327/fae20605/attachment.html>
More information about the Python-ideas
mailing list