| 1 |
""" |
| 2 |
WARNING: for internal use only. |
| 3 |
Everything in SDK private modules is meant to be internal only, but that |
| 4 |
holds for this module **in particular**. |
| 5 |
|
| 6 |
Usage: |
| 7 |
|
| 8 |
from globus_sdk._internal.classprop import classproperty |
| 9 |
|
| 10 |
class A: |
| 11 |
@classproperty |
| 12 |
def foo(self_or_cls): ... |
| 13 |
""" |
| 14 |
|
| 15 |
from __future__ import annotations |
| 16 |
|
| 17 |
import os |
| 18 |
import sys |
| 19 |
import typing as t |
| 20 |
|
| 21 |
T = t.TypeVar("T") |
| 22 |
R = t.TypeVar("R") |
| 23 |
|
| 24 |
|
| 25 |
def _in_sphinx_build() -> bool: # pragma: no cover |
| 26 |
# check if `sphinx-build` was used to invoke |
| 27 |
return os.path.basename(sys.argv[0]) in ["sphinx-build", "sphinx-build.exe"] |
| 28 |
|
| 29 |
|
| 30 |
class _classproperty(t.Generic[T, R]): |
| 31 |
""" |
| 32 |
A hybrid class/instance property descriptor. |
| 33 |
|
| 34 |
On a class, the decorated method will be invoked with `cls`. |
| 35 |
On an instance, the decorated method will be invoked with `self`. |
| 36 |
""" |
| 37 |
|
| 38 |
def __init__(self, func: t.Callable[[type[T] | T], R]) -> None: |
| 39 |
self.func = func |
| 40 |
|
| 41 |
def __get__(self, obj: T | None, cls: type[T]) -> R: |
| 42 |
# NOTE: our __get__ here prefers the object over the class when possible |
| 43 |
# although well-defined behavior for a descriptor, this contradicts the |
| 44 |
# expectation that developers may have from `classmethod` |
| 45 |
if obj is None: |
| 46 |
return self.func(cls) |
| 47 |
return self.func(obj) |
| 48 |
|
| 49 |
|
| 50 |
# if running under sphinx, define this as the stacked classmethod(property(...)) |
| 51 |
# decoration, so that proper autodoc generation happens |
| 52 |
# this is based on the python3.9 behavior which supported stacking these decorators |
| 53 |
# however, that support was pulled in 3.10 and is not going to be reintroduced at |
| 54 |
# present |
| 55 |
# therefore, this sphinx behavior may not be stable in the long term |
| 56 |
if _in_sphinx_build(): # pragma: no cover |
| 57 |
|
| 58 |
def classproperty(func: t.Callable[[T | type[T]], R]) -> _classproperty[T, R]: |
| 59 |
# type ignore this because |
| 60 |
# - it doesn't match the return type |
| 61 |
# - mypy doesn't understand classmethod(property(...)) on older pythons |
| 62 |
return classmethod(property(func)) # type: ignore |
| 63 |
|
| 64 |
else: |
| 65 |
|
| 66 |
def classproperty(func: t.Callable[[T | type[T]], R]) -> _classproperty[T, R]: |
| 67 |
return _classproperty(func) |