Utility functions to unwrap Optional values
Project description
unopt: Utility functions to unwrap Optional[T]
Overview
unopt provides several utility functions to "unwrap" the Optional[T]
(or T | None
)
objects: removes the Optional
type hint and obtains the underlying object.
unopt functions are inspired by the Rust's Option<T>
functionality, but the behavior
is tuned to Python's convention. E.g., unwrap()
raises an exception instead of
aborting.
Install
pip install unopt
Examples
from unopt import *
foo: Optional[int] = 123
bar: Optional[int] = None
# unwrap() returns the given object if it is not None.
assert unwrap(foo) == 123
unwrap(bar) # Raises UnwrapError
# unwrap_or() returns the default value if the given object is None.
assert unwrap_or(foo, 456) == 123
assert unwrap_or(bar, 456) == 456
# unwrap_or_else() returns the default value obtained by invoking the given function.
assert unwrap_or_else(foo, lambda: 456) == 123
assert unwrap_or_else(bar, lambda: 456) == 456
# unwrap_unchecked() just casts the given object without value checking.
assert unwrap_unchecked(foo) == 123
assert unwrap_unchecked(bar) is None # Unsafe
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
unopt-0.2.0.tar.gz
(3.8 kB
view details)
Built Distribution
unopt-0.2.0-py3-none-any.whl
(3.8 kB
view details)
File details
Details for the file unopt-0.2.0.tar.gz
.
File metadata
- Download URL: unopt-0.2.0.tar.gz
- Upload date:
- Size: 3.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.6
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 43c2b629ef94f465bee0a74e13d46faa2245810fec50bde346226e5f573ad082 |
|
MD5 | 7fdf9e29c090c7eae9f0b9a0760ed34a |
|
BLAKE2b-256 | 169469faaf0460d3a97b89c22dc3aa8c4114134f798d155c69386021d9861070 |
File details
Details for the file unopt-0.2.0-py3-none-any.whl
.
File metadata
- Download URL: unopt-0.2.0-py3-none-any.whl
- Upload date:
- Size: 3.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.6
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | e46d972ada65f251364d8da33fe8060d99314e332df4f4d0e5d41f5707d561f4 |
|
MD5 | 2824939b426ea2486d4f57b2b710b6f2 |
|
BLAKE2b-256 | 452a8de3493e54bc14b823c1d427a1a702c1f484727bc5435ed9597c9b58b33e |