Useless expressions [was Re: Undefined behaviour in C]

Steven D'Aprano steve at pearwood.info
Sun Mar 27 21:26:16 EDT 2016


On Mon, 28 Mar 2016 03:39 am, Terry Reedy wrote:

> On 3/27/2016 11:48 AM, Ned Batchelder wrote:
>> On Sunday, March 27, 2016 at 10:43:49 AM UTC-4, BartC wrote:
> 
>>> whether fn has an explicit return or not, and not allowing:
>>>
>>>     fn         # and other kinds of expression
>>>
>>> unless some keyword is used.
>>
>> Python *could* have made it an error to have a useless expression as a
>> statement.
> 
> In interactive mode, which is an essential part of Python, expression
> statements print the value of the expression.  Thus no expression is
> useless.
> 
> So Bart is proposing 

I don't think Bart is intending this as an actual proposal to change Python
so much as just a hypothetical to discuss.


> to either disable an extremely useful feature or 
> split Python into two slightly different dialects.  I think both are bad
> ideas.

I don't think that's quite fair. The interactive interpreter is already
slightly different from non-interactive use, in that bare expressions print
the result, while in non-interactive use they just get garbage collected.
It wouldn't be that different to change "print versus ignore" into "print
versus raise error". I think it is a bit extreme to call that two different
dialects. If so, then the current interactive interpreter is also a
different dialect.

But that's not what makes this a bad idea.

Consider something like file.write. In Python 2, writing to a file behaves
like a procedure, and you write:

with open(filename) as file:
    file.write("something")


In Python 3, the write method has changed to return the number of characters
or bytes actually written. But if you don't need that information, you
aren't *forced* to collect it and ignore it. You can just ignore it:

with open(filename) as file:
    file.write("something")

is still perfectly legal. But Bart's suggestion would make that an error.

No, Bart's suggestion is perfectly reasonable for a linter, but not for
Python. Other languages may choose to be more restrictive. Pascal, for
example, requires you to declare subroutines as functions or procedures
depending on whether or not they return a value, and that's got much to
recommend it too. But Python made different choices.


-- 
Steven




More information about the Python-list mailing list