[Python-ideas] except expression
Chris Angelico
rosuav at gmail.com
Thu Feb 20 16:53:05 CET 2014
On Fri, Feb 21, 2014 at 12:45 AM, M.-A. Lemburg <mal at egenix.com> wrote:
> I also find it disturbing that people are actually considering
> to use this expression form as a way to do quick&dirty suppression
> of exceptions.
>
> The intended use case should really be limited to providing default
> values for functions or methods that are expected to return a value.
>
> Abusing the fact that procedures in Python return None (simply
> because we don't have procedures and need to use functions instead)
> to make use of except expressions would make code less readable.
I absolutely agree here. Nothing in the proposal is _ever_ advocating
that. None of the examples is even showing that. The fact that you
happen to be able to is just an effect of simple and straight-forward
rules.
> x = data[1] except IndexError return None # is readable
That's the intent.
> f = open('x.txt', 'r') except IOError return None # is probably not a good idea
Well, that'd be okay if the rest of your code is like this:
if f: data = f.read(...)
For instance, you might have a rule that a config file will be read if
it exists, but otherwise you query the console. So you might do:
foo = f.readline() if f else input("Enter the foobinator: ")
> os.remove('/') except IOError return None # is really bad style
Yes. This one I don't like, and style guides should condemn it. Or
just leave it up to common sense: Don't be stupid. :)
ChrisA
More information about the Python-ideas
mailing list