pythonpython-3.12

Suppressing recommendations on AttributeError - Python 3.12


I like to use __getattr__ to give objects optional properties while avoiding issues with None. This is a simple example:

from typing import Any

class CelestialBody:

    def __init__(self, name: str, mass: float | None = None) -> None:

        self.name = name
        self._mass = mass

        return None

    def __getattr__(self, name: str) -> Any:

        if f"_{name}" not in self.__dict__:
            raise AttributeError(f"Attribute {name} not found")

        out = getattr(self, f"_{name}")
        if out is None:
            raise AttributeError(f"Attribute {name} not set for {self.name}")
        return out

My problem is that Python tries to be nice when I raise my custom AttributeError and exposes the "private" attribute for which I am creating the interface:

AttributeError: Attribute mass not set for Earth. Did you mean: '_mass'?

Is there a standard way to suppress these recommendations?


Solution

  • The name recommendation logic is triggered only if the name attribute of the AttributeError is not None:

    elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \
            getattr(exc_value, "name", None) is not None:
        wrong_name = getattr(exc_value, "name", None)
        suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name)
        if suggestion:
            self._str += f". Did you mean: '{suggestion}'?"
    

    So you can easily disable the suggestion by setting name to None when instantiating an AttributeError:

    if out is None:
        raise AttributeError(f"Attribute {name} not set for {self.name}", name=None)
    

    Demo here