Skip to content

errors with type narrowing #516

@jasonboh

Description

@jasonboh

Hi, I am having problems understanding what I am seeing here in the below example.

Why can't mypy figure out that after the else statement, we definitely have a DataFrame?

from typing import Union

import pandas as pd

x: Union[pd.Series, pd.DataFrame, pd.Index] = pd.Series([1, 2, 3])
if isinstance(x, (pd.Series, pd.Index)):
    reveal_type(x)  # Revealed type is "Union[pandas.core.series.TimestampSeries, pandas.core.indexes.numeric.NumericIndex]"
    dtype = x.dtype
    reveal_type(dtype)  # Revealed type is "Union[numpy.dtype[numpy.generic], pandas.core.dtypes.base.ExtensionDtype]"
else:  # a DataFrame
    reveal_type(x)  # Revealed type is "Union[pandas.core.series.Series[Any], pandas.core.frame.DataFrame, pandas.core.indexes.base.Index]"
    dtypes = x.dtypes  # yields error: Item "Index" of "Union[Series[Any], DataFrame, Index]" has no attribute "dtypes"  [union-attr] 
    reveal_type(dtypes)  # "Union[numpy.dtype[numpy.generic], pandas.core.dtypes.base.ExtensionDtype, pandas.core.series.Series[Any], Any]"
    dtypes_set = set(x.dtypes) # yield 2 errors: 
    # first error Item "Index" of "Union[Series[Any], DataFrame, Index]" has no attribute "dtypes"  [union-attr]
    # second error: Argument 1 to "set" has incompatible type "Union[dtype[generic], ExtensionDtype, Series[Any], Any]"; expected "Iterable[Any]"  [arg-type]

Metadata

Metadata

Assignees

No one assigned

    Labels

    mypy bugRequires mypy to fix a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions