mypy works perfectly with type hints but when I use a dataclass as return type it don't check the type
My command : python -m pipenv run mypy .
@dataclass
class HttpMessageModel:
message: str
code: int
def http_message(message: str) -> HttpMessageModel:
return {
"message": message,
"code": "200", # --> should fail since we have a int
}
full code exemple : https://github.com/TheSmartMonkey/create-python-app
CodePudding user response:
If I put your code in a single file:
from dataclasses import dataclass
@dataclass
class HttpMessageModel:
message: str
code: int
def http_message(message: str) -> HttpMessageModel:
return {
"message": message,
"code": "200", # --> should fail since we have a int
}
and run mypy
on it, I do get the expected error:
C:\test\python>mypy test.py
test.py:9: error: Incompatible return value type (got "Dict[str, str]", expected "HttpMessageModel")
The problem with checking your actual project might be in how the directory structure is set up. Take a look at https://mypy.readthedocs.io/en/latest/running_mypy.html#mapping-file-paths-to-modules and try either adding __init__.py
files at the root of your package directories or adding namespace_packages = True
to your mypy config.
Note that to return an HttpMessageModel
instead of a dict
, your function should do:
def http_message(message: str) -> HttpMessageModel:
return HttpMessageModel(message, 200)