[Python-ideas] except expression

Rob Cliffe rob.cliffe at btinternet.com
Thu Feb 20 23:41:50 CET 2014


On 20/02/2014 17:41, Phil Connell wrote:
> There's a nice example that just came up in some code I was looking at.
> Paraphrasing:
>
>      if some_cond:
>          ...
>
>      elif not might_be_none.foo:
>          ...
>
>      else:
>          ...
>
> There's a bug in the elif expression, namely 'might_be_none' might be ..None :)
>
>
> The current spelling to fix this is:
>
>      elif not getattr(might_be_none, "foo", None):
>          ...
>
>
> I'm was a fan of the colon version, but it's *really* ugly in this case:
>
>      elif not might_be_none.foo except AttributeError: None:
>          ...
>
>
Minor point: I would tend to add parentheses, either
         elif not (might_be_none.foo except AttributeError: None): # 
preferably

or
     elif (not might_be_none.foo) except AttributeError: None:

AFAICS they both work in this example, but I find either more explicit 
and therefore easier to read.

(Mind you, if might_be_none was a single identifier, wouldn't it be 
clearer to write
     elif might_be_none is None or not might_be_none.foo:
And if it was a more complicated expression, there is the risk that 
AttributeError is raised evaluating it, a probable error that would be 
masked by the "except" form.
)


More information about the Python-ideas mailing list