Useless expressions [was Re: Undefined behaviour in C]

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


On Sun, 27 Mar 2016 10:31 pm, BartC wrote:

> On 27/03/2016 07:34, Paul Rubin wrote:
>> BartC <bc at freeuk.com> writes:
>>>   But my suggestion was to have required a keyword in front of
>>> such expressions.
>>
>> Should there be a keyword in front of a line containing "sqrt(x)" ?
>> What about "launch(missiles)" ?
> 
> They both look like function calls. Function calls are *very* commonly
> used as standalone expressions.
> 
> You /could/ stipulate that they be written:
> 
>    call launch(missiles)    # like Fortran iirc
> 
> but that wouldn't be popular and is unnecessary.
> 
>> The compiler can't tell which of those expressions has a side effect.
>> The first might be buggy code but the second is idiomatic.
> 
> Whether there are side-effects is not quite as important as picking up
> things that are likely to be errors:
> 
>    f()         # Probably OK
>    g()         # Probably OK
>    f()+g()     # Probably not OK

You don't and can't know what's "probably not" okay unless you know what
type of object both f and g return.

Don't think about floats and ints and strings. Think of complex objects with
operator overloading. You're probably thinking of `x + y`. Instead, think
of things like:

graph + node
database + table

in a procedural style instead of a functional style. With operator
overloading, we have the ability to write domain-specific little languages.

It's not the compiler's job to cast value judgements on what is good or
likely style, it must accept anything legal. If you want something to make
value judgements about style, or get warnings about what looks like legal
code but might be an error, then you should use a linter like PyChecker,
Pylint, Jedi or similar. That's not the compiler's job.


> Maybe there is some legitimate, obscure reason for writing the latter,
> but stick some indicator in front to tell the language (and whoever
> happens to be reading the code) that this is what you intend.

In your language, you can make operator overloading illegal if you like, or
discourage it by requiring special syntax, but in Python it is a
first-class (pun not intended) programming style of equal standing to
arithmetic, strings, method calls and modules.



-- 
Steven




More information about the Python-list mailing list