Files
pydantic/docs/usage/mypy.md
T
Samuel Colvin 6914410f38 Validation Decorator (#1179)
* starting validation_decorator

* correct skip_pre_38

* fix coverage and type hints

* mypy tests and move to class based decorator

* 3.6 fix, prevent duplicate github actions

* correct py 3.6 check

* better errors

* cleaner field names for args and kwargs

* add change and comments

* starting docs

* back to 3.7 for docs

* docs

* bump

* add async example and fix print indents

* allow type annotations as strings

* python 3.8 in docs
2020-02-05 17:27:12 +00:00

1.3 KiB

Pydantic models work with mypy provided you use the annotation-only version of required fields:

{!.tmp_examples/mypy_main.py!}

You can run your code through mypy with:

mypy \
  --ignore-missing-imports \
  --follow-imports=skip \
  --strict-optional \
  pydantic_mypy_test.py

If you call mypy on the example code above, you should see mypy detect the attribute access error:

13: error: "Model" has no attribute "middle_name"

Strict Optional

For your code to pass with --strict-optional, you need to to use Optional[] or an alias of Optional[] for all fields with None as the default. (This is standard with mypy.)

Pydantic provides a few useful optional or union types:

  • NoneStr aka. Optional[str]
  • NoneBytes aka. Optional[bytes]
  • StrBytes aka. Union[str, bytes]
  • NoneStrBytes aka. Optional[StrBytes]

If these aren't sufficient you can of course define your own.

Mypy Plugin

Pydantic ships with a mypy plugin that adds a number of important pydantic-specific features to mypy that improve its ability to type-check your code.

See the pydantic mypy plugin docs for more details.

Other pydantic interfaces

Pydantic dataclasses and the validate_assignment decorator should also work well with mypy.