pola-rs/polars · error · ValueError

cannot infer dtype from

Error message

cannot infer dtype from {original_value!r} string value

What it means

polars' database type-inference helper maps a database type-name string (e.g. "INT", "VARCHAR", "DATE") to a polars dtype. When the provided name matches none of the known mappings and `raise_unmatched=True`, the helper raises ValueError instead of returning a dtype. It indicates the database reported a column type the mapper does not recognize.

Solutions

  1. Pass `raise_unmatched=False` and handle the None return, supplying a fallback dtype yourself.
  2. Check the inferred schema and override the offending column with `schema_overrides` / `dtypes` in read_database instead of relying on inference.
  3. Normalize the type name (uppercase, strip parameters like "VARCHAR(50)") before calling, or map the custom type to a supported one beforehand.
  4. Open a polars issue to add the missing database type name to the inference table.

Example fix

// before
dtype = dtype_from_database_typename("NVARCHAR2")  # raises
// after
dtype = dtype_from_database_typename("NVARCHAR2", raise_unmatched=False)
if dtype is None:
    dtype = pl.String
Defensive patterns

Strategy: validation

Validate before calling

from polars.io.database._inference import dtype_from_database_typename
if dtype_from_database_typename(type_name, raise_unmatched=False) is None:
    dtype = pl.String  # fallback or explicit override

Type guard

def is_inferable_type(name: str) -> bool:
    return dtype_from_database_typename(name, raise_unmatched=False) is not None

Try / catch

try:
    dtype = dtype_from_database_typename(name)
except ValueError:
    dtype = pl.String  # or schema_overrides[name]

Prevention

When it happens

Trigger: Calling `dtype_from_database_typename` (directly, or via `dtype_from_cursor_description` / `_dtype_from_name`) with a type string not in the mapping table, e.g. a vendor-specific type like "NVARCHAR2", "UUID", or a custom domain type, while raise_unmatched is True (the default for cursor-description-driven inference).

Common situations: Reading from less-common databases or drivers whose column type names differ from the canonical set (Oracle, SQLite variants, custom types); upgrading a database or driver that returns new type names; calling the inference helper directly with an unnormalized name (wrong case or whitespace if the caller did not normalize).

Related errors


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

Appendix: source

Thrown at py-polars/src/polars/io/database/_inference.py:204

    # temporal dtypes
    elif value.startswith(("DATETIME", "TIMESTAMP")) and not (value.endswith("[D]")):
        if any((tz in value.replace(" ", "")) for tz in ("TZ", "TIMEZONE")):
            if "WITHOUT" not in value:
                return None  # there's a timezone, but we don't know what it is
        unit = timeunit_from_precision(modifier) if modifier else "us"
        dtype = Datetime(time_unit=(unit or "us"))  # type: ignore[arg-type]
    else:
        value = re.sub(r"\d", "", value)
        if value in ("INTERVAL", "TIMEDELTA", "DURATION"):
            dtype = Duration
        elif value == "DATE":
            dtype = Date
        elif value == "TIME":
            dtype = Time

    if not dtype and raise_unmatched:
        msg = f"cannot infer dtype from {original_value!r} string value"
        raise ValueError(msg)

    return dtype


def dtype_from_cursor_description(
    description: tuple[Any, ...],
) -> PolarsDataType | None:
    """Attempt to infer Polars dtype from database cursor description `type_code`."""
    type_code, _disp_size, internal_size, precision, scale, *_ = description
    dtype: PolarsDataType | None = None

    if isclass(type_code):
        # python types, eg: int, float, str, etc
        with suppress(TypeError):
            dtype = parse_py_type_into_dtype(type_code)  # type: ignore[arg-type]

    elif isinstance(type_code, str):
        # database/sql type names, eg: "VARCHAR", "NUMERIC", "BLOB", etc

View on GitHub (pinned to fe841f959e)