Skip to content

Commit

Permalink
Field.number(kind=...) supports any function that returns a number
Browse files Browse the repository at this point in the history
For example, in our internal codebase, we have a function:

```python
def decimal_from_str(value: str, parens_negate: bool = False) -> Decimal:
    ...

amount = Field.number(kind=decimal_from_str)
```
  • Loading branch information
rouge8 committed Mar 11, 2024
1 parent 0f3597e commit 0e6d4c0
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/klein/_form.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
NoReturn,
Optional,
Sequence,
Type,
TypeVar,
cast,
)

Expand All @@ -29,6 +29,7 @@

from ._app import KleinRenderable, _call
from ._decorators import bindable
from ._typing_compat import Protocol
from .interfaces import (
EarlyExit,
IDependencyInjector,
Expand All @@ -41,6 +42,20 @@
)


_T = TypeVar("_T", contravariant=True)


class _Numeric(Protocol[_T]):
def __float__(self) -> float:
...

Check warning on line 50 in src/klein/_form.py

View check run for this annotation

Codecov / codecov/patch

src/klein/_form.py#L50

Added line #L50 was not covered by tests

def __lt__(self, other: _T) -> bool:
...

Check warning on line 53 in src/klein/_form.py

View check run for this annotation

Codecov / codecov/patch

src/klein/_form.py#L53

Added line #L53 was not covered by tests

def __gt__(self, other: _T) -> bool:
...

Check warning on line 56 in src/klein/_form.py

View check run for this annotation

Codecov / codecov/patch

src/klein/_form.py#L56

Added line #L56 was not covered by tests


class CrossSiteRequestForgery(Resource):
"""
Cross site request forgery detected. Request aborted.
Expand Down Expand Up @@ -258,9 +273,9 @@ def hidden(cls, name: str, value: str, **kw: Any) -> "Field":
@classmethod
def number(
cls,
minimum: Optional[int] = None,
maximum: Optional[int] = None,
kind: Type = float,
minimum: Optional[_Numeric] = None,
maximum: Optional[_Numeric] = None,
kind: Callable[[str], _Numeric] = float,
**kw: Any,
) -> "Field":
"""
Expand Down

0 comments on commit 0e6d4c0

Please sign in to comment.