Python Typing - Why can I assign an Optional Pandas DataFrame to a Non-Optional Pandas DataFrame

Viewed 202

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.

1 Answers

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.

Related