[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Thu Feb 20 02:56:50 CET 2014


On Thu, Feb 20, 2014 at 12:05 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 02/19/2014 05:00 PM, Chris Angelico wrote:
>>
>> On Thu, Feb 20, 2014 at 11:15 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
>>> os.unlink(some_file) except OSError -> None
>>
>> Yes, it does make for a one-liner, where the full form takes two:
>>
>> try: os.unlink(some_file)
>> except OSError: pass
>>
>> but I'm not sure that it's the right way to do things.
>
>
> 1) It could be used inside a function call or assigned to a variable;

If you're using the return value, then sure. That's exactly what this
is for. But as far as I know, os.unlink only ever returns None, so
saying "and if it raises OSError, return None instead" doesn't make a
lot of sense.

> 2) We're creating a new expression type -- it'll be valid anywhere an
> expression is valid, even all by itself.  e.g. `1 + 2` is valid, even though
> nothing is done with the result.

Oh yes, I'm not going to *prevent* this sort of thing. It's no
different from reworking your import statements into __import__ calls
just so you can use ternary if to handle versions:

tkinter = __import__("Tkinter" if sys.version_info.major==2 else "tkinter")

Is it good code? I don't think so. Does anything stop you from doing
it? Of course not. And if you really wanted to, you could probably
turn your entire Python program into a single megantic (that's like
gigantic only not so much - next one down is kilantic, and below that
you just have antics - see also
http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=370794)
lambda, make everything into expressions, and do all assignments by
declaring functions and calling them. But it wouldn't be Pythonic
code.

ChrisA


More information about the Python-ideas mailing list