Skip to main content

A Python micro-library that returns try value or default.

Project description

try-or

A Python micro-library that returns the first successful value (non-None) or a default.

What it does

  • Evaluate one or more supplier functions left-to-right.
  • Return the first value that:
    • does not raise a listed exception (exc), and
    • is not None.
  • If all suppliers either raise a listed exception or return None, return the default value.
  • Exceptions not listed in exc are propagated.

Examples

Fall back to default on Exception:

from try_or import try_or

# Return the successful value when no exception is raised
try_or(lambda: int("123"), default=0)
# -> 123

# Fall back to the default when an exception occurs
try_or(lambda: int("not-an-int"), default=0)
# -> 0

Replace None with default:

import os
from try_or import try_or

# Return the default when the result is None
try_or(lambda: os.environ.get("not-exist"), default="1")
# -> "1"

Narrow which exceptions are caught:

from try_or import try_or

# Only fall back on ValueError
try_or(lambda: int("x"), default=0, exc=(ValueError,))
# -> 0

# TypeError will be propagated
try_or(lambda: (1 + "a"), default=0, exc=(ValueError,))
# -> raises TypeError

# Fall back on ValueError or TypeError
try_or(lambda: (1 + "a"), default=0, exc=(ValueError, TypeError))
# -> 0

Multiple suppliers (short-circuiting, lazy evaluation):

import json
import os
from pathlib import Path
from try_or import try_or

config = try_or(
    # 1) Prefer env JSON
    lambda: json.loads(os.environ["APP_CONFIG_JSON"]),
    # 2) Then user config
    lambda: json.loads(Path("~/.myapp/config.json").expanduser().read_text(encoding="utf-8")),
    # 3) Then system config
    lambda: json.loads(Path("/etc/myapp/config.json").read_text(encoding="utf-8")),
    # Default if all above fail or return None
    default={"host": "localhost", "port": 8080},
)
# -> First successful non-None is returned. Later suppliers are not evaluated.

Empty suppliers:

from try_or import try_or

try_or(default="fallback")
# -> "fallback"

The code itself

def try_or(
    *args: Callable[[], T | None],
    default: T,
    exc: type[BaseException] | tuple[type[BaseException], ...]=(Exception,)
) -> T:
    for f in args:
        try:
            value = f()
            if value is not None:
                return value
        except exc:
            pass
    return default

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

try_or-1.0.0.tar.gz (6.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

try_or-1.0.0-py3-none-any.whl (3.4 kB view details)

Uploaded Python 3

File details

Details for the file try_or-1.0.0.tar.gz.

File metadata

  • Download URL: try_or-1.0.0.tar.gz
  • Upload date:
  • Size: 6.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.8

File hashes

Hashes for try_or-1.0.0.tar.gz
Algorithm Hash digest
SHA256 3f8882283fc649a9090d85990d15215782cb6c1937f3f5bc27d2b4b1a22ace65
MD5 be969b3bfa9fc46c42150dd397f466cd
BLAKE2b-256 3a31a9149e61087efe36af31e2c34ad5af4ca4fc7650101963592eb5dc74870b

See more details on using hashes here.

File details

Details for the file try_or-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: try_or-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 3.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.8

File hashes

Hashes for try_or-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b7aaca9e7476a7791b46e237f8d87bf7f4afa1fcac9696a0691d92ebc6f9230d
MD5 b396942def306d6d7560525daf8f3ce3
BLAKE2b-256 e95bdca19b47f48003ef045bb3e9e0c05060cd7ad9291c0a13749c81962e5f3c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page