Skip to content

Commit 62f8cf6

Browse files
committed
chore: allocate the mapped ApifyApiError subclass directly in __new__
1 parent 6812d11 commit 62f8cf6

1 file changed

Lines changed: 5 additions & 5 deletions

File tree

‎src/apify_client/errors.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
from http import HTTPStatus
4-
from typing import TYPE_CHECKING, Any
4+
from typing import TYPE_CHECKING, Any, cast
55

66
from apify_client._docs import docs_group
77

@@ -41,16 +41,16 @@ class ApifyApiError(ApifyClientError):
4141

4242
def __new__(cls, response: HttpResponse, attempt: int, *, method: str = 'GET') -> Self: # noqa: ARG004
4343
"""Dispatch to the subclass matching the response's HTTP status code, if any."""
44-
instance = super().__new__(cls)
44+
target = cls
4545
if cls is ApifyApiError:
4646
status = response.status_code
4747
mapped = _STATUS_TO_CLASS.get(status)
4848
if mapped is None and status >= HTTPStatus.INTERNAL_SERVER_ERROR:
4949
mapped = ServerError
5050
if mapped is not None:
51-
# Retagging is runtime-equivalent to allocating `mapped` directly, but keeps the return type `Self`.
52-
instance.__class__ = mapped
53-
return instance
51+
# `cls` is `ApifyApiError` here, so every mapped subclass is a `type[Self]`.
52+
target = cast('type[Self]', mapped)
53+
return super().__new__(target)
5454

5555
def __init__(self, response: HttpResponse, attempt: int, *, method: str = 'GET') -> None:
5656
"""Initialize the API error from a failed response.

0 commit comments

Comments
 (0)