This packages includes many decorators that will make you write cleaner Python code.
The @pedantic decorator - Type checking at runtime
The @pedantic decorator does the following things:
- The decorated function can only be called by using keyword arguments. Positional arguments are not accepted.
- The decorated function must have type annotations.
- Each time the decorated function is called, pedantic checks that the passed arguments and the return value of the function matches the given type annotations.
As a consequence, the arguments are also checked for
None, becauseNoneis only a valid argument, if it is annotated viatyping.Optional.
In a nutshell:
@pedantic raises an PedanticException if one of the following happened:
- The decorated function is called with positional arguments.
- The function has no type annotation for their return type or one or more parameters do not have type annotations.
- A type annotation is incorrect.
- A type annotation misses type arguments, e.g.
typing.Listinstead oftyping.List[int].
from pedantic import pedantic
@pedantic
def get_sum_of(values: list[int | float]) -> int:
return sum(values)
get_sum_of(values=[0, 1.2, 3, 5.4]) # this raises the following runtime error:
# Type hint of return value is incorrect: Expected type <class 'int'> but 10.0 of type <class 'float'> was the return value which does not match.The @validate decorator
As the name suggests, with @validate you are able to validate the values that are passed to the decorated function.
- @deprecated
- @frozen_dataclass
- @frozen_type_safe_dataclass
- @for_all_methods
- @in_subprocess
- @overrides
- @pedantic
- @pedantic_class
- @require_kwargs
- @retry
- @trace
- @trace_class
- @trace_if_returns
- @validate
There are no hard dependencies. But if you want to use some advanced features you need to install the following packages:
- multiprocess if you want to use the
@in_subprocessdecorator - flask if you want to you the request validators which are designed for
Flask(see unit tests for examples):FlaskParameter(abstract class)FlaskJsonParameterFlaskFormParameterFlaskPathParameterFlaskGetParameterFlaskHeaderParameterGenericFlaskDeserializer
This project is based on poetry and taskfile.
Tip: Run task validate before making commits.
The usage of decorators may affect the performance of your application.
For this reason, I would highly recommend you to disable the decorators if your code runs in a productive environment.
You can disable pedantic by set an environment variable:
export ENABLE_PEDANTIC=0
You can also disable or enable the environment variables in your project by calling a method:
from pedantic import enable_pedantic, disable_pedantic
enable_pedantic()This package is not compatible with compiled source code (e.g. with Nuitka).
That's because it uses the inspect module from the standard library which will raise errors like OSError: could not get source code in case of compiled source code.
Don't forget to check out the documentation.