Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python typehint int as positive

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?

like image 843
Daniel Morell Avatar asked Sep 13 '25 04:09

Daniel Morell


2 Answers

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.

like image 138
soapergem Avatar answered Sep 14 '25 18:09

soapergem


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

like image 37
Lucas Vazquez Avatar answered Sep 14 '25 17:09

Lucas Vazquez