pola-rs/polars · error · TypeError
expected type 'int | str', got
Error message
expected type 'int | str', got {qualified_type_name(item)!r} ({item!r}) What it means
Type guard in Expr.struct.__getitem__: struct fields can be selected only by string name or integer index; any other key type (float, slice, list, etc.) raises TypeError reporting the received type and value.
Solutions
- Use a plain `str` field name or Python `int` index
- Use `.field(['a','b'])` to retrieve multiple fields
- Cast numpy ints with `int(x)` before indexing
Example fix
// before
pl.col('s').struct[np.int64(2)]
// after
pl.col('s').struct[2] Defensive patterns
Strategy: type-guard
Validate before calling
if not isinstance(item, (str, int)):
raise TypeError(f'struct[...] needs str or int, got {type(item).__name__}') Type guard
def is_struct_key(k) -> TypeGuard[str | int]:
return isinstance(k, (str, int)) and not isinstance(k, bool) Try / catch
try:
field = pl.col('s').struct[key]
except TypeError:
field = pl.col('s').struct.field(str(key)) Prevention
- Cast numpy integers to Python int before indexing
- Use .field() for multiple/named field access instead of __getitem__
When it happens
Trigger: Indexing a struct expression with a non-str/non-int key: a float index, an Expr, a list of names, or None.
Common situations: Using numpy integer types that aren't Python int; passing a slice or list where `.field([...])` should be used; accidentally indexing with a Series element.
Understand the failure class
Background: Type mismatch errors: IllegalArgumentException, TypeError and type guards across 150 open-source libraries — this error's family across 150 libraries.
Related errors
- arr.to_struct() got a str instead of a list. hint: pass
- cannot call `map_groups` when filtering groups with `having`
- cannot call `map_groups` when grouping by an expression
- cannot call `map_groups` when grouping by named expressions
- cannot set Series of dtype
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/a77dd8c95be97b30.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/expr/struct.py:75
>>> df.select(pl.col("s").struct[0])
shape: (2, 1)
┌─────┐
│ x │
│ --- │
│ i64 │
╞═════╡
│ 1 │
│ 2 │
└─────┘
"""
if isinstance(item, str):
return self.field(item)
elif isinstance(item, int):
return wrap_expr(self._pyexpr.struct_field_by_index(item))
else:
msg = f"expected type 'int | str', got {qualified_type_name(item)!r} ({item!r})"
raise TypeError(msg)
def field(self, name: str | list[str], *more_names: str) -> Expr:
"""
Retrieve one or multiple `Struct` field(s) as a new Series.
.. engine-support:: in-memory, streaming, distributed
Parameters
----------
name
Name of the struct field to retrieve.
*more_names
Additional struct field names.
Examples
--------
>>> df = pl.DataFrame(
... {View on GitHub (pinned to fe841f959e)