Skip to content

Commit

Permalink
feat: add support of StrictUnion with mypy plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
PrettyWood committed Nov 4, 2020
1 parent 44fc3f3 commit 725c35f
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
20 changes: 19 additions & 1 deletion pydantic/mypy.py
Expand Up @@ -34,7 +34,14 @@
Var,
)
from mypy.options import Options
from mypy.plugin import CheckerPluginInterface, ClassDefContext, MethodContext, Plugin, SemanticAnalyzerPluginInterface
from mypy.plugin import (
AnalyzeTypeContext,
CheckerPluginInterface,
ClassDefContext,
MethodContext,
Plugin,
SemanticAnalyzerPluginInterface,
)
from mypy.plugins import dataclasses
from mypy.semanal import set_callable_name # type: ignore
from mypy.server.trigger import make_wildcard_trigger
Expand Down Expand Up @@ -95,11 +102,22 @@ def get_class_decorator_hook(self, fullname: str) -> Optional[Callable[[ClassDef
return dataclasses.dataclass_class_maker_callback
return None

def get_type_analyze_hook(self, fullname: str) -> Optional[Callable[[AnalyzeTypeContext], Type]]:
if fullname == 'pydantic.types.StrictUnion':
return _convert_strict_union_type
return None

def _pydantic_model_class_maker_callback(self, ctx: ClassDefContext) -> None:
transformer = PydanticModelTransformer(ctx, self.plugin_config)
transformer.transform()


def _convert_strict_union_type(type_context: AnalyzeTypeContext) -> Type:
"""Convert StrictUnion[...] type to Union[...]"""
union_mypy_types: Tuple[Type, ...] = type_context.type.args # e.g. (int?, bool?, str?)
return UnionType(items=union_mypy_types, line=type_context.type.line, column=type_context.type.column)


class PydanticPluginConfig:
__slots__ = ('init_forbid_extra', 'init_typed', 'warn_required_dynamic_aliases', 'warn_untyped_fields')
init_forbid_extra: bool
Expand Down
9 changes: 8 additions & 1 deletion tests/mypy/modules/plugin_success.py
@@ -1,6 +1,6 @@
from typing import ClassVar, Optional, Union

from pydantic import BaseModel, Field
from pydantic import BaseModel, Field, StrictUnion
from pydantic.dataclasses import dataclass


Expand Down Expand Up @@ -133,3 +133,10 @@ class Model(BaseModel):


_ = NestedModel.Model


class PikaModel(BaseModel):
x: StrictUnion[int, bool, str]


pika = PikaModel(x=123)
4 changes: 3 additions & 1 deletion tests/mypy/outputs/plugin_success.txt
@@ -1,3 +1,5 @@
121: error: Unexpected keyword argument "name" for "AddProject" [call-arg]
121: error: Unexpected keyword argument "slug" for "AddProject" [call-arg]
121: error: Unexpected keyword argument "description" for "AddProject" [call-arg]
121: error: Unexpected keyword argument "description" for "AddProject" [call-arg]
139: error: Variable "pydantic.types.StrictUnion" is not valid as a type [valid-type]
139: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases

0 comments on commit 725c35f

Please sign in to comment.