fix: collect only valid fields in mypy plugin (#3247)

* fix: collect only valid fields in mypy plugin

* Fix flake8 C901 in `PydanticModelTransformer.collect_fields`
This commit is contained in:
Hiroshi Ogawa
2021-12-09 07:33:43 +09:00
committed by GitHub
parent dc4710b56c
commit d1a014542a
4 changed files with 18 additions and 4 deletions
+1
View File
@@ -0,0 +1 @@
Fix mypy plugin to collect fields based on `pydantic.utils.is_valid_field` so that it ignores untyped private variables
+3 -1
View File
@@ -1,6 +1,8 @@
from configparser import ConfigParser
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type as TypingType, Union
from pydantic.utils import is_valid_field
try:
import toml
except ImportError: # pragma: no cover
@@ -247,7 +249,7 @@ class PydanticModelTransformer:
continue
lhs = stmt.lvalues[0]
if not isinstance(lhs, NameExpr):
if not isinstance(lhs, NameExpr) or not is_valid_field(lhs.name):
continue
if not stmt.new_syntax and self.plugin_config.warn_untyped_fields:
+13 -1
View File
@@ -1,6 +1,6 @@
from typing import ClassVar, Optional, Union
from pydantic import BaseModel, BaseSettings, Field, create_model
from pydantic import BaseModel, BaseSettings, Field, create_model, validator
from pydantic.dataclasses import dataclass
@@ -169,3 +169,15 @@ class SettingsModel(BaseSettings):
settings = SettingsModel.construct()
def f(name: str) -> str:
return name
class ModelWithAllowReuseValidator(BaseModel):
name: str
_normalize_name = validator('name', allow_reuse=True)(f)
model_with_allow_reuse_validator = ModelWithAllowReuseValidator(name='xyz')
+1 -2
View File
@@ -1,4 +1,3 @@
29: error: Unexpected keyword argument "z" for "Model" [call-arg]
64: error: Untyped fields disallowed [pydantic-field]
79: error: Argument "x" to "OverrideModel" has incompatible type "float"; expected "int" [arg-type]
125: error: Untyped fields disallowed [pydantic-field]
79: error: Argument "x" to "OverrideModel" has incompatible type "float"; expected "int" [arg-type]