Short syntax for try/pass

Chris Angelico rosuav at
Tue Oct 14 16:22:03 CEST 2014

On Wed, Oct 15, 2014 at 1:08 AM, Leonardo Giordani
<giordani.leonardo at> wrote:
> a lot of times the following pattern pops out in Python code:
> try:
>  somecode
> except SomeException:
>  pass
> Converting the code to a non-EAFP version, for example
> if len(lst) != 0:
>  lst[0] = lst[0] + 1

This could be just "if lst:", but I agree, LBYL is not Python's style
(and isn't always possible anyway).

You can at least squish it up onto less lines, which might look better:

try: lst[0] += 1
except IndexError: pass

Alternatively, you can use this style:

from contextlib import suppress

with suppress(IndexError):
    lst[0] += 1


More information about the Python-list mailing list