From: Libor MartĂ­nek Date: Sun, 30 Jan 2022 11:55:31 +0000 (+0100) Subject: Make base convertors.Convertor generic and annotate its subclasses (#1451) X-Git-Tag: 0.19.0~53 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=84820a25f2237c7c8fe7911f4fea2394f02994e8;p=thirdparty%2Fstarlette.git Make base convertors.Convertor generic and annotate its subclasses (#1451) Co-authored-by: Marcelo Trylesinski --- diff --git a/starlette/convertors.py b/starlette/convertors.py index d90a9cd1..e3c03d07 100644 --- a/starlette/convertors.py +++ b/starlette/convertors.py @@ -2,24 +2,26 @@ import math import typing import uuid +T = typing.TypeVar("T") -class Convertor: - regex = "" - def convert(self, value: str) -> typing.Any: +class Convertor(typing.Generic[T]): + regex: typing.ClassVar[str] = "" + + def convert(self, value: str) -> T: raise NotImplementedError() # pragma: no cover - def to_string(self, value: typing.Any) -> str: + def to_string(self, value: T) -> str: raise NotImplementedError() # pragma: no cover class StringConvertor(Convertor): regex = "[^/]+" - def convert(self, value: str) -> typing.Any: + def convert(self, value: str) -> str: return value - def to_string(self, value: typing.Any) -> str: + def to_string(self, value: str) -> str: value = str(value) assert "/" not in value, "May not contain path separators" assert value, "Must not be empty" @@ -29,20 +31,20 @@ class StringConvertor(Convertor): class PathConvertor(Convertor): regex = ".*" - def convert(self, value: str) -> typing.Any: + def convert(self, value: str) -> str: return str(value) - def to_string(self, value: typing.Any) -> str: + def to_string(self, value: str) -> str: return str(value) class IntegerConvertor(Convertor): regex = "[0-9]+" - def convert(self, value: str) -> typing.Any: + def convert(self, value: str) -> int: return int(value) - def to_string(self, value: typing.Any) -> str: + def to_string(self, value: int) -> str: value = int(value) assert value >= 0, "Negative integers are not supported" return str(value) @@ -51,10 +53,10 @@ class IntegerConvertor(Convertor): class FloatConvertor(Convertor): regex = "[0-9]+(.[0-9]+)?" - def convert(self, value: str) -> typing.Any: + def convert(self, value: str) -> float: return float(value) - def to_string(self, value: typing.Any) -> str: + def to_string(self, value: float) -> str: value = float(value) assert value >= 0.0, "Negative floats are not supported" assert not math.isnan(value), "NaN values are not supported" @@ -65,10 +67,10 @@ class FloatConvertor(Convertor): class UUIDConvertor(Convertor): regex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" - def convert(self, value: str) -> typing.Any: + def convert(self, value: str) -> uuid.UUID: return uuid.UUID(value) - def to_string(self, value: typing.Any) -> str: + def to_string(self, value: uuid.UUID) -> str: return str(value)