pola-rs/polars · error · TypeError

expected type 'int | str', got

Error message

expected type 'int | str', got {qualified_type_name(item)!r}

What it means

Subscript type-guard on the struct namespace: indexing a Struct series is only meaningful by integer position (resolved via self.fields[item]) or by field name (resolved via self.field(item)). Any other key type reaches the final else branch and is rejected with the qualified name of the offending item.

Solutions

  1. Pass the field name as a str: s_struct["field_name"].
  2. Pass the positional index as an int: s_struct[0].
  3. Convert/coerce the key first (int(key) or str(key)) once its real type is known.

Example fix

// before
field = s_struct[1.0]  # TypeError

// after
field = s_struct[int(1.0)]  # or s_struct["field_name"]
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(key, (int, str)):
    raise TypeError(f"struct field key must be int|str, got {type(key).__name__}")

Type guard

def is_struct_key(key) -> bool:
    return isinstance(key, (int, str)) and not isinstance(key, bool)

Try / catch

try:
    field = s_struct[key]
except TypeError:
    field = s_struct[str(key)]

Prevention

When it happens

Trigger: Indexing a struct Series with e.g. s_struct[0.0], s_struct[None], a tuple, or a boolean; typing the wrong index variable in a loop over fields.

Common situations: Reusing generic dict-style access code (`s[key]`) where key came from JSON parsing as a non-str; iterating with enumerate and passing the (index, value) tuple by mistake.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/54ef6941cf580951. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/series/struct.py:44


@expr_dispatch
class StructNameSpace(_NamespaceSuggestMixin):
    """Series.struct namespace."""

    _accessor = "struct"

    def __init__(self, series: Series) -> None:
        self._s: PySeries = series._s

    def __getitem__(self, item: int | str) -> Series:
        if isinstance(item, int):
            return self.field(self.fields[item])
        elif isinstance(item, str):
            return self.field(item)
        else:
            msg = f"expected type 'int | str', got {qualified_type_name(item)!r}"
            raise TypeError(msg)

    def _ipython_key_completions_(self) -> list[str]:
        return self.fields

    @property
    def fields(self) -> list[str]:
        """
        Get the names of the fields.

        Examples
        --------
        >>> s = pl.Series([{"a": 1, "b": 2}, {"a": 3, "b": 4}])
        >>> s.struct.fields
        ['a', 'b']
        """
        if getattr(self, "_s", None) is None:
            return []
        return self._s.struct_fields()

View on GitHub (pinned to fe841f959e)