{"record":{"id":"2ab425809af5374a","repo":"pola-rs/polars","slug":"invalid-key-type-type-key-expected-str-or-int","errorCode":null,"errorMessage":"invalid key type {type(key)}; expected str or int","messagePattern":"invalid key type (.+?); expected str or int","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/datatypes/classes.py","lineNumber":855,"sourceCode":"            raise RuntimeError(msg)\n\n    def is_global(self) -> bool:\n        \"\"\"Returns whether this refers to the global categories.\"\"\"\n        return self._categories.is_global()\n\n    def __getitem__(self, key: str | int) -> str | int:\n        if isinstance(key, str):\n            if (cat := self._categories.get_cat(key)) is None:\n                raise KeyError(key)\n            return cat\n        elif isinstance(key, int):\n            if (s := self._categories.cat_to_str(key)) is None:\n                msg = f\"category index out of range: {key}\"\n                raise IndexError(msg)\n            return s\n        else:\n            msg = f\"invalid key type {type(key)}; expected str or int\"\n            raise TypeError(msg)\n\n    def __contains__(self, item: str | int) -> bool:\n        if isinstance(item, str):\n            return self._categories.get_cat(item) is not None\n        elif isinstance(item, int):\n            return self._categories.cat_to_str(item) is not None\n        else:\n            return False\n\n    def __iter__(self) -> Iterator[str | None]:\n        for i in range(self._categories.num_cats_upper_bound()):\n            yield self._categories.cat_to_str(i)\n\n    def to_series(self) -> Series:\n        \"\"\"\n        Return a :class:`Series` containing all categories in this `Categories`.\n\n        The categories are ordered by their physical category value.","sourceCodeStart":837,"sourceCodeEnd":873,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/datatypes/classes.py#L837-L873","documentation":"Categories.__getitem__ only accepts str (name lookup) or int (index lookup). Any other key type (float, slice, list, None) is rejected with a TypeError stating the invalid key type and the expected types.","triggerScenarios":"categories[1.0] (numpy int or float instead of Python int); categories[0:2] slicing; passing a list of keys expecting vectorized lookup.","commonSituations":"Indexing with numpy int64 from array computations without casting; assuming pandas-like list-based indexing is supported.","solutions":["Cast keys explicitly: categories[int(k)] or categories[str(k)]","Iterate and index one key at a time for multiple lookups","Check isinstance(key, (str, int)) before indexing"],"exampleFix":"// before\ncat = categories[np.int64(2)]\n// after\ncat = categories[int(np.int64(2))]","handlingStrategy":"type-guard","validationCode":"if not isinstance(key, (str, int)) or isinstance(key, bool):\n    raise TypeError('key must be str or int')","typeGuard":"def is_valid_key(key) -> bool:\n    return isinstance(key, (str, int)) and not isinstance(key, bool)","tryCatchPattern":"try:\n    val = categories[key]\nexcept TypeError:\n    val = categories[int(key)]  # e.g. numpy scalar","preventionTips":["Cast numpy scalars with int()/str() before indexing","Remember Categories does not support slices or list indexing","Prefer .get-style membership checks for uncertain key types"],"tags":["polars","categorical","type-error","invalid-key"],"backgroundTag":"invalid-argument-value","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}