pola-rs/polars · error · TypeError

it is not allowed to create a CompatLevel object

Error message

it is not allowed to create a CompatLevel object

What it means

CompatLevel is a sentinel-style class: its __init__ unconditionally raises TypeError. Valid instances exist only as pre-created class singletons built internally via _with_version, and user code obtains them through the factory methods CompatLevel.oldest() and CompatLevel.newest(), which are accepted wherever polars APIs take a compat_level argument (e.g. serialization controls). Direct construction, or operations like copy/deepcopy/unpickling that re-run __init__, trigger this error.

Source

Thrown at py-polars/src/polars/interchange/protocol.py:262

    LITTLE = "<"
    BIG = ">"
    NATIVE = "="
    NA = "|"


class CopyNotAllowedError(RuntimeError):
    """Exception raised when a copy is required, but `allow_copy` is set to `False`."""


class CompatLevel:
    """Data structure compatibility level."""

    _version: int

    def __init__(self) -> None:
        msg = "it is not allowed to create a CompatLevel object"
        raise TypeError(msg)

    @staticmethod
    def _with_version(version: int) -> CompatLevel:
        compat_level = CompatLevel.__new__(CompatLevel)
        compat_level._version = version
        return compat_level

    @staticmethod
    def _newest() -> CompatLevel:
        return CompatLevel._future1  # type: ignore[attr-defined]

    @staticmethod
    def newest() -> CompatLevel:
        """
        Get the highest supported compatibility level.

        .. warning::
            Highest compatibility level is considered **unstable**. It may be changed

View on GitHub (pinned to df599052da)

Solutions

  1. Use the factories: pl.CompatLevel.oldest() for maximum compatibility, pl.CompatLevel.newest() for the newest level
  2. For copies or unpickling, re-fetch the singleton by version instead of reconstructing the object
  3. If you need a level that does not exist, file a feature request - custom versions are not supported

Example fix

// before
compat = pl.CompatLevel()  # TypeError: it is not allowed to create a CompatLevel object

// after
compat = pl.CompatLevel.oldest()   # or pl.CompatLevel.newest()
df.write_csv('out.csv', compat_level=compat)
Defensive patterns

Strategy: validation

Validate before calling

import polars as pl

# correct way to obtain a CompatLevel - never construct it
compat = pl.CompatLevel.oldest()   # or pl.CompatLevel.newest()

# guard before passing compat_level around
def is_compat_level(obj: object) -> bool:
    return isinstance(obj, type(pl.CompatLevel.oldest()))

Type guard

import polars as pl

def is_compat_level(value: object) -> bool:
    """True for valid, factory-produced CompatLevel singletons."""
    return isinstance(value, pl.CompatLevel)

Try / catch

try:
    compat = pl.CompatLevel()
except TypeError:
    compat = pl.CompatLevel.oldest()  # fall back to the factory method

Prevention

When it happens

Trigger: Calling pl.CompatLevel() directly; copy.copy / copy.deepcopy / pickle round-trips that reconstruct through __init__; test doubles or subclasses that instantiate CompatLevel.

Common situations: Passing compat_level options to polars serialization APIs and mistakenly constructing the object; code copied from examples of other option classes; pickling DataFrames or configs that reference a CompatLevel instance.

Related errors


AI-assisted analysis of pola-rs/polars@df599052da (2026-08-16). Data as JSON: /api/errors/73f9c6c571e63548. Report an issue: GitHub.