I am curious what would be the best way to specify that a type is not just a int
but a positive int
in Python.
Examples:
# As function argument
def my_age(age: int) -> str:
return f"You are {age} years old."
# As class property
class User:
id: int
In both of these situations a negative value would be erroneous. It would be nice to be warned by my IDE/linter.
Is there a simple way to specify an integer as positive using type-hints?
Little late to the party but there is now a library called annotated-types that provides exactly what you want and is the 'official' way to go about this, per PEP-593. So for your example of positive integers, you could make use of the built-in typing.Annotated
and annotated-types' Gt
predicate, like this:
from typing import Annotated
from annotated_types import Gt
def my_age(age: Annotated[int, Gt(0)]) -> str:
return f"You are {age} years old."
# As class property
class User:
id: Annotated[int, Gt(0)]
Note that like all things related to type hints in Python, this doesn't actually enforce the constraint at runtime. If you want to enforce it you would still have to build assertions yourself.
If you are using FastAPI, you can use PositiveInt
from pydantic
.
from pydantic.types import PositiveInt
class Pizza:
price: PositiveInt
Read more: https://pydantic-docs.helpmanual.io/usage/types/#pydantic-types
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With