Skip to content

Instantly share code, notes, and snippets.

@spezold
Created February 22, 2026 12:57
Show Gist options
  • Select an option

  • Save spezold/382627a6048d615439582fd014e52b12 to your computer and use it in GitHub Desktop.

Select an option

Save spezold/382627a6048d615439582fd014e52b12 to your computer and use it in GitHub Desktop.
Simulating ternary (one-liner) try-except in Python
from functools import wraps
from typing import Callable as C
def attempt[**A, R, F](*, unless: type[BaseException], fallback: F, call: C[A, R]) -> C[A, R | F]:
"""
Attempt a function call; return its value if it succeeds, return the ``fallback`` if an exception of type
``unless`` is raised (so, basically, simulate a one-liner ``try-except`` statement).
Usage example::
>>> from operator import truediv as div
>>> result = attempt(unless=ZeroDivisionError, fallback=42, call=div)(1, 0) # 1/0 → division by zero!
>>> print(result)
42
:param unless: exception type to be handled
:param fallback: default value to be returned
:param call: function to be called
:return: corresponding wrapper that accepts the same arguments as the wrapped function
"""
@wraps(call) # Mainly doc and typing cosmetics
def wrapper(*args, **kwargs) -> R | F:
try:
result = call(*args, **kwargs)
except unless:
result = fallback
return result
return wrapper
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment