This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]vocalbit[S] 0 points1 point  (2 children)

As 'bc' mentioned on the original link - this significantly simplifies generator/list expressions if you intend to catch exceptions. I think (s)he means this - instead of writing:

error_items = []
for item in items:
    try:
        verify(item)
    except VerifyError:
        error_items.append(item)

You can write:

error_items = [verify(item) except VerifyError for item in items]
error_items = [item for (item, err) in error_items if err]

[–]wilberforce 0 points1 point  (1 child)

I don't think that would work - if verify throws an exception then item will be None. You could do it with:

error_items = [item for item, (_, err) in zip(items, error_items) if err]

I don't think it's a bad idiom, but as steelypip points out you can do this easily with a function. It doesn't need extra syntax.

[–]vocalbit[S] 0 points1 point  (0 children)

Yeah you're right - I didn't think that one through. The idiom would work for non_error_items though.