pola-rs/polars · error · AttributeError

cannot override `{cls.__name__}.{name}` with custom namespac

Error message

cannot override `{cls.__name__}.{name}` with custom namespace {ns_class.__name__!r}

What it means

AttributeError from _create_namespace (py-polars/src/polars/api.py:57-60). Even if the name is not a reserved polars namespace, registering it is refused when the target class already has an attribute of that name that is a function, a property, or starts with an underscore — i.e. you cannot shadow real methods, properties, or private internals with a custom namespace. Overriding another (non-reserved, non-method) custom namespace only warns.

Source

Thrown at py-polars/src/polars/api.py:60

        ns_instance = self._ns(instance)  # type: ignore[call-arg]
        setattr(instance, self._accessor, ns_instance)
        return ns_instance


def _create_namespace(
    name: str, cls: type[Expr | DataFrame | LazyFrame | Series]
) -> Callable[[type[NS]], type[NS]]:
    """Register custom namespace against the underlying Polars class."""

    def namespace(ns_class: type[NS]) -> type[NS]:
        if name in _reserved_namespaces:
            msg = f"cannot override reserved namespace {name!r}"
            raise AttributeError(msg)
        elif (attr := getattr(cls, name, None)) is not None:
            if isfunction(attr) or isinstance(attr, property) or name.startswith("_"):
                msg = f"cannot override `{cls.__name__}.{name}` with custom namespace {ns_class.__name__!r}"
                raise AttributeError(msg)
            warn(
                f"overriding existing custom namespace {name!r} (on {cls.__name__})",
                UserWarning,
                stacklevel=find_stacklevel(),
            )

        setattr(cls, name, NameSpace(name, ns_class))
        cls._accessors.add(name)
        return ns_class

    return namespace


def register_expr_namespace(name: str) -> Callable[[type[NS]], type[NS]]:
    """
    Decorator for registering custom functionality with a Polars Expr.

    Parameters

View on GitHub (pinned to df599052da)

Solutions

  1. Rename the namespace to something not present on the class: check hasattr(pl.DataFrame, name) is None first
  2. Namespace-qualify the feature, e.g. 'mylib_sort' or 'ops'
  3. Expose functionality as plain functions taking a frame instead of a namespace if the natural name is taken

Example fix

# before
@pl.register_dataframe_namespace('group_by')
class MyGroupBy: ...

# after
@pl.register_dataframe_namespace('mygroup')
class MyGroupBy: ...
Defensive patterns

Strategy: validation

Validate before calling

from inspect import isfunction, isproperty
import polars as pl

def safe_namespace_name(name: str, cls=pl.DataFrame) -> bool:
    attr = getattr(cls, name, None)
    if attr is None:
        return True
    return not (isfunction(attr) or isinstance(attr, property) or name.startswith('_'))

Prevention

When it happens

Trigger: @pl.register_dataframe_namespace('group_by') (method exists), @pl.register_lazyframe_namespace('collect'), @pl.register_series_namespace('_private') (underscore name), or any name matching an existing function/property on DataFrame/Expr/LazyFrame/Series.

Common situations: Extension libraries choosing names ('sort', 'join', 'width') that collide with real methods; private-namespaced internal attributes beginning with '_'.

Related errors


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