single |
# annotated-types
[CI]
[pypi]
[versions]
[license]
[PEP-593] added `typing.Annotated` as a way of
adding context-specific metadata to existing types, and specifies that
`Annotated[T, x]` _should_ be treated as `T` by any tool or library without
special
logic for `x`.
This package provides metadata objects which can be used to represent
common
constraints such as upper and lower bounds on scalar values and collection
sizes,
a `Predicate` marker for runtime checks, and
descriptions of how we intend these metadata to be interpreted. In some
cases,
we also note alternative representations which do not require this package.
## Install
```bash
pip install annotated-types
```
## Examples
```python
from typing import Annotated
from annotated_types import Gt, Len, Predicate
class MyClass:
age: Annotated[int, Gt(18)] # Valid: 19, 20,
...
# Invalid: 17, 18,
"19", 19.0, ...
factors: list[Annotated[int, Predicate(is_prime)]] # Valid: 2, 3, 5,
7, 11, ...
# Invalid: 4, 8,
-2, 5.0, "prime", ...
my_list: Annotated[list[int], Len(0, 10)] # Valid: [], [10,
20, 30, 40, 50]
# Invalid: (1, 2),
["abc"], [0] * 20
```
## Documentation
_While `annotated-types` avoids runtime checks for performance, users
should not
construct invalid combinations such as `MultipleOf("non-numeric")` or
`Annotated[int, Len(3)]`.
Downstream implementors may choose to raise an error, emit a warning,
silently ignore
a metadata item, etc., if the metadata objects described below are used
with an
incompatible type - or for any other reason!_
### Gt, Ge, Lt, Le
Express inclusive and/or exclusive bounds on orderable values - which may
be numbers,
dates, times, strings, sets, etc. Note that the boundary value need not be
of the
same type that was annotated, so long as they can be compared:
`Annotated[int, Gt(1.5)]`
is fine, for example, and implies that the value is an integer x such that
`x > 1.5`.
We suggest that implementors may also interpret
`functools.partial(operator.le, 1.5)`
as being equivalent to `Gt(1.5)`, for users who wish to avoid a runtime
dependency on
the `annotated-types` package.
To be explicit, these types have the following meanings:
* `Gt(x)` - value must be "Greater Than" `x` - equivalent to exclusive
minimum
* `Ge(x)` - value must be "Greater than or Equal" to `x` - equivalent to
inclusive minimum
* `Lt(x)` - value must be "Less Than" `x` - equivalent to exclusive maximum
* `Le(x)` - value must be "Less than or Equal" to `x` - equivalent to
inclusive maximum
### Interval
`Interval(gt, ge, lt, le)` allows you to specify an upper and lower bound
with a single
metadata object. `None` attributes should be ignored, and non-`None`
attributes
treated as per the single bounds above.
### MultipleOf
`MultipleOf(multiple_of=x)` might be interpreted in two ways:
|