[Python-ideas] except expression
Chris Angelico
rosuav at gmail.com
Wed Feb 19 14:30:16 CET 2014
On Wed, Feb 19, 2014 at 11:57 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
> I don't know how common a pattern it is in other people's code but
> something like:
>
> header = {
> 'param1': foo,
> 'param2': bar,
> ...
> }
>
> try:
> header['paramN'] = load_from_file(baz, spam)
> except OSError:
> header['paramN'] = ''
That looks awesome! Do you have actual production code that looks like
that, and if so, can I have a squiz at it? Because that's a strong
use-case right there.
What *isn't* a clear use-case is where you want the header to not
exist at all if the exception's thrown. For that, it's better to use
"try: assign; except OSError: pass", because there's no easy way to
tell a dict to not set something. It might be nice if it could be
done, but it can't. For that reason I've sometimes stipulated that a
list or dict is allowed to have some kind of shim in it, resulting in
code like this:
lst = [
fn1 and load_from_file(fn1),
fn2 and load_from_file(fn2),
load_from_constant("spam spam spam",
# ... etc ...
]
But if you specifically want those empty strings anyway, then yes,
except expressions would be perfect.
ChrisA
More information about the Python-ideas
mailing list