Skip to content

Commit

Permalink
Use Self type from PEP 673 everywhere (#183)
Browse files Browse the repository at this point in the history
This PR makes consistent use of the `Self` type. It also removes version checks for `from typing_extensions Self` and others as typing_extentions is considered a builtin module in stubs by all major type checkers (see typeshed). I added an isort option to reflect that fact similar to what is done in the typeshed project.
  • Loading branch information
hamdanal authored Aug 26, 2023
1 parent c862c7f commit 7c19828
Show file tree
Hide file tree
Showing 38 changed files with 137 additions and 210 deletions.
2 changes: 1 addition & 1 deletion django-stubs/contrib/admin/options.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ from typing import (
TypeVar,
Union,
)
from typing_extensions import Literal, TypedDict

from django.contrib.admin.filters import ListFilter
from django.contrib.admin.models import LogEntry
Expand Down Expand Up @@ -47,7 +48,6 @@ from django.http.response import (
from django.template.response import TemplateResponse
from django.urls.resolvers import URLPattern
from django.utils.safestring import SafeText
from typing_extensions import Literal, TypedDict

IS_POPUP_VAR: str
TO_FIELD_VAR: str
Expand Down
7 changes: 1 addition & 6 deletions django-stubs/contrib/auth/base_user.pyi
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
import sys
from typing import Any, List, Optional, Tuple, TypeVar, Union, overload
from typing_extensions import Literal

from django.db import models
from django.db.models.base import Model
from django.db.models.fields import BooleanField

if sys.version_info < (3, 8):
from typing_extensions import Literal
else:
from typing import Literal

_T = TypeVar("_T", bound=Model)

class BaseUserManager(models.Manager[_T]):
Expand Down
12 changes: 1 addition & 11 deletions django-stubs/contrib/auth/models.pyi
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import sys
from typing import Any, ClassVar, Collection, Optional, Set, Tuple, Type, TypeVar, Union
from typing_extensions import Literal, Self

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.base_user import AbstractBaseUser as AbstractBaseUser
Expand All @@ -10,16 +10,6 @@ from django.db import models
from django.db.models.base import Model
from django.db.models.manager import EmptyManager

if sys.version_info < (3, 8):
from typing_extensions import Literal
else:
from typing import Literal

if sys.version_info < (3, 11):
from typing_extensions import Self
else:
from typing import Self

_AnyUser = Union[Model, "AnonymousUser"]

def update_last_login(
Expand Down
3 changes: 2 additions & 1 deletion django-stubs/contrib/contenttypes/fields.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
from typing_extensions import Self

from django.contrib.contenttypes.models import ContentType
from django.core.checks.messages import CheckMessage
Expand Down Expand Up @@ -84,7 +85,7 @@ class GenericRelation(ForeignObject[Any]):
content_type_field_name: Any = ...
for_concrete_model: Any = ...
to_fields: Any = ...
def __new__(cls, *args: Any, **kwargs: Any) -> GenericRelation: ...
def __new__(cls, *args: Any, **kwargs: Any) -> Self: ...
def __init__(
self,
to: Union[Type[Model], str],
Expand Down
4 changes: 2 additions & 2 deletions django-stubs/contrib/humanize/templatetags/humanize.pyi
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from datetime import date
from datetime import datetime as datetime
from typing import Any, Callable, Dict, Optional, SupportsInt, Tuple, Type, Union
from typing import Any, Callable, Dict, Optional, SupportsInt, Tuple, Union

from django import template

Expand All @@ -21,4 +21,4 @@ class NaturalTimeFormatter:
past_substrings: Dict[str, str]
future_substrings: Dict[str, str]
@classmethod
def string_for(cls: Type[NaturalTimeFormatter], value: Any) -> Any: ...
def string_for(cls, value: Any) -> Any: ...
2 changes: 1 addition & 1 deletion django-stubs/contrib/postgres/fields/array.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ from typing import (
Union,
overload,
)
from typing_extensions import Literal

from django.db.models.expressions import Combinable
from django.db.models.fields import Field, _ErrorMessagesToOverride, _ValidatorCallable
from typing_extensions import Literal

from .mixins import CheckFieldDefaultMixin

Expand Down
12 changes: 6 additions & 6 deletions django-stubs/contrib/postgres/fields/citext.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ from typing import (
Union,
overload,
)
from typing_extensions import Literal

from django.db.models.fields import CharField, EmailField, TextField
from typing_extensions import Literal

_Choice = Tuple[Any, Any]
_ChoiceNamedGroup = Tuple[str, Iterable[_Choice]]
Expand Down Expand Up @@ -75,8 +75,8 @@ class CICharField(CIText, CharField[_C]):
validators: Iterable[_ValidatorCallable] = ...,
error_messages: Optional[_ErrorMessagesToOverride] = ...,
) -> None: ...
def __get__(self: CICharField[_C], instance: Any, owner: Any) -> _C: ...
def __set__(self: CICharField[_C], instance: Any, value: _C) -> None: ... # type: ignore [override]
def __get__(self, instance: Any, owner: Any) -> _C: ...
def __set__(self, instance: Any, value: _C) -> None: ... # type: ignore [override]

class CIEmailField(CIText, EmailField[_C]):
@overload
Expand Down Expand Up @@ -129,7 +129,7 @@ class CIEmailField(CIText, EmailField[_C]):
validators: Iterable[_ValidatorCallable] = ...,
error_messages: Optional[_ErrorMessagesToOverride] = ...,
) -> None: ...
def __get__(self: CIEmailField[_C], instance: Any, owner: Any) -> _C: ...
def __get__(self, instance: Any, owner: Any) -> _C: ...
def __set__(self, instance: Any, value: _C) -> None: ... # type: ignore [override]

class CITextField(CIText, TextField[_C]):
Expand Down Expand Up @@ -183,5 +183,5 @@ class CITextField(CIText, TextField[_C]):
validators: Iterable[_ValidatorCallable] = ...,
error_messages: Optional[_ErrorMessagesToOverride] = ...,
) -> None: ...
def __get__(self: CITextField[_C], instance: Any, owner: Any) -> _C: ...
def __set__(self: CITextField[_C], instance: Any, value: _C) -> None: ... # type: ignore [override]
def __get__(self, instance: Any, owner: Any) -> _C: ...
def __set__(self, instance: Any, value: _C) -> None: ... # type: ignore [override]
6 changes: 3 additions & 3 deletions django-stubs/contrib/postgres/fields/hstore.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ from typing import (
Union,
overload,
)
from typing_extensions import Literal

from django.db.models import Field, Transform
from typing_extensions import Literal

from .mixins import CheckFieldDefaultMixin

Expand Down Expand Up @@ -76,8 +76,8 @@ class HStoreField(Generic[_T], CheckFieldDefaultMixin, Field[Any, Any]):
error_messages: Optional[_ErrorMessagesToOverride] = ...,
) -> None: ...
def get_transform(self, name: Any) -> Any: ...
def __get__(self: HStoreField[_T], instance: Any, owner: Any) -> _T: ...
def __set__(self: HStoreField[_T], instance: Any, value: _T) -> None: ...
def __get__(self, instance: Any, owner: Any) -> _T: ...
def __set__(self, instance: Any, value: _T) -> None: ...

class KeyTransform(Transform):
def __init__(self, key_name: str, *args: Any, **kwargs: Any) -> None: ...
Expand Down
15 changes: 7 additions & 8 deletions django-stubs/contrib/postgres/search.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Any, Dict, Iterable, Optional, TypeVar, Union
from typing import Any, Dict, Iterable, Optional, Union
from typing_extensions import Self

from django.db.models import Field
from django.db.models.expressions import (
Expand Down Expand Up @@ -88,15 +89,13 @@ class CombinedSearchVector(SearchVectorCombinable, CombinedExpression):
output_field: Optional[_OutputField] = ...,
) -> None: ...

_T = TypeVar("_T", bound="SearchQueryCombinable")

class SearchQueryCombinable:
BITAND: str = ...
BITOR: str = ...
def __or__(self: _T, other: SearchQueryCombinable) -> _T: ...
def __ror__(self: _T, other: SearchQueryCombinable) -> _T: ...
def __and__(self: _T, other: SearchQueryCombinable) -> _T: ...
def __rand__(self: _T, other: SearchQueryCombinable) -> _T: ...
def __or__(self, other: SearchQueryCombinable) -> Self: ...
def __ror__(self, other: SearchQueryCombinable) -> Self: ...
def __and__(self, other: SearchQueryCombinable) -> Self: ...
def __rand__(self, other: SearchQueryCombinable) -> Self: ...

class SearchQuery(SearchQueryCombinable, Value): # type: ignore
SEARCH_TYPES: Dict[str, str] = ...
Expand All @@ -109,7 +108,7 @@ class SearchQuery(SearchQueryCombinable, Value): # type: ignore
invert: bool = ...,
search_type: str = ...
) -> None: ...
def __invert__(self: _T) -> _T: ...
def __invert__(self) -> Self: ...

class CombinedSearchQuery(SearchQueryCombinable, CombinedExpression): # type: ignore
def __init__(
Expand Down
2 changes: 1 addition & 1 deletion django-stubs/contrib/staticfiles/finders.pyi
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from typing import Any, Iterable, Iterator, List, Mapping, Optional, Union, overload
from typing_extensions import Literal

from django.core.checks.messages import CheckMessage
from django.core.files.storage import Storage
from typing_extensions import Literal

searched_locations: Any

Expand Down
9 changes: 4 additions & 5 deletions django-stubs/core/files/base.pyi
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import types
from io import StringIO
from typing import IO, Any, Iterator, Optional, Type, TypeVar, Union
from typing import IO, Any, Iterator, Optional, Type, Union
from typing_extensions import Self

from django.core.files.utils import FileProxyMixin

_T = TypeVar("_T", bound="File")

class File(FileProxyMixin, IO[Any]):
DEFAULT_CHUNK_SIZE: Any = ...
file: IO[Any] = ...
Expand All @@ -20,14 +19,14 @@ class File(FileProxyMixin, IO[Any]):
def multiple_chunks(self, chunk_size: Optional[int] = ...) -> bool: ...
def __iter__(self) -> Iterator[Union[bytes, str]]: ...
def __next__(self) -> Union[bytes, str]: ...
def __enter__(self: _T) -> _T: ...
def __enter__(self) -> Self: ...
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
tb: Optional[types.TracebackType],
) -> None: ...
def open(self: _T, mode: Optional[str] = ...) -> _T: ...
def open(self, mode: Optional[str] = ...) -> Self: ...
def close(self) -> None: ...

class ContentFile(File):
Expand Down
2 changes: 1 addition & 1 deletion django-stubs/core/files/uploadedfile.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,4 @@ class SimpleUploadedFile(InMemoryUploadedFile):
self, name: str, content: Optional[Union[bytes, str]], content_type: str = ...
) -> None: ...
@classmethod
def from_dict(cls: Any, file_dict: Dict[str, Union[str, bytes]]) -> None: ...
def from_dict(cls, file_dict: Dict[str, Union[str, bytes]]) -> None: ...
7 changes: 3 additions & 4 deletions django-stubs/core/mail/backends/base.pyi
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import types
from typing import Any, Iterable, Optional, Type, TypeVar
from typing import Any, Iterable, Optional, Type
from typing_extensions import Self

from django.core.mail.message import EmailMessage

_T = TypeVar("_T", bound="BaseEmailBackend")

class BaseEmailBackend:
def __init__(self, fail_silently: bool = ..., **kwargs: Any) -> None: ...
def open(self) -> Optional[bool]: ...
def close(self) -> None: ...
def __enter__(self: _T) -> _T: ...
def __enter__(self) -> Self: ...
def __exit__(
self,
exc_type: Type[BaseException],
Expand Down
2 changes: 1 addition & 1 deletion django-stubs/db/backends/utils.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ from typing import (
Type,
Union,
)
from typing_extensions import Literal
from uuid import UUID

import psycopg2
from django.db.backends.postgresql.base import DatabaseWrapper
from psycopg2.extensions import Column
from typing_extensions import Literal

logger: Any

Expand Down
3 changes: 2 additions & 1 deletion django-stubs/db/migrations/migration.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import List, Optional, Tuple
from typing_extensions import Self

from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.operations.base import Operation
Expand Down Expand Up @@ -32,6 +33,6 @@ class Migration:

class SwappableTuple(Tuple[str, str]):
setting: str = ...
def __new__(cls, value: Tuple[str, str], setting: str) -> SwappableTuple: ...
def __new__(cls, value: Tuple[str, str], setting: str) -> Self: ...

def swappable_dependency(value: str) -> SwappableTuple: ...
22 changes: 5 additions & 17 deletions django-stubs/db/models/base.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import sys
from typing import (
Any,
Callable,
Expand All @@ -11,9 +10,9 @@ from typing import (
Set,
Tuple,
Type,
TypeVar,
Union,
)
from typing_extensions import Self

from django.core.checks.messages import CheckMessage
from django.core.exceptions import (
Expand All @@ -23,14 +22,6 @@ from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db.models.manager import BaseManager
from django.db.models.options import Options

if sys.version_info < (3, 11):
from typing_extensions import Self
else:
from typing import Self

_M = TypeVar("_M", bound=Any)
_Self = TypeVar("_Self", bound="Model")

class ModelStateFieldsCacheDescriptor: ...

class ModelState:
Expand All @@ -55,11 +46,8 @@ class Model(metaclass=ModelBase):
def add_to_class(cls, name: str, value: Any) -> Any: ...
@classmethod
def from_db(
cls: Type[_Self],
db: Optional[str],
field_names: Collection[str],
values: Collection[Any],
) -> _Self: ...
cls, db: Optional[str], field_names: Collection[str], values: Collection[Any]
) -> Self: ...
def delete(
self, using: Any = ..., keep_parents: bool = ...
) -> Tuple[int, Dict[str, int]]: ...
Expand All @@ -76,8 +64,8 @@ class Model(metaclass=ModelBase):
def clean_fields(self, exclude: Optional[Collection[str]] = ...) -> None: ...
def validate_unique(self, exclude: Optional[Collection[str]] = ...) -> None: ...
def unique_error_message(
self: _Self,
model_class: Type[_Self],
self,
model_class: Type[Self],
unique_check: Collection[Union[Callable[..., Any], str]],
) -> ValidationError: ...
def save(
Expand Down
7 changes: 3 additions & 4 deletions django-stubs/db/models/constraints.pyi
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
from enum import Enum
from typing import Any, Optional, Sequence, Tuple, Type, TypeVar, Union
from typing import Any, Optional, Sequence, Tuple, Type, Union
from typing_extensions import Self

from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.models.base import Model
from django.db.models.expressions import BaseExpression, Combinable
from django.db.models.query_utils import Q

_T = TypeVar("_T", bound="BaseConstraint")

class Deferrable(Enum):
DEFERRED: str
IMMEDIATE: str
Expand Down Expand Up @@ -36,7 +35,7 @@ class BaseConstraint:
schema_editor: Optional[BaseDatabaseSchemaEditor],
) -> str: ...
def deconstruct(self) -> Any: ...
def clone(self: _T) -> _T: ...
def clone(self) -> Self: ...

class CheckConstraint(BaseConstraint):
check: Q
Expand Down
Loading

0 comments on commit 7c19828

Please sign in to comment.