Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add URL converter protocol type #1984

Merged
merged 1 commit into from
Mar 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions django-stubs/urls/converters.pyi
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from typing import Any
from typing import Any, Protocol
from uuid import UUID

class _Converter(Protocol):
regex: str
def __init__(self) -> None: ...
def to_python(self, value: str) -> Any: ...
def to_url(self, value: Any) -> str: ...

class IntConverter:
regex: str
def to_python(self, value: str) -> int: ...
Expand All @@ -19,9 +25,9 @@ class UUIDConverter:
class SlugConverter(StringConverter): ...
class PathConverter(StringConverter): ...

DEFAULT_CONVERTERS: dict[str, Any]
REGISTERED_CONVERTERS: dict[str, Any]
DEFAULT_CONVERTERS: dict[str, _Converter]
REGISTERED_CONVERTERS: dict[str, _Converter]

def register_converter(converter: type[Any], type_name: str) -> None: ...
def get_converters() -> dict[str, Any]: ...
def get_converter(raw_converter: str) -> Any: ...
def register_converter(converter: type[_Converter], type_name: str) -> None: ...
def get_converters() -> dict[str, _Converter]: ...
def get_converter(raw_converter: str) -> _Converter: ...
36 changes: 36 additions & 0 deletions tests/typecheck/urls/test_converters.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
- case: test_register_converter_builtin
main: |
from django.urls import register_converter
from django.urls.converters import IntConverter

register_converter(IntConverter, "bigint")

- case: test_register_converter_custom
main: |
from django.urls import register_converter

class BigIntConverter:
regex = r"[0-9]+"

def to_python(self, value: str) -> int:
return int(value)

def to_url(self, value: int) -> str:
return str(value)

register_converter(BigIntConverter, "bigint")

- case: test_register_converter_incorrect_types
main: |
from django.urls import register_converter

class BigIntConverter:
regex = r"[0-9]+"

def to_python(self, value: int) -> str:
return str(value)

def to_url(self, value: str) -> int:
return int(value)

register_converter(BigIntConverter, "bigint") # E: Argument 1 to "register_converter" has incompatible type "Type[BigIntConverter]"; expected "Type[_Converter]" [arg-type]