pola-rs/polars · error · TypeError

invalid key type {type(key)}; expected str or int

Error message

invalid key type {type(key)}; expected str or int

What it means

Error "invalid key type {type(key)}; expected str or int" thrown in pola-rs/polars.

Source

Thrown at py-polars/src/polars/datatypes/classes.py:851

            raise RuntimeError(msg)

    def is_global(self) -> bool:
        """Returns whether this refers to the global categories."""
        return self._categories.is_global()

    def __getitem__(self, key: str | int | None) -> str | int | None:
        # TODO: In 2.0, this should raise KeyError instead of returning if key is a str.
        # and an IndexError should be raised if the int key is larger than self.len().
        # TODO: In 2.0, this should raise TypeError instead of returning if key is None.
        if key is None:
            return key
        elif isinstance(key, str):
            return self._categories.get_cat(key)
        elif isinstance(key, int):
            return self._categories.cat_to_str(key)
        else:
            msg = f"invalid key type {type(key)}; expected str or int"
            raise TypeError(msg)

    def __contains__(self, item: str | int) -> bool:
        if isinstance(item, str):
            return self._categories.get_cat(item) is not None
        elif isinstance(item, int):
            return self._categories.cat_to_str(item) is not None
        else:
            return False

    def __iter__(self) -> Iterator[str | None]:
        for i in range(self._categories.num_cats_upper_bound()):
            yield self._categories.cat_to_str(i)

    def to_series(self) -> Series:
        """
        Return a :class:`Series` containing all categories in this `Categories`.

        The categories are ordered by their physical category value.

View on GitHub (pinned to df599052da)

When it happens

Trigger: Thrown at py-polars/src/polars/datatypes/classes.py:851 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16). Data as JSON: /api/errors/2ab425809af5374a. Report an issue: GitHub.