Why use contextlib.suppress as opposed to try/except with pass?

It is two lines less code without sacrificing readability.

It might be especially convenient for nested or consecutive code blocks. Compare:

try:
    a()
    try:
        b()
    except B:
        pass
except A:
    pass

vs.:

with suppress(A):
    a()
    with suppress(B):
        b()

It also allows to express the intent:

  • with suppress(SpecificError): do_something() says don’t propagate the error if it is raised while doing something
  • try: do_something() except SpecificError: pass says do something and don’t propagate the error if it is raised

It is less important because most people won’t notice the difference.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)