Pydantic data conversion and PyCharm's PyTypeChecker

Viewed 215

According to the documentation, "pydantic may cast input data to force it to conform to model field types [...] This is a deliberate decision of pydantic, and in general it's the most useful approach."

The following code works as expected:

>>> from pydantic import BaseModel
>>> class Foo(BaseModel):
...     bar: int

>>> foo = Foo(bar="3")     # Passing a string

And mypy doesn't complain, but PyCharm's PyTypeChecker does:

Expected type 'int', got 'str' instead

Is there any way I can keep using automatic data conversion and avoid the inspection error (other than disabling the inspection)?

Using Python 3.8.10, Pydantic 1.8.2, Mypy 0.910, PyCharm 2021.2.2 2021.2.3

1 Answers

You could use pydantic Pycharm plugin. Its step-by-step setup can be found on official page.

As a solution you can specify the types you use as parsable (or acceptable) and disable warning about them in configuration file. This disabling will only work for the types that you specified. For example, so:

# pyproject.toml

[tool.pydantic-pycharm-plugin.parsable-types]
# int field accepts to parse str
"int" = ["str"]

[tool.pydantic-pycharm-plugin]
# You can set higlith level (default is "warning")
# You can select it from "warning",  "weak_warning", "disable"
parsable-type-highlight = "disable"
acceptable-type-highlight = "disable"

By the way, this plugin is mentioned on official pydantic page.

Related