Skip to content

Commit

Permalink
Bump mypy from 0.770 to 0.780 (#1598)
Browse files Browse the repository at this point in the history
* Bump mypy from 0.770 to 0.780

Bumps [mypy](https://github.com/python/mypy) from 0.770 to 0.780.
- [Release notes](https://github.com/python/mypy/releases)
- [Commits](python/mypy@v0.770...v0.780)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

* fix mypy errors and remove AnyType

* fix python 3.6 inconsistencies

* linting

* tweak typing

* fix typing for 3.6

* bump

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
Co-authored-by: Samuel Colvin <s@muelcolvin.com>
  • Loading branch information
dependabot-preview[bot] and samuelcolvin committed Jun 25, 2020
1 parent 97b6b46 commit 70d531f
Show file tree
Hide file tree
Showing 12 changed files with 54 additions and 47 deletions.
1 change: 1 addition & 0 deletions changes/1598-samuelcolvin.md
@@ -0,0 +1 @@
Update mypy, remove `AnyType` alias for `Type[Any]`
9 changes: 4 additions & 5 deletions pydantic/dataclasses.py
Expand Up @@ -5,7 +5,6 @@
from .errors import DataclassTypeError
from .fields import Required
from .main import create_model, validate_model
from .typing import AnyType

if TYPE_CHECKING:
from .main import BaseModel # noqa: F401
Expand Down Expand Up @@ -56,7 +55,7 @@ def setattr_validate_assignment(self: 'DataclassType', name: str, value: Any) ->


def _process_class(
_cls: AnyType,
_cls: Type[Any],
init: bool,
repr: bool,
eq: bool,
Expand Down Expand Up @@ -120,7 +119,7 @@ def _pydantic_post_init(self: 'DataclassType', *initvars: Any) -> None:


def dataclass(
_cls: Optional[AnyType] = None,
_cls: Optional[Type[Any]] = None,
*,
init: bool = True,
repr: bool = True,
Expand All @@ -129,15 +128,15 @@ def dataclass(
unsafe_hash: bool = False,
frozen: bool = False,
config: Type[Any] = None,
) -> Union[Callable[[AnyType], 'DataclassType'], 'DataclassType']:
) -> Union[Callable[[Type[Any]], 'DataclassType'], 'DataclassType']:
"""
Like the python standard lib dataclasses but with type validation.
Arguments are the same as for standard dataclasses, except for validate_assignment which has the same meaning
as Config.validate_assignment.
"""

def wrap(cls: AnyType) -> 'DataclassType':
def wrap(cls: Type[Any]) -> 'DataclassType':
return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen, config)

if _cls is None:
Expand Down
8 changes: 4 additions & 4 deletions pydantic/errors.py
@@ -1,8 +1,8 @@
from decimal import Decimal
from pathlib import Path
from typing import Any, Set, Union
from typing import Any, Set, Type, Union

from .typing import AnyType, display_as_type
from .typing import display_as_type

# explicitly state exports to avoid "from .errors import *" also importing Decimal, Path etc.
__all__ = (
Expand Down Expand Up @@ -413,7 +413,7 @@ class ArbitraryTypeError(PydanticTypeError):
code = 'arbitrary_type'
msg_template = 'instance of {expected_arbitrary_type} expected'

def __init__(self, *, expected_arbitrary_type: AnyType) -> None:
def __init__(self, *, expected_arbitrary_type: Type[Any]) -> None:
super().__init__(expected_arbitrary_type=display_as_type(expected_arbitrary_type))


Expand All @@ -426,7 +426,7 @@ class SubclassError(PydanticTypeError):
code = 'subclass'
msg_template = 'subclass of {expected_class} expected'

def __init__(self, *, expected_class: AnyType) -> None:
def __init__(self, *, expected_class: Type[Any]) -> None:
super().__init__(expected_class=display_as_type(expected_class))


Expand Down
5 changes: 2 additions & 3 deletions pydantic/fields.py
Expand Up @@ -27,7 +27,6 @@
from .errors import NoneIsNotAllowedError
from .types import Json, JsonWrapper
from .typing import (
AnyType,
Callable,
ForwardRef,
NoArgAnyCallable,
Expand Down Expand Up @@ -237,7 +236,7 @@ def __init__(
self,
*,
name: str,
type_: AnyType,
type_: Type[Any],
class_validators: Optional[Dict[str, Validator]],
model_config: Type['BaseConfig'],
default: Any = None,
Expand Down Expand Up @@ -486,7 +485,7 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity)
# type_ has been refined eg. as the type of a List and sub_fields needs to be populated
self.sub_fields = [self._create_sub_type(self.type_, '_' + self.name)]

def _create_sub_type(self, type_: AnyType, name: str, *, for_keys: bool = False) -> 'ModelField':
def _create_sub_type(self, type_: Type[Any], name: str, *, for_keys: bool = False) -> 'ModelField':
return self.__class__(
type_=type_,
name=name,
Expand Down
4 changes: 2 additions & 2 deletions pydantic/main.py
Expand Up @@ -33,7 +33,7 @@
from .parse import Protocol, load_file, load_str_bytes
from .schema import model_schema
from .types import PyObject, StrBytes
from .typing import AnyCallable, AnyType, ForwardRef, is_classvar, resolve_annotations, update_field_forward_refs
from .typing import AnyCallable, ForwardRef, is_classvar, resolve_annotations, update_field_forward_refs
from .utils import (
ClassAttribute,
GetterDict,
Expand Down Expand Up @@ -110,7 +110,7 @@ class BaseConfig:
schema_extra: Union[Dict[str, Any], 'SchemaExtraCallable'] = {}
json_loads: Callable[[str], Any] = json.loads
json_dumps: Callable[..., str] = json.dumps
json_encoders: Dict[AnyType, AnyCallable] = {}
json_encoders: Dict[Type[Any], AnyCallable] = {}

@classmethod
def get_field_info(cls, name: str) -> Dict[str, Any]:
Expand Down
4 changes: 2 additions & 2 deletions pydantic/schema.py
Expand Up @@ -737,7 +737,7 @@ def field_singleton_schema( # noqa: C901 (ignore complexity)
def multivalue_literal_field_for_schema(values: Tuple[Any, ...], field: ModelField) -> ModelField:
return ModelField(
name=field.name,
type_=Union[tuple(Literal[value] for value in values)],
type_=Union[tuple(Literal[value] for value in values)], # type: ignore
class_validators=field.class_validators,
model_config=field.model_config,
default=field.default,
Expand Down Expand Up @@ -801,7 +801,7 @@ def go(type_: Any) -> Type[Any]:
return type_

if origin is Union:
return Union[tuple(go(a) for a in args)]
return Union[tuple(go(a) for a in args)] # type: ignore

if issubclass(origin, List) and (field_info.min_items is not None or field_info.max_items is not None):
used_constraints.update({'min_items', 'max_items'})
Expand Down
3 changes: 1 addition & 2 deletions pydantic/types.py
Expand Up @@ -9,7 +9,6 @@
from uuid import UUID

from . import errors
from .typing import AnyType
from .utils import import_string, update_not_none
from .validators import (
bytes_validator,
Expand Down Expand Up @@ -527,7 +526,7 @@ class JsonWrapper:


class JsonMeta(type):
def __getitem__(self, t: AnyType) -> Type[JsonWrapper]:
def __getitem__(self, t: Type[Any]) -> Type[JsonWrapper]:
return type('JsonWrapperValue', (JsonWrapper,), {'inner_type': t})


Expand Down
53 changes: 31 additions & 22 deletions pydantic/typing.py
Expand Up @@ -24,21 +24,32 @@
except ImportError:
from typing import _Final as typing_base # type: ignore

try:
from typing import ForwardRef # type: ignore

def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Type[Any]:
return type_._evaluate(globalns, localns)
if sys.version_info < (3, 7):
if TYPE_CHECKING:

class ForwardRef:
def _eval_type(self, globalns: Any, localns: Any) -> Any:
pass

else:
from typing import _ForwardRef as ForwardRef
else:
from typing import ForwardRef

except ImportError:
# python 3.6
from typing import _ForwardRef as ForwardRef # type: ignore

def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Type[Any]:
if sys.version_info < (3, 7):

def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:
return type_._eval_type(globalns, localns)


else:

def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:
return type_._evaluate(globalns, localns)


if sys.version_info < (3, 7):
from typing import Callable as Callable

Expand Down Expand Up @@ -82,7 +93,6 @@ def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Type[
'Callable',
'AnyCallable',
'NoArgAnyCallable',
'AnyType',
'NoneType',
'display_as_type',
'resolve_annotations',
Expand All @@ -108,11 +118,10 @@ def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Type[
)


AnyType = Type[Any]
NoneType = None.__class__


def display_as_type(v: AnyType) -> str:
def display_as_type(v: Type[Any]) -> str:
if not isinstance(v, typing_base) and not isinstance(v, type):
v = v.__class__

Expand All @@ -131,7 +140,7 @@ def display_as_type(v: AnyType) -> str:
return str(v).replace('typing.', '')


def resolve_annotations(raw_annotations: Dict[str, AnyType], module_name: Optional[str]) -> Dict[str, AnyType]:
def resolve_annotations(raw_annotations: Dict[str, Type[Any]], module_name: Optional[str]) -> Dict[str, Type[Any]]:
"""
Partially taken from typing.get_type_hints.
Expand All @@ -157,25 +166,25 @@ def resolve_annotations(raw_annotations: Dict[str, AnyType], module_name: Option
return annotations


def is_callable_type(type_: AnyType) -> bool:
def is_callable_type(type_: Type[Any]) -> bool:
return type_ is Callable or getattr(type_, '__origin__', None) is Callable


if sys.version_info >= (3, 7):

def is_literal_type(type_: AnyType) -> bool:
def is_literal_type(type_: Type[Any]) -> bool:
return Literal is not None and getattr(type_, '__origin__', None) is Literal

def literal_values(type_: AnyType) -> Tuple[Any, ...]:
def literal_values(type_: Type[Any]) -> Tuple[Any, ...]:
return type_.__args__


else:

def is_literal_type(type_: AnyType) -> bool:
def is_literal_type(type_: Type[Any]) -> bool:
return Literal is not None and hasattr(type_, '__values__') and type_ == Literal[type_.__values__]

def literal_values(type_: AnyType) -> Tuple[Any, ...]:
def literal_values(type_: Type[Any]) -> Tuple[Any, ...]:
return type_.__values__


Expand All @@ -195,24 +204,24 @@ def all_literal_values(type_: Type[Any]) -> Tuple[Any, ...]:
test_type = NewType('test_type', str)


def is_new_type(type_: AnyType) -> bool:
def is_new_type(type_: Type[Any]) -> bool:
"""
Check whether type_ was created using typing.NewType
"""
return isinstance(type_, test_type.__class__) and hasattr(type_, '__supertype__') # type: ignore


def new_type_supertype(type_: AnyType) -> AnyType:
def new_type_supertype(type_: Type[Any]) -> Type[Any]:
while hasattr(type_, '__supertype__'):
type_ = type_.__supertype__
return type_


def _check_classvar(v: AnyType) -> bool:
def _check_classvar(v: Type[Any]) -> bool:
return v.__class__ == ClassVar.__class__ and (sys.version_info < (3, 7) or getattr(v, '_name', None) == 'ClassVar')


def is_classvar(ann_type: AnyType) -> bool:
def is_classvar(ann_type: Type[Any]) -> bool:
return _check_classvar(ann_type) or _check_classvar(getattr(ann_type, '__origin__', None))


Expand All @@ -228,7 +237,7 @@ def update_field_forward_refs(field: 'ModelField', globalns: Any, localns: Any)
update_field_forward_refs(sub_f, globalns=globalns, localns=localns)


def get_class(type_: AnyType) -> Union[None, bool, AnyType]:
def get_class(type_: Type[Any]) -> Union[None, bool, Type[Any]]:
"""
Tries to get the class of a Type[T] annotation. Returns True if Type is used
without brackets. Otherwise returns None.
Expand Down
6 changes: 3 additions & 3 deletions pydantic/utils.py
Expand Up @@ -19,7 +19,7 @@
no_type_check,
)

from .typing import AnyType, display_as_type
from .typing import display_as_type
from .version import version_info

if TYPE_CHECKING:
Expand Down Expand Up @@ -85,7 +85,7 @@ def truncate(v: Union[str], *, max_len: int = 80) -> str:
return v


def sequence_like(v: AnyType) -> bool:
def sequence_like(v: Type[Any]) -> bool:
return isinstance(v, (list, tuple, set, frozenset, GeneratorType))


Expand All @@ -101,7 +101,7 @@ def validate_field_name(bases: List[Type['BaseModel']], field_name: str) -> None
)


def lenient_issubclass(cls: Any, class_or_tuple: Union[AnyType, Tuple[AnyType, ...]]) -> bool:
def lenient_issubclass(cls: Any, class_or_tuple: Union[Type[Any], Tuple[Type[Any], ...]]) -> bool:
return isinstance(cls, type) and issubclass(cls, class_or_tuple)


Expand Down
5 changes: 2 additions & 3 deletions pydantic/validators.py
Expand Up @@ -27,7 +27,6 @@
from .datetime_parse import parse_date, parse_datetime, parse_duration, parse_time
from .typing import (
AnyCallable,
AnyType,
ForwardRef,
all_literal_values,
display_as_type,
Expand Down Expand Up @@ -502,7 +501,7 @@ def check(self, config: Type['BaseConfig']) -> bool:

# order is important here, for example: bool is a subclass of int so has to come first, datetime before date same,
# IPv4Interface before IPv4Address, etc
_VALIDATORS: List[Tuple[AnyType, List[Any]]] = [
_VALIDATORS: List[Tuple[Type[Any], List[Any]]] = [
(IntEnum, [int_validator, enum_validator]),
(Enum, [enum_validator]),
(
Expand Down Expand Up @@ -547,7 +546,7 @@ def check(self, config: Type['BaseConfig']) -> bool:


def find_validators( # noqa: C901 (ignore complexity)
type_: AnyType, config: Type['BaseConfig']
type_: Type[Any], config: Type['BaseConfig']
) -> Generator[AnyCallable, None, None]:
if type_ is Any:
return
Expand Down
1 change: 1 addition & 0 deletions setup.cfg
Expand Up @@ -42,6 +42,7 @@ force_grid_wrap=0
combine_as_imports=True

[mypy]
show_error_codes = True
follow_imports = silent
strict_optional = True
warn_redundant_casts = True
Expand Down
2 changes: 1 addition & 1 deletion tests/requirements.txt
Expand Up @@ -4,7 +4,7 @@ Cython==0.29.19;sys_platform!='win32'
flake8==3.8.2
flake8-quotes==3.2.0
isort==4.3.21
mypy==0.770
mypy==0.780
pycodestyle==2.6.0
pyflakes==2.2.0
pytest==5.4.2
Expand Down

0 comments on commit 70d531f

Please sign in to comment.