langhelpers.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. from __future__ import annotations
  2. import collections
  3. from collections.abc import Iterable
  4. import textwrap
  5. from typing import Any
  6. from typing import Callable
  7. from typing import cast
  8. from typing import Dict
  9. from typing import List
  10. from typing import Mapping
  11. from typing import MutableMapping
  12. from typing import NoReturn
  13. from typing import Optional
  14. from typing import overload
  15. from typing import Sequence
  16. from typing import Set
  17. from typing import Tuple
  18. from typing import Type
  19. from typing import TYPE_CHECKING
  20. from typing import TypeVar
  21. from typing import Union
  22. import uuid
  23. import warnings
  24. from sqlalchemy.util import asbool as asbool # noqa: F401
  25. from sqlalchemy.util import immutabledict as immutabledict # noqa: F401
  26. from sqlalchemy.util import to_list as to_list # noqa: F401
  27. from sqlalchemy.util import unique_list as unique_list
  28. from .compat import inspect_getfullargspec
  29. if True:
  30. # zimports workaround :(
  31. from sqlalchemy.util import ( # noqa: F401
  32. memoized_property as memoized_property,
  33. )
  34. EMPTY_DICT: Mapping[Any, Any] = immutabledict()
  35. _T = TypeVar("_T", bound=Any)
  36. _C = TypeVar("_C", bound=Callable[..., Any])
  37. class _ModuleClsMeta(type):
  38. def __setattr__(cls, key: str, value: Callable[..., Any]) -> None:
  39. super().__setattr__(key, value)
  40. cls._update_module_proxies(key) # type: ignore
  41. class ModuleClsProxy(metaclass=_ModuleClsMeta):
  42. """Create module level proxy functions for the
  43. methods on a given class.
  44. The functions will have a compatible signature
  45. as the methods.
  46. """
  47. _setups: Dict[
  48. Type[Any],
  49. Tuple[
  50. Set[str],
  51. List[Tuple[MutableMapping[str, Any], MutableMapping[str, Any]]],
  52. ],
  53. ] = collections.defaultdict(lambda: (set(), []))
  54. @classmethod
  55. def _update_module_proxies(cls, name: str) -> None:
  56. attr_names, modules = cls._setups[cls]
  57. for globals_, locals_ in modules:
  58. cls._add_proxied_attribute(name, globals_, locals_, attr_names)
  59. def _install_proxy(self) -> None:
  60. attr_names, modules = self._setups[self.__class__]
  61. for globals_, locals_ in modules:
  62. globals_["_proxy"] = self
  63. for attr_name in attr_names:
  64. globals_[attr_name] = getattr(self, attr_name)
  65. def _remove_proxy(self) -> None:
  66. attr_names, modules = self._setups[self.__class__]
  67. for globals_, locals_ in modules:
  68. globals_["_proxy"] = None
  69. for attr_name in attr_names:
  70. del globals_[attr_name]
  71. @classmethod
  72. def create_module_class_proxy(
  73. cls,
  74. globals_: MutableMapping[str, Any],
  75. locals_: MutableMapping[str, Any],
  76. ) -> None:
  77. attr_names, modules = cls._setups[cls]
  78. modules.append((globals_, locals_))
  79. cls._setup_proxy(globals_, locals_, attr_names)
  80. @classmethod
  81. def _setup_proxy(
  82. cls,
  83. globals_: MutableMapping[str, Any],
  84. locals_: MutableMapping[str, Any],
  85. attr_names: Set[str],
  86. ) -> None:
  87. for methname in dir(cls):
  88. cls._add_proxied_attribute(methname, globals_, locals_, attr_names)
  89. @classmethod
  90. def _add_proxied_attribute(
  91. cls,
  92. methname: str,
  93. globals_: MutableMapping[str, Any],
  94. locals_: MutableMapping[str, Any],
  95. attr_names: Set[str],
  96. ) -> None:
  97. if not methname.startswith("_"):
  98. meth = getattr(cls, methname)
  99. if callable(meth):
  100. locals_[methname] = cls._create_method_proxy(
  101. methname, globals_, locals_
  102. )
  103. else:
  104. attr_names.add(methname)
  105. @classmethod
  106. def _create_method_proxy(
  107. cls,
  108. name: str,
  109. globals_: MutableMapping[str, Any],
  110. locals_: MutableMapping[str, Any],
  111. ) -> Callable[..., Any]:
  112. fn = getattr(cls, name)
  113. def _name_error(name: str, from_: Exception) -> NoReturn:
  114. raise NameError(
  115. "Can't invoke function '%s', as the proxy object has "
  116. "not yet been "
  117. "established for the Alembic '%s' class. "
  118. "Try placing this code inside a callable."
  119. % (name, cls.__name__)
  120. ) from from_
  121. globals_["_name_error"] = _name_error
  122. translations = getattr(fn, "_legacy_translations", [])
  123. if translations:
  124. spec = inspect_getfullargspec(fn)
  125. if spec[0] and spec[0][0] == "self":
  126. spec[0].pop(0)
  127. outer_args = inner_args = "*args, **kw"
  128. translate_str = "args, kw = _translate(%r, %r, %r, args, kw)" % (
  129. fn.__name__,
  130. tuple(spec),
  131. translations,
  132. )
  133. def translate(
  134. fn_name: str, spec: Any, translations: Any, args: Any, kw: Any
  135. ) -> Any:
  136. return_kw = {}
  137. return_args = []
  138. for oldname, newname in translations:
  139. if oldname in kw:
  140. warnings.warn(
  141. "Argument %r is now named %r "
  142. "for method %s()." % (oldname, newname, fn_name)
  143. )
  144. return_kw[newname] = kw.pop(oldname)
  145. return_kw.update(kw)
  146. args = list(args)
  147. if spec[3]:
  148. pos_only = spec[0][: -len(spec[3])]
  149. else:
  150. pos_only = spec[0]
  151. for arg in pos_only:
  152. if arg not in return_kw:
  153. try:
  154. return_args.append(args.pop(0))
  155. except IndexError:
  156. raise TypeError(
  157. "missing required positional argument: %s"
  158. % arg
  159. )
  160. return_args.extend(args)
  161. return return_args, return_kw
  162. globals_["_translate"] = translate
  163. else:
  164. outer_args = "*args, **kw"
  165. inner_args = "*args, **kw"
  166. translate_str = ""
  167. func_text = textwrap.dedent(
  168. """\
  169. def %(name)s(%(args)s):
  170. %(doc)r
  171. %(translate)s
  172. try:
  173. p = _proxy
  174. except NameError as ne:
  175. _name_error('%(name)s', ne)
  176. return _proxy.%(name)s(%(apply_kw)s)
  177. e
  178. """
  179. % {
  180. "name": name,
  181. "translate": translate_str,
  182. "args": outer_args,
  183. "apply_kw": inner_args,
  184. "doc": fn.__doc__,
  185. }
  186. )
  187. lcl: MutableMapping[str, Any] = {}
  188. exec(func_text, cast("Dict[str, Any]", globals_), lcl)
  189. return cast("Callable[..., Any]", lcl[name])
  190. def _with_legacy_names(translations: Any) -> Any:
  191. def decorate(fn: _C) -> _C:
  192. fn._legacy_translations = translations # type: ignore[attr-defined]
  193. return fn
  194. return decorate
  195. def rev_id() -> str:
  196. return uuid.uuid4().hex[-12:]
  197. @overload
  198. def to_tuple(x: Any, default: Tuple[Any, ...]) -> Tuple[Any, ...]: ...
  199. @overload
  200. def to_tuple(x: None, default: Optional[_T] = ...) -> _T: ...
  201. @overload
  202. def to_tuple(
  203. x: Any, default: Optional[Tuple[Any, ...]] = None
  204. ) -> Tuple[Any, ...]: ...
  205. def to_tuple(
  206. x: Any, default: Optional[Tuple[Any, ...]] = None
  207. ) -> Optional[Tuple[Any, ...]]:
  208. if x is None:
  209. return default
  210. elif isinstance(x, str):
  211. return (x,)
  212. elif isinstance(x, Iterable):
  213. return tuple(x)
  214. else:
  215. return (x,)
  216. def dedupe_tuple(tup: Tuple[str, ...]) -> Tuple[str, ...]:
  217. return tuple(unique_list(tup))
  218. class Dispatcher:
  219. def __init__(self, uselist: bool = False) -> None:
  220. self._registry: Dict[Tuple[Any, ...], Any] = {}
  221. self.uselist = uselist
  222. def dispatch_for(
  223. self, target: Any, qualifier: str = "default"
  224. ) -> Callable[[_C], _C]:
  225. def decorate(fn: _C) -> _C:
  226. if self.uselist:
  227. self._registry.setdefault((target, qualifier), []).append(fn)
  228. else:
  229. assert (target, qualifier) not in self._registry
  230. self._registry[(target, qualifier)] = fn
  231. return fn
  232. return decorate
  233. def dispatch(self, obj: Any, qualifier: str = "default") -> Any:
  234. if isinstance(obj, str):
  235. targets: Sequence[Any] = [obj]
  236. elif isinstance(obj, type):
  237. targets = obj.__mro__
  238. else:
  239. targets = type(obj).__mro__
  240. for spcls in targets:
  241. if qualifier != "default" and (spcls, qualifier) in self._registry:
  242. return self._fn_or_list(self._registry[(spcls, qualifier)])
  243. elif (spcls, "default") in self._registry:
  244. return self._fn_or_list(self._registry[(spcls, "default")])
  245. else:
  246. raise ValueError("no dispatch function for object: %s" % obj)
  247. def _fn_or_list(
  248. self, fn_or_list: Union[List[Callable[..., Any]], Callable[..., Any]]
  249. ) -> Callable[..., Any]:
  250. if self.uselist:
  251. def go(*arg: Any, **kw: Any) -> None:
  252. if TYPE_CHECKING:
  253. assert isinstance(fn_or_list, Sequence)
  254. for fn in fn_or_list:
  255. fn(*arg, **kw)
  256. return go
  257. else:
  258. return fn_or_list # type: ignore
  259. def branch(self) -> Dispatcher:
  260. """Return a copy of this dispatcher that is independently
  261. writable."""
  262. d = Dispatcher()
  263. if self.uselist:
  264. d._registry.update(
  265. (k, [fn for fn in self._registry[k]]) for k in self._registry
  266. )
  267. else:
  268. d._registry.update(self._registry)
  269. return d
  270. def not_none(value: Optional[_T]) -> _T:
  271. assert value is not None
  272. return value