2

Why does the following code not raise a mypy error?

from typing import Optional

import pandas as pd

data = {'col1': [1, 2], 'col2': [3, 4]}
optional_df: Optional[pd.DataFrame] = pd.DataFrame(data=data)
df: pd.DataFrame = optional_df 

In the same file I have this block of code:

optional_string: Optional[str] = "baz"
string: str = optional_string

Error:

foo.py:11: error: Incompatible types in assignment (expression has type "Optional[str]", variable has type "str")
Found 1 error in 1 file (checked 109 source files)

I am launching mypy like this:

mypy --config-file ../quality_checks/mypy.ini .

And my config file looks like this:

[mypy]
python_version = 3.7
strict = True

[mypy-pandas]
ignore_missing_imports = True

I assume that the ignore_missing_imports is probably the issue here, but I am not sure if that is true or why it is true.

sixtyfootersdude
  • 25,859
  • 43
  • 145
  • 213
  • You are right that `ignore_missing_imports` is the issue, because then `pd.DataFrame` is treated as `Any`. If you change `str` to `Any` in your last example (so `optional_string: Optional[Any] = "baz"; string: Any = optional_string`), this also results in no error. – Mario Ishac May 05 '21 at 22:41
  • And because `Any` allows `None` (so `Any == Optional[Any]`), that assignment is valid. See this related question: https://stackoverflow.com/questions/64689030/mypy-annotation-for-any-type-but-none. – Mario Ishac May 05 '21 at 22:42

1 Answers1

1

pandas doesn't (yet, though this will likely change before too long) expose type hints - if you run

import pandas as pd

df: pd.DataFrame
reveal_type(df)

then you should see that it's revelead as Any, meaning that it won't be type-checked.

ignoring_gravity
  • 6,677
  • 4
  • 32
  • 65