| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import abc |
| 4 |
import sys |
| 5 |
import typing as t |
| 6 |
|
| 7 |
if sys.version_info >= (3, 11): |
| 8 |
from typing import Self |
| 9 |
else: |
| 10 |
from typing_extensions import Self |
| 11 |
|
| 12 |
# TODO: Remove this dispatch after we drop Python 3.8 support. |
| 13 |
# In 3.9+ `dict.__class_getitem__` is available. |
| 14 |
if t.TYPE_CHECKING: |
| 15 |
# pylint: disable=unsubscriptable-object |
| 16 |
_PayloadBaseDict = t.Dict[str, t.Any] |
| 17 |
else: |
| 18 |
_PayloadBaseDict = dict |
| 19 |
|
| 20 |
|
| 21 |
class GlobusPayload(_PayloadBaseDict): |
| 22 |
""" |
| 23 |
A class for defining helper objects which wrap some kind of "payload" dict. |
| 24 |
Typical for helper objects which formulate a request payload. |
| 25 |
|
| 26 |
Payload types inheriting from this class can be passed directly to the client |
| 27 |
``post()``, ``put()``, and ``patch()`` methods. These methods will |
| 28 |
recognize a ``PayloadBase`` and apply conversions for serialization with |
| 29 |
the requested encoder (e.g. as a JSON request body). |
| 30 |
""" |
| 31 |
|
| 32 |
|
| 33 |
class AbstractGlobusPayload(GlobusPayload, abc.ABC): |
| 34 |
""" |
| 35 |
An abstract class which is a GlobusPayload. |
| 36 |
|
| 37 |
This is a shim which is needed because we have a metaclass conflict between |
| 38 |
dict:type and ABC:ABCMeta. |
| 39 |
|
| 40 |
Setting the metaclass helps type checkers understand that such classes are |
| 41 |
abstract. |
| 42 |
""" |
| 43 |
|
| 44 |
# explicitly define `__new__` in order to check for abstract methods which |
| 45 |
# were not redefined |
| 46 |
def __new__(cls, *args: t.Any, **kwargs: t.Any) -> Self: |
| 47 |
obj = super().__new__(cls, *args, **kwargs) |
| 48 |
abstractmethods: frozenset[str] = ( |
| 49 |
obj.__abstractmethods__ # type: ignore[attr-defined] |
| 50 |
) |
| 51 |
if abstractmethods: |
| 52 |
s = "" if len(abstractmethods) == 1 else "s" |
| 53 |
methodnames = ", ".join(f"'{f}'" for f in abstractmethods) |
| 54 |
# this error very closely imitates the errors produced by ABCMeta |
| 55 |
raise TypeError( |
| 56 |
f"Can't instantiate abstract class {cls.__name__} without " |
| 57 |
f"an implementation for abstract method{s} {methodnames}" |
| 58 |
) |
| 59 |
return obj |