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/enum-like holder that must only be obtained via its static factories (e.g. `CompatLevel.oldest()`/`newest()`), which use `__new__` internally. Direct instantiation is blocked to keep the set of versions controlled.

Solutions

  1. Use the provided static constructors instead of instantiating
  2. If a specific version is needed, pass the integer version to the API that accepts it rather than constructing CompatLevel yourself

Example fix

// before
level = CompatLevel()
// after
level = CompatLevel.newest()  # or CompatLevel.oldest()
Defensive patterns

Strategy: type-guard

Validate before calling

if compat_level is None or isinstance(compat_level, type):
    compat_level = CompatLevel.newest()

Type guard

def is_compat_level(x) -> bool:
    return isinstance(x, CompatLevel)

Try / catch

try:
    level = CompatLevel()
except TypeError:
    level = CompatLevel.newest()

Prevention

When it happens

Trigger: Calling `CompatLevel()` directly; passing the class where a CompatLevel instance is expected somewhere that instantiates it.

Common situations: Trying to define a custom compatibility level; mistaking CompatLevel for a regular options class when writing serialization code.

Related errors


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

Appendix: source

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

from __future__ import annotations

from polars._utils.unstable import issue_unstable_warning

# TODO: Interchange support was removed, but for stability reasons, `CompatLevel` has
# remained here. However, we should probably move it somewhere else.


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 fe841f959e)