https://github.com/mianfg/pvv
Minimal Python decorator to enforce type validation from type hints
https://github.com/mianfg/pvv
python python-decorators validation
Last synced: 8 days ago
JSON representation
Minimal Python decorator to enforce type validation from type hints
- Host: GitHub
- URL: https://github.com/mianfg/pvv
- Owner: mianfg
- License: mit
- Created: 2024-02-21T15:18:44.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2024-02-23T13:51:41.000Z (almost 2 years ago)
- Last Synced: 2025-09-29T04:21:23.624Z (4 months ago)
- Topics: python, python-decorators, validation
- Language: Python
- Homepage: https://pypi.org/project/pvv/
- Size: 6.84 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# pvv
Minimal Python decorator to enforce type validation from type hints
## Installation
This library has been created to have zero dependencies, and work with native Python. Use your favorite package manager to install `pvv` from PyPI.
```
pip install pvv
```
## Usage
There are two ways to use the `validate` decorator from `pvv`:
### Validate all parameters
Just use the decorator. A `TypeError` will be raised if the function is called with parameters of incorrect type.
> [!NOTE]
> `pvv` will check if the given parameters to a function are instances of the class annotated as a parameter. If one parameter has no type hints, it will be ignored in the validation.
> [!WARNING]
> `pvv` will only work with type hints that can be used with class and instance checks.
```python
from pvv import validate
@validate
def function(a: str, b: int, c):
pass
```
```
>>> function("a", 3, 2)
>>> function(c=2, a="a", b=2)
>>> function(3, "a", 2)
TypeError: Incorrect type of function arguments: 'a' must be of type 'str', 'b' must be of type 'int'
```
### Validate some parameters
```python
from pvv import validate
@validate('a', 'c')
def function(a: str, b: int, c: bool | None):
pass
```
```
>>> function("a", 3, True)
>>> function(3, "b", 0)
TypeError: Incorrect type of function arguments: 'a' must be of type 'str', 'c' must be of type 'bool | None'
```
### An important note
The parameters of the `validate` decorator must all be of type `str`, otherwise a `ValidatorError` will be raised:
```
>>> @validate('a', 1)
... def func(*args, **kwargs):
... pass
pvv.exceptions.ValidatorError: All arguments of decorator must be of type 'str'
```