[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Wed Feb 19 07:10:34 CET 2014


In the interests of a larger sample size, I've enhanced my "simple
try/except clause finder" script to locate the following:

1) Assignments to the same "thing" (which might be a simple name, an
attribute, an item, whatever)
2) Augmented assignments, as long as they use the same operator
3) Return values
4) Expressions

The last one gets a *lot* of false positives. As far as the AST is
concerned, both of these are try/except blocks with a simple
expression in each:

try:
    big.complex.function.call(int(x))
except ValueError:
    big.complex.function.call(x)

# and #

try:
    some_file.write(some_data)
except IOError:
    print("Unable to write data", file=sys.stderr)

The former might well want to be changed (though I've put those into
my "semantic changes" section, see below), but the latter definitely
can't. For the moment, I'm not trying to make the script recognize
those, so the human has to skim over all of them. But the other three
are fairly useful.

Once again, there are a good number of try/except blocks that match
these fairly restrictive rules - around 300. (THIS! IS! PYTHON!) And
once again, they overwhelmingly *do not* use the 'as' clause. For
reference, I had the script collect stats on except clauses overall.
The same files contain 4617 except clauses, of which 1007 use 'as'.
Based on that approximate one-in-five ratio, I would expect there to
be about 60 uses of 'as' in the simple try/excepts; but this is not
the case. In fact, there are only 34 out of 301, roughly half the
proportion required (note that this is skipping all files with
"/test/" in their names; including those gives 52/390 which is still
way lower than 1/5); and skipping all the two-expression blocks (most
of which are false positives) brings it down to just 7 out of 235.
Seven. That's how few simple try/except clauses use 'as'.

So, I'm really needing someone's big Python project to run this on, to
get an alternative data set. Someone want to help out with stats?

Annotated examples:
https://github.com/Rosuav/ExceptExpr/blob/master/examples.py
All files:
https://github.com/Rosuav/ExceptExpr/

ChrisA


More information about the Python-ideas mailing list