0

I wrote the following class:

from typing import Any

from pydantic import BaseModel

class _UnknownFieldExceptionMixin:
    model: type[BaseModel]
    field: FieldName

    def __init__(self, model: type[BaseModel], field: FieldName, *args: Any) -> None:
        self.model = model
        self.field = field
        # super().__init__(model, field, *args)

    def __repr__(self) -> str:
        return f'{self.__class__.__name__}({self.model.__name__}, {self.field!r})'

    def __str__(self) -> str:
        return f'Unknown field {self.field!r} for model {self.model.__name__}.'


class UnknownFieldWarning(_UnknownFieldExceptionMixin, Warning):
    """An unknown model field was assigned, and will be ignored."""
    pass


class UnknownFieldError(_UnknownFieldExceptionMixin, TypeError):
    """An unknown model field was assigned."""
    pass

Note that the call to super().__init__ is commented-out in _UnknownFieldExceptionMixin.__init__.

Nevertheless, when I instantiate UnknownFieldError like so:

class Thing(BaseModel):
    x: float

exc = UnknownFieldError(Thing, 'foo')

The exc object has a .args attribute, as if Exception.__init__(*args, **kwargs) had been called:

print(exc.args)

What's going on here? Is this some hard-coded behavior for subclasses of Exception, so that you don't have to deal with super() and *args? Or am I missing something else here?

shadowtalker
  • 12,529
  • 3
  • 53
  • 96

0 Answers0