{"record":{"id":"cd4607a189ed4928","repo":"pola-rs/polars","slug":"can-not-get-dtype-of-categorical-anyvalue","errorCode":null,"errorMessage":"can not get dtype of Categorical AnyValue","messagePattern":"can not get dtype of Categorical AnyValue","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/polars-core/src/datatypes/any_value.rs","lineNumber":268,"sourceCode":"            Float32(_) => DataType::Float32,\n            Float64(_) => DataType::Float64,\n            String(_) | StringOwned(_) => DataType::String,\n            Binary(_) | BinaryOwned(_) => DataType::Binary,\n            #[cfg(feature = \"dtype-date\")]\n            Date(_) => DataType::Date,\n            #[cfg(feature = \"dtype-time\")]\n            Time(_) => DataType::Time,\n            #[cfg(feature = \"dtype-datetime\")]\n            Datetime(_, tu, tz) => DataType::Datetime(*tu, (*tz).cloned()),\n            #[cfg(feature = \"dtype-datetime\")]\n            DatetimeOwned(_, tu, tz) => {\n                DataType::Datetime(*tu, tz.as_ref().map(|v| v.as_ref().clone()))\n            },\n            #[cfg(feature = \"dtype-duration\")]\n            Duration(_, tu) => DataType::Duration(*tu),\n            #[cfg(feature = \"dtype-categorical\")]\n            Categorical(_, _) | CategoricalOwned(_, _) => {\n                unimplemented!(\"can not get dtype of Categorical AnyValue\")\n            },\n            #[cfg(feature = \"dtype-categorical\")]\n            Enum(_, _) | EnumOwned(_, _) => unimplemented!(\"can not get dtype of Enum AnyValue\"),\n            List(s) => DataType::List(Box::new(s.dtype().clone())),\n            #[cfg(feature = \"dtype-array\")]\n            Array(s, size) => DataType::Array(Box::new(s.dtype().clone()), *size),\n            #[cfg(feature = \"dtype-struct\")]\n            Struct(_, _, fields) => DataType::Struct(fields.to_vec()),\n            #[cfg(feature = \"dtype-struct\")]\n            StructOwned(payload) => DataType::Struct(payload.1.clone()),\n            #[cfg(feature = \"dtype-decimal\")]\n            Decimal(_, p, s) => DataType::Decimal(*p, *s),\n            #[cfg(feature = \"object\")]\n            Object(o) => DataType::Object(o.type_name()),\n            #[cfg(feature = \"object\")]\n            ObjectOwned(o) => DataType::Object(o.0.type_name()),\n        }\n    }","sourceCodeStart":250,"sourceCodeEnd":286,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/crates/polars-core/src/datatypes/any_value.rs#L250-L286","documentation":"AnyValue::dtype() panics for Categorical/CategoricalOwned scalars. A Categorical AnyValue carries only the physical category index plus a borrowed reference to the categories; constructing a full DataType::Categorical would require deciding on and cloning the categories mapping, so the conversion is deliberately unimplemented.","triggerScenarios":"Introspecting the dtype of a scalar extracted from a Categorical column: s = df[\"cat\"]; av = s.get(0); av.dtype() - or any library code path that calls AnyValue::dtype() on a value taken from a categorical/enum Series (scalar coercion, schema inference from scalars).","commonSituations":"Building schemas from sample values, generic scalar-handling utilities, or passing a single categorical value around and querying its type instead of the column's type.","solutions":["Get the dtype from the Series/Column instead of the scalar: df[\"cat\"].dtype","Extract the scalar as a string first if you only need its value: s.get(0).cast(pl.String) or str value accessors","If you truly need a per-scalar dtype, pattern-match the AnyValue and handle Categorical(_, ref_map) yourself"],"exampleFix":"# before\nav = df[\"cat\"].get(0)\ndt = av.dtype()  # panics for Categorical AnyValue\n\n# after\ndt = df[\"cat\"].dtype  # dtype from the column, never panics","handlingStrategy":"validation","validationCode":"# Ask the column, not the scalar\nif isinstance(df[\"cat\"].dtype, pl.Categorical):\n    dtype = df[\"cat\"].dtype  # safe\nelse:\n    dtype = df[\"cat\"].get(0).dtype()","typeGuard":"def scalar_dtype_safe(series: pl.Series, idx: int = 0):\n    if isinstance(series.dtype, (pl.Categorical, pl.Enum)):\n        return series.dtype  # categorical/enum scalars cannot produce dtypes\n    return series.get(idx).dtype()","tryCatchPattern":null,"preventionTips":["Always read dtypes from Series/schema; never from individual AnyValues","Cast categorical scalars to String when only the value matters"],"tags":["rust","polars","panic","unimplemented","any-value","categorical","dtype"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}