Extend typehints to include dynamic checks (that might otherwise be dealt with by assertions) in Python.
Project description
For more info, please visit the GitHub page of this project.
Basic example
import parameter_checks as pc
@pc.hints.cleanup # be left with only type-annotations
@pc.hints.enforce # enforce the lambda but not the types
def div(a: int, b: pc.annotations.Checks[int, lambda b: b != 0]):
return a / b
div(1, 1) # returns 1.0
div(1, 0) # raises ValueError
As can be seen in this example, this package provides a new type-annotation:
pc.annotations.Checks
(it also provides pc.annotations.Hooks, see below).
Using @pc.hints.enforce on a function
will enforce the checks given to those annotations (but not the types).
@pc.hints.cleanup would produce the
div.__annotations__
of {"a": int, "b": int}
in the example above.
Complex example
import parameter_checks as pc
def decision_boundary(fct, parameter, parameter_name, typehint):
if type(parameter) is not typehint:
err_str = f"In function {fct}, parameter {parameter_name}={parameter} " \
f"is not of type {typehint}!"
raise TypeError(err_str)
# Yes, the following calculation should be in the function-body,
# but it demonstrates that arbitrary changes can be made here,
# which might be useful if, for example, some conversion has
# to happen in many parameters of many functions.
# Moving that conversion into its own function and calling it
# in the typehint might make the program more readable than
# packing it into the function-body.
return 3 + 4 * parameter - parameter ** 2
@pc.hints.enforce
def foo(
x: pc.annotations.Hooks[float, decision_boundary],
additional_offset: pc.annotations.Checks[float, lambda b: 0 <= b <= 100] = 0.
):
return x + additional_offset
assert foo(1.) == 6.
assert foo(2.) == 7.
assert foo(5.) == -2.
assert foo(5., 2.) == 0.
foo("not a float!") # raises TypeError
foo(1., -1.) # raises ValueError
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
parameter-checks-0.1.3.tar.gz
(9.3 kB
view hashes)
Built Distribution
Close
Hashes for parameter_checks-0.1.3-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | e5688478d1fe56d5c9b66abd0993c5b8d6e1ca651c7323f8779e8412235fd822 |
|
MD5 | 6ff204bf33d7ae80a87961193b245c3f |
|
BLAKE2b-256 | 54da12d49ec4d83ba535e4cc18ca0cef227aba133d27c915178ee2a619a9f821 |