pandas-stubs icon indicating copy to clipboard operation
pandas-stubs copied to clipboard

BUG: `columns` on existing `DataFrame` does not accept "List[str]"

Open bashtage opened this issue 3 years ago • 2 comments

import pandas as pd
df = pd.DataFrame({"a":[1,2,3],"b":[0.0,1,1]})

df.columns= ["c", "d"]  # mypy error, columns is `Index` so cannot take List[str}

bashtage avatar Jul 02 '22 23:07 bashtage

This is a bug in mypy: https://github.com/python/mypy/issues/3004

Here's a simple example:

from typing import Union


class Foobar:
    def __init__(self, x: Union[int, str]):
        self._x = self.makestr(x)

    def makestr(self, x: Union[int, str]) -> str:
        if isinstance(x, int):
            return str(x)
        elif isinstance(x, str):
            return x
        else:
            raise Exception("invalid type")

    @property
    def x(self) -> str:
        return self._x

    @x.setter
    def x(self, x: Union[int, str]) -> None:
        self._x = self.makestr(x)


fb = Foobar("abc")
fb.x = 3

mypy will then report:

mypyasym.py:26: error: Incompatible types in assignment (expression has type "int", variable has type "str")

Dr-Irv avatar Jul 04 '22 03:07 Dr-Irv