Undefined behaviour in C [was Re: The Cost of Dynamism]
BartC
bc at freeuk.com
Sat Mar 26 11:24:48 EDT 2016
On 26/03/2016 14:30, Chris Angelico wrote:
> On Sun, Mar 27, 2016 at 1:09 AM, BartC <bc at freeuk.com> wrote:
>> I'm surprised that both C and Python allow statements that apparently do
>> nothing. In both, an example is:
>>
>> x
>>
>> on a line by itself. This expression is evaluated, but then any result
>> discarded. If there was a genuine use for this (for example, reporting any
>> error with the evaluation), then it would be simple enough to require a
>> keyword in front.
>
> Tell me, which of these is a statement that "does nothing"?
>
> foo
> foo.bar
> foo["bar"]
> foo.__call__
> foo()
> int(foo)
>
> All of them are expressions to be evaluated and the result discarded.
> I'm sure you'll recognize "foo()" as useful code, but to the
> interpreter, they're all the same.
Out of that lot, only foo() is something that is commonly written both
as an expression and standalone statement.
> And any one of them could raise an
> exception rather than emit a value; for instance, consider these code
> blocks:
>
> # Personally, I prefer doing it the other way, but
> # if you have a big Py2 codebase, this will help
> # port it to Py3.
> try: raw_input
> except NameError: raw_input = input
>
> try: int(sys.argv[1])
> except IndexError:
> print("No argument given")
> except ValueError:
> print("Not an integer")
>
> In each case, the "dummy evaluation" of an expression is used as a way
> of asking "Will this throw?". That's why this has to be squarely in
> the hands of linters, not the main interpreter; there's nothing that
> can't in some way be useful.
But notice that to render such an evaluation 'useful', you've put 'try:'
in front, which is also a cue to the reader.
Now you can't just do that anyway (try expects an except block to
follow). But my suggestion was to have required a keyword in front of
such expressions. Then no linter is needed. And stops some
head-scratching from people who have to read the code.
--
Bartc
More information about the Python-list
mailing list