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.1.tar.gz (7.1 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.1-py3-none-any.whl (3.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: try_or-1.0.1.tar.gz
  • Upload date:
  • Size: 7.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for try_or-1.0.1.tar.gz
Algorithm Hash digest
SHA256 154805c7816c5ccc0e1a0344e3516278c063d4f5dc405ea92e279f3e04765691
MD5 00314883c273b0b5fd26584815c18215
BLAKE2b-256 f17d688fc2f298ebb3eb32fda037d855a45102dd5977ff835575d6960dd592d8

See more details on using hashes here.

Provenance

The following attestation bundles were made for try_or-1.0.1.tar.gz:

Publisher: python-publish.yml on nakat-t/try-or-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

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

File metadata

  • Download URL: try_or-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 3.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for try_or-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 2870d12f4df45d014eb39fb0b8b089cb08d0e332af16b2907eac693e9083409f
MD5 7bac30cfdfdc33125b5169660657063d
BLAKE2b-256 47e7c72ec7b04561863a326ad435802e806f7935e475e76362e2222919d74653

See more details on using hashes here.

Provenance

The following attestation bundles were made for try_or-1.0.1-py3-none-any.whl:

Publisher: python-publish.yml on nakat-t/try-or-py

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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