libb.try_else

try_else(func, default=None)[source]

Wrap function to return default value if it fails.

Parameters:
  • func – Function to wrap.

  • default – Default value or callable to return on failure.

Returns:

Wrapped function.

Example:

>>> import json
>>> d = try_else(json.loads, 2)('{"a": 1, "b": "foo"}')
>>> d
{'a': 1, 'b': 'foo'}
>>> repl = lambda x: 'foobar'
>>> d = try_else(json.loads, repl)('{"a": 1, b: "foo"}')
>>> d
'foobar'