mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
0c18619769
* Add mypy plugin * Make all arguments optional for BaseSettings * Get test coverage up * Add changes * Add type-checking for BaseModel.construct, and checking for from_orm * Fix formatting and linting * Fix the build * Heavy refactor of plugin and mypy tests * Make linting pass * Handle dynamic aliases * Better organize plugin code * Add docs * Add support for error codes * Fix minor docs typo * Rename config settings, add docstrings, and incorporate other feedback * Incorporate feedback * Update docs, remove dataclasses for cython * fix mypy example
1.2 KiB
1.2 KiB
Pydantic works with mypy provided you use the annotation-only version of required fields:
{!.tmp_examples/mypy_example.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:
NoneStraka.Optional[str]NoneBytesaka.Optional[bytes]StrBytesaka.Union[str, bytes]NoneStrBytesaka.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.