langhelpers.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218
  1. # util/langhelpers.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: allow-untyped-defs, allow-untyped-calls
  8. """Routines to help with the creation, loading and introspection of
  9. modules, classes, hierarchies, attributes, functions, and methods.
  10. """
  11. from __future__ import annotations
  12. import collections
  13. import enum
  14. from functools import update_wrapper
  15. import inspect
  16. import itertools
  17. import operator
  18. import re
  19. import sys
  20. import textwrap
  21. import threading
  22. import types
  23. from types import CodeType
  24. from typing import Any
  25. from typing import Callable
  26. from typing import cast
  27. from typing import Dict
  28. from typing import FrozenSet
  29. from typing import Generic
  30. from typing import Iterator
  31. from typing import List
  32. from typing import Mapping
  33. from typing import NoReturn
  34. from typing import Optional
  35. from typing import overload
  36. from typing import Sequence
  37. from typing import Set
  38. from typing import Tuple
  39. from typing import Type
  40. from typing import TYPE_CHECKING
  41. from typing import TypeVar
  42. from typing import Union
  43. import warnings
  44. from . import _collections
  45. from . import compat
  46. from ._has_cy import HAS_CYEXTENSION
  47. from .typing import Literal
  48. from .. import exc
  49. _T = TypeVar("_T")
  50. _T_co = TypeVar("_T_co", covariant=True)
  51. _F = TypeVar("_F", bound=Callable[..., Any])
  52. _MP = TypeVar("_MP", bound="memoized_property[Any]")
  53. _MA = TypeVar("_MA", bound="HasMemoized.memoized_attribute[Any]")
  54. _HP = TypeVar("_HP", bound="hybridproperty[Any]")
  55. _HM = TypeVar("_HM", bound="hybridmethod[Any]")
  56. if compat.py310:
  57. def get_annotations(obj: Any) -> Mapping[str, Any]:
  58. return inspect.get_annotations(obj)
  59. else:
  60. def get_annotations(obj: Any) -> Mapping[str, Any]:
  61. # it's been observed that cls.__annotations__ can be non present.
  62. # it's not clear what causes this, running under tox py37/38 it
  63. # happens, running straight pytest it doesnt
  64. # https://docs.python.org/3/howto/annotations.html#annotations-howto
  65. if isinstance(obj, type):
  66. ann = obj.__dict__.get("__annotations__", None)
  67. else:
  68. ann = getattr(obj, "__annotations__", None)
  69. if ann is None:
  70. return _collections.EMPTY_DICT
  71. else:
  72. return cast("Mapping[str, Any]", ann)
  73. def md5_hex(x: Any) -> str:
  74. x = x.encode("utf-8")
  75. m = compat.md5_not_for_security()
  76. m.update(x)
  77. return cast(str, m.hexdigest())
  78. class safe_reraise:
  79. """Reraise an exception after invoking some
  80. handler code.
  81. Stores the existing exception info before
  82. invoking so that it is maintained across a potential
  83. coroutine context switch.
  84. e.g.::
  85. try:
  86. sess.commit()
  87. except:
  88. with safe_reraise():
  89. sess.rollback()
  90. TODO: we should at some point evaluate current behaviors in this regard
  91. based on current greenlet, gevent/eventlet implementations in Python 3, and
  92. also see the degree to which our own asyncio (based on greenlet also) is
  93. impacted by this. .rollback() will cause IO / context switch to occur in
  94. all these scenarios; what happens to the exception context from an
  95. "except:" block if we don't explicitly store it? Original issue was #2703.
  96. """
  97. __slots__ = ("_exc_info",)
  98. _exc_info: Union[
  99. None,
  100. Tuple[
  101. Type[BaseException],
  102. BaseException,
  103. types.TracebackType,
  104. ],
  105. Tuple[None, None, None],
  106. ]
  107. def __enter__(self) -> None:
  108. self._exc_info = sys.exc_info()
  109. def __exit__(
  110. self,
  111. type_: Optional[Type[BaseException]],
  112. value: Optional[BaseException],
  113. traceback: Optional[types.TracebackType],
  114. ) -> NoReturn:
  115. assert self._exc_info is not None
  116. # see #2703 for notes
  117. if type_ is None:
  118. exc_type, exc_value, exc_tb = self._exc_info
  119. assert exc_value is not None
  120. self._exc_info = None # remove potential circular references
  121. raise exc_value.with_traceback(exc_tb)
  122. else:
  123. self._exc_info = None # remove potential circular references
  124. assert value is not None
  125. raise value.with_traceback(traceback)
  126. def walk_subclasses(cls: Type[_T]) -> Iterator[Type[_T]]:
  127. seen: Set[Any] = set()
  128. stack = [cls]
  129. while stack:
  130. cls = stack.pop()
  131. if cls in seen:
  132. continue
  133. else:
  134. seen.add(cls)
  135. stack.extend(cls.__subclasses__())
  136. yield cls
  137. def string_or_unprintable(element: Any) -> str:
  138. if isinstance(element, str):
  139. return element
  140. else:
  141. try:
  142. return str(element)
  143. except Exception:
  144. return "unprintable element %r" % element
  145. def clsname_as_plain_name(cls: Type[Any]) -> str:
  146. return " ".join(
  147. n.lower() for n in re.findall(r"([A-Z][a-z]+|SQL)", cls.__name__)
  148. )
  149. def method_is_overridden(
  150. instance_or_cls: Union[Type[Any], object],
  151. against_method: Callable[..., Any],
  152. ) -> bool:
  153. """Return True if the two class methods don't match."""
  154. if not isinstance(instance_or_cls, type):
  155. current_cls = instance_or_cls.__class__
  156. else:
  157. current_cls = instance_or_cls
  158. method_name = against_method.__name__
  159. current_method: types.MethodType = getattr(current_cls, method_name)
  160. return current_method != against_method
  161. def decode_slice(slc: slice) -> Tuple[Any, ...]:
  162. """decode a slice object as sent to __getitem__.
  163. takes into account the 2.5 __index__() method, basically.
  164. """
  165. ret: List[Any] = []
  166. for x in slc.start, slc.stop, slc.step:
  167. if hasattr(x, "__index__"):
  168. x = x.__index__()
  169. ret.append(x)
  170. return tuple(ret)
  171. def _unique_symbols(used: Sequence[str], *bases: str) -> Iterator[str]:
  172. used_set = set(used)
  173. for base in bases:
  174. pool = itertools.chain(
  175. (base,),
  176. map(lambda i: base + str(i), range(1000)),
  177. )
  178. for sym in pool:
  179. if sym not in used_set:
  180. used_set.add(sym)
  181. yield sym
  182. break
  183. else:
  184. raise NameError("exhausted namespace for symbol base %s" % base)
  185. def map_bits(fn: Callable[[int], Any], n: int) -> Iterator[Any]:
  186. """Call the given function given each nonzero bit from n."""
  187. while n:
  188. b = n & (~n + 1)
  189. yield fn(b)
  190. n ^= b
  191. _Fn = TypeVar("_Fn", bound="Callable[..., Any]")
  192. # this seems to be in flux in recent mypy versions
  193. def decorator(target: Callable[..., Any]) -> Callable[[_Fn], _Fn]:
  194. """A signature-matching decorator factory."""
  195. def decorate(fn: _Fn) -> _Fn:
  196. if not inspect.isfunction(fn) and not inspect.ismethod(fn):
  197. raise Exception("not a decoratable function")
  198. spec = compat.inspect_getfullargspec(fn)
  199. env: Dict[str, Any] = {}
  200. spec = _update_argspec_defaults_into_env(spec, env)
  201. names = (
  202. tuple(cast("Tuple[str, ...]", spec[0]))
  203. + cast("Tuple[str, ...]", spec[1:3])
  204. + (fn.__name__,)
  205. )
  206. targ_name, fn_name = _unique_symbols(names, "target", "fn")
  207. metadata: Dict[str, Optional[str]] = dict(target=targ_name, fn=fn_name)
  208. metadata.update(format_argspec_plus(spec, grouped=False))
  209. metadata["name"] = fn.__name__
  210. if inspect.iscoroutinefunction(fn):
  211. metadata["prefix"] = "async "
  212. metadata["target_prefix"] = "await "
  213. else:
  214. metadata["prefix"] = ""
  215. metadata["target_prefix"] = ""
  216. # look for __ positional arguments. This is a convention in
  217. # SQLAlchemy that arguments should be passed positionally
  218. # rather than as keyword
  219. # arguments. note that apply_pos doesn't currently work in all cases
  220. # such as when a kw-only indicator "*" is present, which is why
  221. # we limit the use of this to just that case we can detect. As we add
  222. # more kinds of methods that use @decorator, things may have to
  223. # be further improved in this area
  224. if "__" in repr(spec[0]):
  225. code = (
  226. """\
  227. %(prefix)sdef %(name)s%(grouped_args)s:
  228. return %(target_prefix)s%(target)s(%(fn)s, %(apply_pos)s)
  229. """
  230. % metadata
  231. )
  232. else:
  233. code = (
  234. """\
  235. %(prefix)sdef %(name)s%(grouped_args)s:
  236. return %(target_prefix)s%(target)s(%(fn)s, %(apply_kw)s)
  237. """
  238. % metadata
  239. )
  240. mod = sys.modules[fn.__module__]
  241. env.update(vars(mod))
  242. env.update({targ_name: target, fn_name: fn, "__name__": fn.__module__})
  243. decorated = cast(
  244. types.FunctionType,
  245. _exec_code_in_env(code, env, fn.__name__),
  246. )
  247. decorated.__defaults__ = getattr(fn, "__func__", fn).__defaults__
  248. decorated.__wrapped__ = fn # type: ignore
  249. return cast(_Fn, update_wrapper(decorated, fn))
  250. return update_wrapper(decorate, target)
  251. def _update_argspec_defaults_into_env(spec, env):
  252. """given a FullArgSpec, convert defaults to be symbol names in an env."""
  253. if spec.defaults:
  254. new_defaults = []
  255. i = 0
  256. for arg in spec.defaults:
  257. if type(arg).__module__ not in ("builtins", "__builtin__"):
  258. name = "x%d" % i
  259. env[name] = arg
  260. new_defaults.append(name)
  261. i += 1
  262. else:
  263. new_defaults.append(arg)
  264. elem = list(spec)
  265. elem[3] = tuple(new_defaults)
  266. return compat.FullArgSpec(*elem)
  267. else:
  268. return spec
  269. def _exec_code_in_env(
  270. code: Union[str, types.CodeType], env: Dict[str, Any], fn_name: str
  271. ) -> Callable[..., Any]:
  272. exec(code, env)
  273. return env[fn_name] # type: ignore[no-any-return]
  274. _PF = TypeVar("_PF")
  275. _TE = TypeVar("_TE")
  276. class PluginLoader:
  277. def __init__(
  278. self, group: str, auto_fn: Optional[Callable[..., Any]] = None
  279. ):
  280. self.group = group
  281. self.impls: Dict[str, Any] = {}
  282. self.auto_fn = auto_fn
  283. def clear(self):
  284. self.impls.clear()
  285. def load(self, name: str) -> Any:
  286. if name in self.impls:
  287. return self.impls[name]()
  288. if self.auto_fn:
  289. loader = self.auto_fn(name)
  290. if loader:
  291. self.impls[name] = loader
  292. return loader()
  293. for impl in compat.importlib_metadata_get(self.group):
  294. if impl.name == name:
  295. self.impls[name] = impl.load
  296. return impl.load()
  297. raise exc.NoSuchModuleError(
  298. "Can't load plugin: %s:%s" % (self.group, name)
  299. )
  300. def register(self, name: str, modulepath: str, objname: str) -> None:
  301. def load():
  302. mod = __import__(modulepath)
  303. for token in modulepath.split(".")[1:]:
  304. mod = getattr(mod, token)
  305. return getattr(mod, objname)
  306. self.impls[name] = load
  307. def _inspect_func_args(fn):
  308. try:
  309. co_varkeywords = inspect.CO_VARKEYWORDS
  310. except AttributeError:
  311. # https://docs.python.org/3/library/inspect.html
  312. # The flags are specific to CPython, and may not be defined in other
  313. # Python implementations. Furthermore, the flags are an implementation
  314. # detail, and can be removed or deprecated in future Python releases.
  315. spec = compat.inspect_getfullargspec(fn)
  316. return spec[0], bool(spec[2])
  317. else:
  318. # use fn.__code__ plus flags to reduce method call overhead
  319. co = fn.__code__
  320. nargs = co.co_argcount
  321. return (
  322. list(co.co_varnames[:nargs]),
  323. bool(co.co_flags & co_varkeywords),
  324. )
  325. @overload
  326. def get_cls_kwargs(
  327. cls: type,
  328. *,
  329. _set: Optional[Set[str]] = None,
  330. raiseerr: Literal[True] = ...,
  331. ) -> Set[str]:
  332. ...
  333. @overload
  334. def get_cls_kwargs(
  335. cls: type, *, _set: Optional[Set[str]] = None, raiseerr: bool = False
  336. ) -> Optional[Set[str]]:
  337. ...
  338. def get_cls_kwargs(
  339. cls: type, *, _set: Optional[Set[str]] = None, raiseerr: bool = False
  340. ) -> Optional[Set[str]]:
  341. r"""Return the full set of inherited kwargs for the given `cls`.
  342. Probes a class's __init__ method, collecting all named arguments. If the
  343. __init__ defines a \**kwargs catch-all, then the constructor is presumed
  344. to pass along unrecognized keywords to its base classes, and the
  345. collection process is repeated recursively on each of the bases.
  346. Uses a subset of inspect.getfullargspec() to cut down on method overhead,
  347. as this is used within the Core typing system to create copies of type
  348. objects which is a performance-sensitive operation.
  349. No anonymous tuple arguments please !
  350. """
  351. toplevel = _set is None
  352. if toplevel:
  353. _set = set()
  354. assert _set is not None
  355. ctr = cls.__dict__.get("__init__", False)
  356. has_init = (
  357. ctr
  358. and isinstance(ctr, types.FunctionType)
  359. and isinstance(ctr.__code__, types.CodeType)
  360. )
  361. if has_init:
  362. names, has_kw = _inspect_func_args(ctr)
  363. _set.update(names)
  364. if not has_kw and not toplevel:
  365. if raiseerr:
  366. raise TypeError(
  367. f"given cls {cls} doesn't have an __init__ method"
  368. )
  369. else:
  370. return None
  371. else:
  372. has_kw = False
  373. if not has_init or has_kw:
  374. for c in cls.__bases__:
  375. if get_cls_kwargs(c, _set=_set) is None:
  376. break
  377. _set.discard("self")
  378. return _set
  379. def get_func_kwargs(func: Callable[..., Any]) -> List[str]:
  380. """Return the set of legal kwargs for the given `func`.
  381. Uses getargspec so is safe to call for methods, functions,
  382. etc.
  383. """
  384. return compat.inspect_getfullargspec(func)[0]
  385. def get_callable_argspec(
  386. fn: Callable[..., Any], no_self: bool = False, _is_init: bool = False
  387. ) -> compat.FullArgSpec:
  388. """Return the argument signature for any callable.
  389. All pure-Python callables are accepted, including
  390. functions, methods, classes, objects with __call__;
  391. builtins and other edge cases like functools.partial() objects
  392. raise a TypeError.
  393. """
  394. if inspect.isbuiltin(fn):
  395. raise TypeError("Can't inspect builtin: %s" % fn)
  396. elif inspect.isfunction(fn):
  397. if _is_init and no_self:
  398. spec = compat.inspect_getfullargspec(fn)
  399. return compat.FullArgSpec(
  400. spec.args[1:],
  401. spec.varargs,
  402. spec.varkw,
  403. spec.defaults,
  404. spec.kwonlyargs,
  405. spec.kwonlydefaults,
  406. spec.annotations,
  407. )
  408. else:
  409. return compat.inspect_getfullargspec(fn)
  410. elif inspect.ismethod(fn):
  411. if no_self and (_is_init or fn.__self__):
  412. spec = compat.inspect_getfullargspec(fn.__func__)
  413. return compat.FullArgSpec(
  414. spec.args[1:],
  415. spec.varargs,
  416. spec.varkw,
  417. spec.defaults,
  418. spec.kwonlyargs,
  419. spec.kwonlydefaults,
  420. spec.annotations,
  421. )
  422. else:
  423. return compat.inspect_getfullargspec(fn.__func__)
  424. elif inspect.isclass(fn):
  425. return get_callable_argspec(
  426. fn.__init__, no_self=no_self, _is_init=True
  427. )
  428. elif hasattr(fn, "__func__"):
  429. return compat.inspect_getfullargspec(fn.__func__)
  430. elif hasattr(fn, "__call__"):
  431. if inspect.ismethod(fn.__call__):
  432. return get_callable_argspec(fn.__call__, no_self=no_self)
  433. else:
  434. raise TypeError("Can't inspect callable: %s" % fn)
  435. else:
  436. raise TypeError("Can't inspect callable: %s" % fn)
  437. def format_argspec_plus(
  438. fn: Union[Callable[..., Any], compat.FullArgSpec], grouped: bool = True
  439. ) -> Dict[str, Optional[str]]:
  440. """Returns a dictionary of formatted, introspected function arguments.
  441. A enhanced variant of inspect.formatargspec to support code generation.
  442. fn
  443. An inspectable callable or tuple of inspect getargspec() results.
  444. grouped
  445. Defaults to True; include (parens, around, argument) lists
  446. Returns:
  447. args
  448. Full inspect.formatargspec for fn
  449. self_arg
  450. The name of the first positional argument, varargs[0], or None
  451. if the function defines no positional arguments.
  452. apply_pos
  453. args, re-written in calling rather than receiving syntax. Arguments are
  454. passed positionally.
  455. apply_kw
  456. Like apply_pos, except keyword-ish args are passed as keywords.
  457. apply_pos_proxied
  458. Like apply_pos but omits the self/cls argument
  459. Example::
  460. >>> format_argspec_plus(lambda self, a, b, c=3, **d: 123)
  461. {'grouped_args': '(self, a, b, c=3, **d)',
  462. 'self_arg': 'self',
  463. 'apply_kw': '(self, a, b, c=c, **d)',
  464. 'apply_pos': '(self, a, b, c, **d)'}
  465. """
  466. if callable(fn):
  467. spec = compat.inspect_getfullargspec(fn)
  468. else:
  469. spec = fn
  470. args = compat.inspect_formatargspec(*spec)
  471. apply_pos = compat.inspect_formatargspec(
  472. spec[0], spec[1], spec[2], None, spec[4]
  473. )
  474. if spec[0]:
  475. self_arg = spec[0][0]
  476. apply_pos_proxied = compat.inspect_formatargspec(
  477. spec[0][1:], spec[1], spec[2], None, spec[4]
  478. )
  479. elif spec[1]:
  480. # I'm not sure what this is
  481. self_arg = "%s[0]" % spec[1]
  482. apply_pos_proxied = apply_pos
  483. else:
  484. self_arg = None
  485. apply_pos_proxied = apply_pos
  486. num_defaults = 0
  487. if spec[3]:
  488. num_defaults += len(cast(Tuple[Any], spec[3]))
  489. if spec[4]:
  490. num_defaults += len(spec[4])
  491. name_args = spec[0] + spec[4]
  492. defaulted_vals: Union[List[str], Tuple[()]]
  493. if num_defaults:
  494. defaulted_vals = name_args[0 - num_defaults :]
  495. else:
  496. defaulted_vals = ()
  497. apply_kw = compat.inspect_formatargspec(
  498. name_args,
  499. spec[1],
  500. spec[2],
  501. defaulted_vals,
  502. formatvalue=lambda x: "=" + str(x),
  503. )
  504. if spec[0]:
  505. apply_kw_proxied = compat.inspect_formatargspec(
  506. name_args[1:],
  507. spec[1],
  508. spec[2],
  509. defaulted_vals,
  510. formatvalue=lambda x: "=" + str(x),
  511. )
  512. else:
  513. apply_kw_proxied = apply_kw
  514. if grouped:
  515. return dict(
  516. grouped_args=args,
  517. self_arg=self_arg,
  518. apply_pos=apply_pos,
  519. apply_kw=apply_kw,
  520. apply_pos_proxied=apply_pos_proxied,
  521. apply_kw_proxied=apply_kw_proxied,
  522. )
  523. else:
  524. return dict(
  525. grouped_args=args,
  526. self_arg=self_arg,
  527. apply_pos=apply_pos[1:-1],
  528. apply_kw=apply_kw[1:-1],
  529. apply_pos_proxied=apply_pos_proxied[1:-1],
  530. apply_kw_proxied=apply_kw_proxied[1:-1],
  531. )
  532. def format_argspec_init(method, grouped=True):
  533. """format_argspec_plus with considerations for typical __init__ methods
  534. Wraps format_argspec_plus with error handling strategies for typical
  535. __init__ cases::
  536. object.__init__ -> (self)
  537. other unreflectable (usually C) -> (self, *args, **kwargs)
  538. """
  539. if method is object.__init__:
  540. grouped_args = "(self)"
  541. args = "(self)" if grouped else "self"
  542. proxied = "()" if grouped else ""
  543. else:
  544. try:
  545. return format_argspec_plus(method, grouped=grouped)
  546. except TypeError:
  547. grouped_args = "(self, *args, **kwargs)"
  548. args = grouped_args if grouped else "self, *args, **kwargs"
  549. proxied = "(*args, **kwargs)" if grouped else "*args, **kwargs"
  550. return dict(
  551. self_arg="self",
  552. grouped_args=grouped_args,
  553. apply_pos=args,
  554. apply_kw=args,
  555. apply_pos_proxied=proxied,
  556. apply_kw_proxied=proxied,
  557. )
  558. def create_proxy_methods(
  559. target_cls: Type[Any],
  560. target_cls_sphinx_name: str,
  561. proxy_cls_sphinx_name: str,
  562. classmethods: Sequence[str] = (),
  563. methods: Sequence[str] = (),
  564. attributes: Sequence[str] = (),
  565. use_intermediate_variable: Sequence[str] = (),
  566. ) -> Callable[[_T], _T]:
  567. """A class decorator indicating attributes should refer to a proxy
  568. class.
  569. This decorator is now a "marker" that does nothing at runtime. Instead,
  570. it is consumed by the tools/generate_proxy_methods.py script to
  571. statically generate proxy methods and attributes that are fully
  572. recognized by typing tools such as mypy.
  573. """
  574. def decorate(cls):
  575. return cls
  576. return decorate
  577. def getargspec_init(method):
  578. """inspect.getargspec with considerations for typical __init__ methods
  579. Wraps inspect.getargspec with error handling for typical __init__ cases::
  580. object.__init__ -> (self)
  581. other unreflectable (usually C) -> (self, *args, **kwargs)
  582. """
  583. try:
  584. return compat.inspect_getfullargspec(method)
  585. except TypeError:
  586. if method is object.__init__:
  587. return (["self"], None, None, None)
  588. else:
  589. return (["self"], "args", "kwargs", None)
  590. def unbound_method_to_callable(func_or_cls):
  591. """Adjust the incoming callable such that a 'self' argument is not
  592. required.
  593. """
  594. if isinstance(func_or_cls, types.MethodType) and not func_or_cls.__self__:
  595. return func_or_cls.__func__
  596. else:
  597. return func_or_cls
  598. def generic_repr(
  599. obj: Any,
  600. additional_kw: Sequence[Tuple[str, Any]] = (),
  601. to_inspect: Optional[Union[object, List[object]]] = None,
  602. omit_kwarg: Sequence[str] = (),
  603. ) -> str:
  604. """Produce a __repr__() based on direct association of the __init__()
  605. specification vs. same-named attributes present.
  606. """
  607. if to_inspect is None:
  608. to_inspect = [obj]
  609. else:
  610. to_inspect = _collections.to_list(to_inspect)
  611. missing = object()
  612. pos_args = []
  613. kw_args: _collections.OrderedDict[str, Any] = _collections.OrderedDict()
  614. vargs = None
  615. for i, insp in enumerate(to_inspect):
  616. try:
  617. spec = compat.inspect_getfullargspec(insp.__init__)
  618. except TypeError:
  619. continue
  620. else:
  621. default_len = len(spec.defaults) if spec.defaults else 0
  622. if i == 0:
  623. if spec.varargs:
  624. vargs = spec.varargs
  625. if default_len:
  626. pos_args.extend(spec.args[1:-default_len])
  627. else:
  628. pos_args.extend(spec.args[1:])
  629. else:
  630. kw_args.update(
  631. [(arg, missing) for arg in spec.args[1:-default_len]]
  632. )
  633. if default_len:
  634. assert spec.defaults
  635. kw_args.update(
  636. [
  637. (arg, default)
  638. for arg, default in zip(
  639. spec.args[-default_len:], spec.defaults
  640. )
  641. ]
  642. )
  643. output: List[str] = []
  644. output.extend(repr(getattr(obj, arg, None)) for arg in pos_args)
  645. if vargs is not None and hasattr(obj, vargs):
  646. output.extend([repr(val) for val in getattr(obj, vargs)])
  647. for arg, defval in kw_args.items():
  648. if arg in omit_kwarg:
  649. continue
  650. try:
  651. val = getattr(obj, arg, missing)
  652. if val is not missing and val != defval:
  653. output.append("%s=%r" % (arg, val))
  654. except Exception:
  655. pass
  656. if additional_kw:
  657. for arg, defval in additional_kw:
  658. try:
  659. val = getattr(obj, arg, missing)
  660. if val is not missing and val != defval:
  661. output.append("%s=%r" % (arg, val))
  662. except Exception:
  663. pass
  664. return "%s(%s)" % (obj.__class__.__name__, ", ".join(output))
  665. class portable_instancemethod:
  666. """Turn an instancemethod into a (parent, name) pair
  667. to produce a serializable callable.
  668. """
  669. __slots__ = "target", "name", "kwargs", "__weakref__"
  670. def __getstate__(self):
  671. return {
  672. "target": self.target,
  673. "name": self.name,
  674. "kwargs": self.kwargs,
  675. }
  676. def __setstate__(self, state):
  677. self.target = state["target"]
  678. self.name = state["name"]
  679. self.kwargs = state.get("kwargs", ())
  680. def __init__(self, meth, kwargs=()):
  681. self.target = meth.__self__
  682. self.name = meth.__name__
  683. self.kwargs = kwargs
  684. def __call__(self, *arg, **kw):
  685. kw.update(self.kwargs)
  686. return getattr(self.target, self.name)(*arg, **kw)
  687. def class_hierarchy(cls):
  688. """Return an unordered sequence of all classes related to cls.
  689. Traverses diamond hierarchies.
  690. Fibs slightly: subclasses of builtin types are not returned. Thus
  691. class_hierarchy(class A(object)) returns (A, object), not A plus every
  692. class systemwide that derives from object.
  693. """
  694. hier = {cls}
  695. process = list(cls.__mro__)
  696. while process:
  697. c = process.pop()
  698. bases = (_ for _ in c.__bases__ if _ not in hier)
  699. for b in bases:
  700. process.append(b)
  701. hier.add(b)
  702. if c.__module__ == "builtins" or not hasattr(c, "__subclasses__"):
  703. continue
  704. for s in [
  705. _
  706. for _ in (
  707. c.__subclasses__()
  708. if not issubclass(c, type)
  709. else c.__subclasses__(c)
  710. )
  711. if _ not in hier
  712. ]:
  713. process.append(s)
  714. hier.add(s)
  715. return list(hier)
  716. def iterate_attributes(cls):
  717. """iterate all the keys and attributes associated
  718. with a class, without using getattr().
  719. Does not use getattr() so that class-sensitive
  720. descriptors (i.e. property.__get__()) are not called.
  721. """
  722. keys = dir(cls)
  723. for key in keys:
  724. for c in cls.__mro__:
  725. if key in c.__dict__:
  726. yield (key, c.__dict__[key])
  727. break
  728. def monkeypatch_proxied_specials(
  729. into_cls,
  730. from_cls,
  731. skip=None,
  732. only=None,
  733. name="self.proxy",
  734. from_instance=None,
  735. ):
  736. """Automates delegation of __specials__ for a proxying type."""
  737. if only:
  738. dunders = only
  739. else:
  740. if skip is None:
  741. skip = (
  742. "__slots__",
  743. "__del__",
  744. "__getattribute__",
  745. "__metaclass__",
  746. "__getstate__",
  747. "__setstate__",
  748. )
  749. dunders = [
  750. m
  751. for m in dir(from_cls)
  752. if (
  753. m.startswith("__")
  754. and m.endswith("__")
  755. and not hasattr(into_cls, m)
  756. and m not in skip
  757. )
  758. ]
  759. for method in dunders:
  760. try:
  761. maybe_fn = getattr(from_cls, method)
  762. if not hasattr(maybe_fn, "__call__"):
  763. continue
  764. maybe_fn = getattr(maybe_fn, "__func__", maybe_fn)
  765. fn = cast(types.FunctionType, maybe_fn)
  766. except AttributeError:
  767. continue
  768. try:
  769. spec = compat.inspect_getfullargspec(fn)
  770. fn_args = compat.inspect_formatargspec(spec[0])
  771. d_args = compat.inspect_formatargspec(spec[0][1:])
  772. except TypeError:
  773. fn_args = "(self, *args, **kw)"
  774. d_args = "(*args, **kw)"
  775. py = (
  776. "def %(method)s%(fn_args)s: "
  777. "return %(name)s.%(method)s%(d_args)s" % locals()
  778. )
  779. env: Dict[str, types.FunctionType] = (
  780. from_instance is not None and {name: from_instance} or {}
  781. )
  782. exec(py, env)
  783. try:
  784. env[method].__defaults__ = fn.__defaults__
  785. except AttributeError:
  786. pass
  787. setattr(into_cls, method, env[method])
  788. def methods_equivalent(meth1, meth2):
  789. """Return True if the two methods are the same implementation."""
  790. return getattr(meth1, "__func__", meth1) is getattr(
  791. meth2, "__func__", meth2
  792. )
  793. def as_interface(obj, cls=None, methods=None, required=None):
  794. """Ensure basic interface compliance for an instance or dict of callables.
  795. Checks that ``obj`` implements public methods of ``cls`` or has members
  796. listed in ``methods``. If ``required`` is not supplied, implementing at
  797. least one interface method is sufficient. Methods present on ``obj`` that
  798. are not in the interface are ignored.
  799. If ``obj`` is a dict and ``dict`` does not meet the interface
  800. requirements, the keys of the dictionary are inspected. Keys present in
  801. ``obj`` that are not in the interface will raise TypeErrors.
  802. Raises TypeError if ``obj`` does not meet the interface criteria.
  803. In all passing cases, an object with callable members is returned. In the
  804. simple case, ``obj`` is returned as-is; if dict processing kicks in then
  805. an anonymous class is returned.
  806. obj
  807. A type, instance, or dictionary of callables.
  808. cls
  809. Optional, a type. All public methods of cls are considered the
  810. interface. An ``obj`` instance of cls will always pass, ignoring
  811. ``required``..
  812. methods
  813. Optional, a sequence of method names to consider as the interface.
  814. required
  815. Optional, a sequence of mandatory implementations. If omitted, an
  816. ``obj`` that provides at least one interface method is considered
  817. sufficient. As a convenience, required may be a type, in which case
  818. all public methods of the type are required.
  819. """
  820. if not cls and not methods:
  821. raise TypeError("a class or collection of method names are required")
  822. if isinstance(cls, type) and isinstance(obj, cls):
  823. return obj
  824. interface = set(methods or [m for m in dir(cls) if not m.startswith("_")])
  825. implemented = set(dir(obj))
  826. complies = operator.ge
  827. if isinstance(required, type):
  828. required = interface
  829. elif not required:
  830. required = set()
  831. complies = operator.gt
  832. else:
  833. required = set(required)
  834. if complies(implemented.intersection(interface), required):
  835. return obj
  836. # No dict duck typing here.
  837. if not isinstance(obj, dict):
  838. qualifier = complies is operator.gt and "any of" or "all of"
  839. raise TypeError(
  840. "%r does not implement %s: %s"
  841. % (obj, qualifier, ", ".join(interface))
  842. )
  843. class AnonymousInterface:
  844. """A callable-holding shell."""
  845. if cls:
  846. AnonymousInterface.__name__ = "Anonymous" + cls.__name__
  847. found = set()
  848. for method, impl in dictlike_iteritems(obj):
  849. if method not in interface:
  850. raise TypeError("%r: unknown in this interface" % method)
  851. if not callable(impl):
  852. raise TypeError("%r=%r is not callable" % (method, impl))
  853. setattr(AnonymousInterface, method, staticmethod(impl))
  854. found.add(method)
  855. if complies(found, required):
  856. return AnonymousInterface
  857. raise TypeError(
  858. "dictionary does not contain required keys %s"
  859. % ", ".join(required - found)
  860. )
  861. _GFD = TypeVar("_GFD", bound="generic_fn_descriptor[Any]")
  862. class generic_fn_descriptor(Generic[_T_co]):
  863. """Descriptor which proxies a function when the attribute is not
  864. present in dict
  865. This superclass is organized in a particular way with "memoized" and
  866. "non-memoized" implementation classes that are hidden from type checkers,
  867. as Mypy seems to not be able to handle seeing multiple kinds of descriptor
  868. classes used for the same attribute.
  869. """
  870. fget: Callable[..., _T_co]
  871. __doc__: Optional[str]
  872. __name__: str
  873. def __init__(self, fget: Callable[..., _T_co], doc: Optional[str] = None):
  874. self.fget = fget
  875. self.__doc__ = doc or fget.__doc__
  876. self.__name__ = fget.__name__
  877. @overload
  878. def __get__(self: _GFD, obj: None, cls: Any) -> _GFD:
  879. ...
  880. @overload
  881. def __get__(self, obj: object, cls: Any) -> _T_co:
  882. ...
  883. def __get__(self: _GFD, obj: Any, cls: Any) -> Union[_GFD, _T_co]:
  884. raise NotImplementedError()
  885. if TYPE_CHECKING:
  886. def __set__(self, instance: Any, value: Any) -> None:
  887. ...
  888. def __delete__(self, instance: Any) -> None:
  889. ...
  890. def _reset(self, obj: Any) -> None:
  891. raise NotImplementedError()
  892. @classmethod
  893. def reset(cls, obj: Any, name: str) -> None:
  894. raise NotImplementedError()
  895. class _non_memoized_property(generic_fn_descriptor[_T_co]):
  896. """a plain descriptor that proxies a function.
  897. primary rationale is to provide a plain attribute that's
  898. compatible with memoized_property which is also recognized as equivalent
  899. by mypy.
  900. """
  901. if not TYPE_CHECKING:
  902. def __get__(self, obj, cls):
  903. if obj is None:
  904. return self
  905. return self.fget(obj)
  906. class _memoized_property(generic_fn_descriptor[_T_co]):
  907. """A read-only @property that is only evaluated once."""
  908. if not TYPE_CHECKING:
  909. def __get__(self, obj, cls):
  910. if obj is None:
  911. return self
  912. obj.__dict__[self.__name__] = result = self.fget(obj)
  913. return result
  914. def _reset(self, obj):
  915. _memoized_property.reset(obj, self.__name__)
  916. @classmethod
  917. def reset(cls, obj, name):
  918. obj.__dict__.pop(name, None)
  919. # despite many attempts to get Mypy to recognize an overridden descriptor
  920. # where one is memoized and the other isn't, there seems to be no reliable
  921. # way other than completely deceiving the type checker into thinking there
  922. # is just one single descriptor type everywhere. Otherwise, if a superclass
  923. # has non-memoized and subclass has memoized, that requires
  924. # "class memoized(non_memoized)". but then if a superclass has memoized and
  925. # superclass has non-memoized, the class hierarchy of the descriptors
  926. # would need to be reversed; "class non_memoized(memoized)". so there's no
  927. # way to achieve this.
  928. # additional issues, RO properties:
  929. # https://github.com/python/mypy/issues/12440
  930. if TYPE_CHECKING:
  931. # allow memoized and non-memoized to be freely mixed by having them
  932. # be the same class
  933. memoized_property = generic_fn_descriptor
  934. non_memoized_property = generic_fn_descriptor
  935. # for read only situations, mypy only sees @property as read only.
  936. # read only is needed when a subtype specializes the return type
  937. # of a property, meaning assignment needs to be disallowed
  938. ro_memoized_property = property
  939. ro_non_memoized_property = property
  940. else:
  941. memoized_property = ro_memoized_property = _memoized_property
  942. non_memoized_property = ro_non_memoized_property = _non_memoized_property
  943. def memoized_instancemethod(fn: _F) -> _F:
  944. """Decorate a method memoize its return value.
  945. Best applied to no-arg methods: memoization is not sensitive to
  946. argument values, and will always return the same value even when
  947. called with different arguments.
  948. """
  949. def oneshot(self, *args, **kw):
  950. result = fn(self, *args, **kw)
  951. def memo(*a, **kw):
  952. return result
  953. memo.__name__ = fn.__name__
  954. memo.__doc__ = fn.__doc__
  955. self.__dict__[fn.__name__] = memo
  956. return result
  957. return update_wrapper(oneshot, fn) # type: ignore
  958. class HasMemoized:
  959. """A mixin class that maintains the names of memoized elements in a
  960. collection for easy cache clearing, generative, etc.
  961. """
  962. if not TYPE_CHECKING:
  963. # support classes that want to have __slots__ with an explicit
  964. # slot for __dict__. not sure if that requires base __slots__ here.
  965. __slots__ = ()
  966. _memoized_keys: FrozenSet[str] = frozenset()
  967. def _reset_memoizations(self) -> None:
  968. for elem in self._memoized_keys:
  969. self.__dict__.pop(elem, None)
  970. def _assert_no_memoizations(self) -> None:
  971. for elem in self._memoized_keys:
  972. assert elem not in self.__dict__
  973. def _set_memoized_attribute(self, key: str, value: Any) -> None:
  974. self.__dict__[key] = value
  975. self._memoized_keys |= {key}
  976. class memoized_attribute(memoized_property[_T]):
  977. """A read-only @property that is only evaluated once.
  978. :meta private:
  979. """
  980. fget: Callable[..., _T]
  981. __doc__: Optional[str]
  982. __name__: str
  983. def __init__(self, fget: Callable[..., _T], doc: Optional[str] = None):
  984. self.fget = fget
  985. self.__doc__ = doc or fget.__doc__
  986. self.__name__ = fget.__name__
  987. @overload
  988. def __get__(self: _MA, obj: None, cls: Any) -> _MA:
  989. ...
  990. @overload
  991. def __get__(self, obj: Any, cls: Any) -> _T:
  992. ...
  993. def __get__(self, obj, cls):
  994. if obj is None:
  995. return self
  996. obj.__dict__[self.__name__] = result = self.fget(obj)
  997. obj._memoized_keys |= {self.__name__}
  998. return result
  999. @classmethod
  1000. def memoized_instancemethod(cls, fn: _F) -> _F:
  1001. """Decorate a method memoize its return value.
  1002. :meta private:
  1003. """
  1004. def oneshot(self: Any, *args: Any, **kw: Any) -> Any:
  1005. result = fn(self, *args, **kw)
  1006. def memo(*a, **kw):
  1007. return result
  1008. memo.__name__ = fn.__name__
  1009. memo.__doc__ = fn.__doc__
  1010. self.__dict__[fn.__name__] = memo
  1011. self._memoized_keys |= {fn.__name__}
  1012. return result
  1013. return update_wrapper(oneshot, fn) # type: ignore
  1014. if TYPE_CHECKING:
  1015. HasMemoized_ro_memoized_attribute = property
  1016. else:
  1017. HasMemoized_ro_memoized_attribute = HasMemoized.memoized_attribute
  1018. class MemoizedSlots:
  1019. """Apply memoized items to an object using a __getattr__ scheme.
  1020. This allows the functionality of memoized_property and
  1021. memoized_instancemethod to be available to a class using __slots__.
  1022. """
  1023. __slots__ = ()
  1024. def _fallback_getattr(self, key):
  1025. raise AttributeError(key)
  1026. def __getattr__(self, key: str) -> Any:
  1027. if key.startswith("_memoized_attr_") or key.startswith(
  1028. "_memoized_method_"
  1029. ):
  1030. raise AttributeError(key)
  1031. # to avoid recursion errors when interacting with other __getattr__
  1032. # schemes that refer to this one, when testing for memoized method
  1033. # look at __class__ only rather than going into __getattr__ again.
  1034. elif hasattr(self.__class__, f"_memoized_attr_{key}"):
  1035. value = getattr(self, f"_memoized_attr_{key}")()
  1036. setattr(self, key, value)
  1037. return value
  1038. elif hasattr(self.__class__, f"_memoized_method_{key}"):
  1039. fn = getattr(self, f"_memoized_method_{key}")
  1040. def oneshot(*args, **kw):
  1041. result = fn(*args, **kw)
  1042. def memo(*a, **kw):
  1043. return result
  1044. memo.__name__ = fn.__name__
  1045. memo.__doc__ = fn.__doc__
  1046. setattr(self, key, memo)
  1047. return result
  1048. oneshot.__doc__ = fn.__doc__
  1049. return oneshot
  1050. else:
  1051. return self._fallback_getattr(key)
  1052. # from paste.deploy.converters
  1053. def asbool(obj: Any) -> bool:
  1054. if isinstance(obj, str):
  1055. obj = obj.strip().lower()
  1056. if obj in ["true", "yes", "on", "y", "t", "1"]:
  1057. return True
  1058. elif obj in ["false", "no", "off", "n", "f", "0"]:
  1059. return False
  1060. else:
  1061. raise ValueError("String is not true/false: %r" % obj)
  1062. return bool(obj)
  1063. def bool_or_str(*text: str) -> Callable[[str], Union[str, bool]]:
  1064. """Return a callable that will evaluate a string as
  1065. boolean, or one of a set of "alternate" string values.
  1066. """
  1067. def bool_or_value(obj: str) -> Union[str, bool]:
  1068. if obj in text:
  1069. return obj
  1070. else:
  1071. return asbool(obj)
  1072. return bool_or_value
  1073. def asint(value: Any) -> Optional[int]:
  1074. """Coerce to integer."""
  1075. if value is None:
  1076. return value
  1077. return int(value)
  1078. def coerce_kw_type(
  1079. kw: Dict[str, Any],
  1080. key: str,
  1081. type_: Type[Any],
  1082. flexi_bool: bool = True,
  1083. dest: Optional[Dict[str, Any]] = None,
  1084. ) -> None:
  1085. r"""If 'key' is present in dict 'kw', coerce its value to type 'type\_' if
  1086. necessary. If 'flexi_bool' is True, the string '0' is considered false
  1087. when coercing to boolean.
  1088. """
  1089. if dest is None:
  1090. dest = kw
  1091. if (
  1092. key in kw
  1093. and (not isinstance(type_, type) or not isinstance(kw[key], type_))
  1094. and kw[key] is not None
  1095. ):
  1096. if type_ is bool and flexi_bool:
  1097. dest[key] = asbool(kw[key])
  1098. else:
  1099. dest[key] = type_(kw[key])
  1100. def constructor_key(obj: Any, cls: Type[Any]) -> Tuple[Any, ...]:
  1101. """Produce a tuple structure that is cacheable using the __dict__ of
  1102. obj to retrieve values
  1103. """
  1104. names = get_cls_kwargs(cls)
  1105. return (cls,) + tuple(
  1106. (k, obj.__dict__[k]) for k in names if k in obj.__dict__
  1107. )
  1108. def constructor_copy(obj: _T, cls: Type[_T], *args: Any, **kw: Any) -> _T:
  1109. """Instantiate cls using the __dict__ of obj as constructor arguments.
  1110. Uses inspect to match the named arguments of ``cls``.
  1111. """
  1112. names = get_cls_kwargs(cls)
  1113. kw.update(
  1114. (k, obj.__dict__[k]) for k in names.difference(kw) if k in obj.__dict__
  1115. )
  1116. return cls(*args, **kw)
  1117. def counter() -> Callable[[], int]:
  1118. """Return a threadsafe counter function."""
  1119. lock = threading.Lock()
  1120. counter = itertools.count(1)
  1121. # avoid the 2to3 "next" transformation...
  1122. def _next():
  1123. with lock:
  1124. return next(counter)
  1125. return _next
  1126. def duck_type_collection(
  1127. specimen: Any, default: Optional[Type[Any]] = None
  1128. ) -> Optional[Type[Any]]:
  1129. """Given an instance or class, guess if it is or is acting as one of
  1130. the basic collection types: list, set and dict. If the __emulates__
  1131. property is present, return that preferentially.
  1132. """
  1133. if hasattr(specimen, "__emulates__"):
  1134. # canonicalize set vs sets.Set to a standard: the builtin set
  1135. if specimen.__emulates__ is not None and issubclass(
  1136. specimen.__emulates__, set
  1137. ):
  1138. return set
  1139. else:
  1140. return specimen.__emulates__ # type: ignore
  1141. isa = issubclass if isinstance(specimen, type) else isinstance
  1142. if isa(specimen, list):
  1143. return list
  1144. elif isa(specimen, set):
  1145. return set
  1146. elif isa(specimen, dict):
  1147. return dict
  1148. if hasattr(specimen, "append"):
  1149. return list
  1150. elif hasattr(specimen, "add"):
  1151. return set
  1152. elif hasattr(specimen, "set"):
  1153. return dict
  1154. else:
  1155. return default
  1156. def assert_arg_type(
  1157. arg: Any, argtype: Union[Tuple[Type[Any], ...], Type[Any]], name: str
  1158. ) -> Any:
  1159. if isinstance(arg, argtype):
  1160. return arg
  1161. else:
  1162. if isinstance(argtype, tuple):
  1163. raise exc.ArgumentError(
  1164. "Argument '%s' is expected to be one of type %s, got '%s'"
  1165. % (name, " or ".join("'%s'" % a for a in argtype), type(arg))
  1166. )
  1167. else:
  1168. raise exc.ArgumentError(
  1169. "Argument '%s' is expected to be of type '%s', got '%s'"
  1170. % (name, argtype, type(arg))
  1171. )
  1172. def dictlike_iteritems(dictlike):
  1173. """Return a (key, value) iterator for almost any dict-like object."""
  1174. if hasattr(dictlike, "items"):
  1175. return list(dictlike.items())
  1176. getter = getattr(dictlike, "__getitem__", getattr(dictlike, "get", None))
  1177. if getter is None:
  1178. raise TypeError("Object '%r' is not dict-like" % dictlike)
  1179. if hasattr(dictlike, "iterkeys"):
  1180. def iterator():
  1181. for key in dictlike.iterkeys():
  1182. assert getter is not None
  1183. yield key, getter(key)
  1184. return iterator()
  1185. elif hasattr(dictlike, "keys"):
  1186. return iter((key, getter(key)) for key in dictlike.keys())
  1187. else:
  1188. raise TypeError("Object '%r' is not dict-like" % dictlike)
  1189. class classproperty(property):
  1190. """A decorator that behaves like @property except that operates
  1191. on classes rather than instances.
  1192. The decorator is currently special when using the declarative
  1193. module, but note that the
  1194. :class:`~.sqlalchemy.ext.declarative.declared_attr`
  1195. decorator should be used for this purpose with declarative.
  1196. """
  1197. fget: Callable[[Any], Any]
  1198. def __init__(self, fget: Callable[[Any], Any], *arg: Any, **kw: Any):
  1199. super().__init__(fget, *arg, **kw)
  1200. self.__doc__ = fget.__doc__
  1201. def __get__(self, obj: Any, cls: Optional[type] = None) -> Any:
  1202. return self.fget(cls)
  1203. class hybridproperty(Generic[_T]):
  1204. def __init__(self, func: Callable[..., _T]):
  1205. self.func = func
  1206. self.clslevel = func
  1207. def __get__(self, instance: Any, owner: Any) -> _T:
  1208. if instance is None:
  1209. clsval = self.clslevel(owner)
  1210. return clsval
  1211. else:
  1212. return self.func(instance)
  1213. def classlevel(self, func: Callable[..., Any]) -> hybridproperty[_T]:
  1214. self.clslevel = func
  1215. return self
  1216. class rw_hybridproperty(Generic[_T]):
  1217. def __init__(self, func: Callable[..., _T]):
  1218. self.func = func
  1219. self.clslevel = func
  1220. self.setfn: Optional[Callable[..., Any]] = None
  1221. def __get__(self, instance: Any, owner: Any) -> _T:
  1222. if instance is None:
  1223. clsval = self.clslevel(owner)
  1224. return clsval
  1225. else:
  1226. return self.func(instance)
  1227. def __set__(self, instance: Any, value: Any) -> None:
  1228. assert self.setfn is not None
  1229. self.setfn(instance, value)
  1230. def setter(self, func: Callable[..., Any]) -> rw_hybridproperty[_T]:
  1231. self.setfn = func
  1232. return self
  1233. def classlevel(self, func: Callable[..., Any]) -> rw_hybridproperty[_T]:
  1234. self.clslevel = func
  1235. return self
  1236. class hybridmethod(Generic[_T]):
  1237. """Decorate a function as cls- or instance- level."""
  1238. def __init__(self, func: Callable[..., _T]):
  1239. self.func = self.__func__ = func
  1240. self.clslevel = func
  1241. def __get__(self, instance: Any, owner: Any) -> Callable[..., _T]:
  1242. if instance is None:
  1243. return self.clslevel.__get__(owner, owner.__class__) # type:ignore
  1244. else:
  1245. return self.func.__get__(instance, owner) # type:ignore
  1246. def classlevel(self, func: Callable[..., Any]) -> hybridmethod[_T]:
  1247. self.clslevel = func
  1248. return self
  1249. class symbol(int):
  1250. """A constant symbol.
  1251. >>> symbol('foo') is symbol('foo')
  1252. True
  1253. >>> symbol('foo')
  1254. <symbol 'foo>
  1255. A slight refinement of the MAGICCOOKIE=object() pattern. The primary
  1256. advantage of symbol() is its repr(). They are also singletons.
  1257. Repeated calls of symbol('name') will all return the same instance.
  1258. """
  1259. name: str
  1260. symbols: Dict[str, symbol] = {}
  1261. _lock = threading.Lock()
  1262. def __new__(
  1263. cls,
  1264. name: str,
  1265. doc: Optional[str] = None,
  1266. canonical: Optional[int] = None,
  1267. ) -> symbol:
  1268. with cls._lock:
  1269. sym = cls.symbols.get(name)
  1270. if sym is None:
  1271. assert isinstance(name, str)
  1272. if canonical is None:
  1273. canonical = hash(name)
  1274. sym = int.__new__(symbol, canonical)
  1275. sym.name = name
  1276. if doc:
  1277. sym.__doc__ = doc
  1278. # NOTE: we should ultimately get rid of this global thing,
  1279. # however, currently it is to support pickling. The best
  1280. # change would be when we are on py3.11 at a minimum, we
  1281. # switch to stdlib enum.IntFlag.
  1282. cls.symbols[name] = sym
  1283. else:
  1284. if canonical and canonical != sym:
  1285. raise TypeError(
  1286. f"Can't replace canonical symbol for {name!r} "
  1287. f"with new int value {canonical}"
  1288. )
  1289. return sym
  1290. def __reduce__(self):
  1291. return symbol, (self.name, "x", int(self))
  1292. def __str__(self):
  1293. return repr(self)
  1294. def __repr__(self):
  1295. return f"symbol({self.name!r})"
  1296. class _IntFlagMeta(type):
  1297. def __init__(
  1298. cls,
  1299. classname: str,
  1300. bases: Tuple[Type[Any], ...],
  1301. dict_: Dict[str, Any],
  1302. **kw: Any,
  1303. ) -> None:
  1304. items: List[symbol]
  1305. cls._items = items = []
  1306. for k, v in dict_.items():
  1307. if isinstance(v, int):
  1308. sym = symbol(k, canonical=v)
  1309. elif not k.startswith("_"):
  1310. raise TypeError("Expected integer values for IntFlag")
  1311. else:
  1312. continue
  1313. setattr(cls, k, sym)
  1314. items.append(sym)
  1315. cls.__members__ = _collections.immutabledict(
  1316. {sym.name: sym for sym in items}
  1317. )
  1318. def __iter__(self) -> Iterator[symbol]:
  1319. raise NotImplementedError(
  1320. "iter not implemented to ensure compatibility with "
  1321. "Python 3.11 IntFlag. Please use __members__. See "
  1322. "https://github.com/python/cpython/issues/99304"
  1323. )
  1324. class _FastIntFlag(metaclass=_IntFlagMeta):
  1325. """An 'IntFlag' copycat that isn't slow when performing bitwise
  1326. operations.
  1327. the ``FastIntFlag`` class will return ``enum.IntFlag`` under TYPE_CHECKING
  1328. and ``_FastIntFlag`` otherwise.
  1329. """
  1330. if TYPE_CHECKING:
  1331. from enum import IntFlag
  1332. FastIntFlag = IntFlag
  1333. else:
  1334. FastIntFlag = _FastIntFlag
  1335. _E = TypeVar("_E", bound=enum.Enum)
  1336. def parse_user_argument_for_enum(
  1337. arg: Any,
  1338. choices: Dict[_E, List[Any]],
  1339. name: str,
  1340. resolve_symbol_names: bool = False,
  1341. ) -> Optional[_E]:
  1342. """Given a user parameter, parse the parameter into a chosen value
  1343. from a list of choice objects, typically Enum values.
  1344. The user argument can be a string name that matches the name of a
  1345. symbol, or the symbol object itself, or any number of alternate choices
  1346. such as True/False/ None etc.
  1347. :param arg: the user argument.
  1348. :param choices: dictionary of enum values to lists of possible
  1349. entries for each.
  1350. :param name: name of the argument. Used in an :class:`.ArgumentError`
  1351. that is raised if the parameter doesn't match any available argument.
  1352. """
  1353. for enum_value, choice in choices.items():
  1354. if arg is enum_value:
  1355. return enum_value
  1356. elif resolve_symbol_names and arg == enum_value.name:
  1357. return enum_value
  1358. elif arg in choice:
  1359. return enum_value
  1360. if arg is None:
  1361. return None
  1362. raise exc.ArgumentError(f"Invalid value for '{name}': {arg!r}")
  1363. _creation_order = 1
  1364. def set_creation_order(instance: Any) -> None:
  1365. """Assign a '_creation_order' sequence to the given instance.
  1366. This allows multiple instances to be sorted in order of creation
  1367. (typically within a single thread; the counter is not particularly
  1368. threadsafe).
  1369. """
  1370. global _creation_order
  1371. instance._creation_order = _creation_order
  1372. _creation_order += 1
  1373. def warn_exception(func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
  1374. """executes the given function, catches all exceptions and converts to
  1375. a warning.
  1376. """
  1377. try:
  1378. return func(*args, **kwargs)
  1379. except Exception:
  1380. warn("%s('%s') ignored" % sys.exc_info()[0:2])
  1381. def ellipses_string(value, len_=25):
  1382. try:
  1383. if len(value) > len_:
  1384. return "%s..." % value[0:len_]
  1385. else:
  1386. return value
  1387. except TypeError:
  1388. return value
  1389. class _hash_limit_string(str):
  1390. """A string subclass that can only be hashed on a maximum amount
  1391. of unique values.
  1392. This is used for warnings so that we can send out parameterized warnings
  1393. without the __warningregistry__ of the module, or the non-overridable
  1394. "once" registry within warnings.py, overloading memory,
  1395. """
  1396. _hash: int
  1397. def __new__(
  1398. cls, value: str, num: int, args: Sequence[Any]
  1399. ) -> _hash_limit_string:
  1400. interpolated = (value % args) + (
  1401. " (this warning may be suppressed after %d occurrences)" % num
  1402. )
  1403. self = super().__new__(cls, interpolated)
  1404. self._hash = hash("%s_%d" % (value, hash(interpolated) % num))
  1405. return self
  1406. def __hash__(self) -> int:
  1407. return self._hash
  1408. def __eq__(self, other: Any) -> bool:
  1409. return hash(self) == hash(other)
  1410. def warn(msg: str, code: Optional[str] = None) -> None:
  1411. """Issue a warning.
  1412. If msg is a string, :class:`.exc.SAWarning` is used as
  1413. the category.
  1414. """
  1415. if code:
  1416. _warnings_warn(exc.SAWarning(msg, code=code))
  1417. else:
  1418. _warnings_warn(msg, exc.SAWarning)
  1419. def warn_limited(msg: str, args: Sequence[Any]) -> None:
  1420. """Issue a warning with a parameterized string, limiting the number
  1421. of registrations.
  1422. """
  1423. if args:
  1424. msg = _hash_limit_string(msg, 10, args)
  1425. _warnings_warn(msg, exc.SAWarning)
  1426. _warning_tags: Dict[CodeType, Tuple[str, Type[Warning]]] = {}
  1427. def tag_method_for_warnings(
  1428. message: str, category: Type[Warning]
  1429. ) -> Callable[[_F], _F]:
  1430. def go(fn):
  1431. _warning_tags[fn.__code__] = (message, category)
  1432. return fn
  1433. return go
  1434. _not_sa_pattern = re.compile(r"^(?:sqlalchemy\.(?!testing)|alembic\.)")
  1435. def _warnings_warn(
  1436. message: Union[str, Warning],
  1437. category: Optional[Type[Warning]] = None,
  1438. stacklevel: int = 2,
  1439. ) -> None:
  1440. # adjust the given stacklevel to be outside of SQLAlchemy
  1441. try:
  1442. frame = sys._getframe(stacklevel)
  1443. except ValueError:
  1444. # being called from less than 3 (or given) stacklevels, weird,
  1445. # but don't crash
  1446. stacklevel = 0
  1447. except:
  1448. # _getframe() doesn't work, weird interpreter issue, weird,
  1449. # ok, but don't crash
  1450. stacklevel = 0
  1451. else:
  1452. stacklevel_found = warning_tag_found = False
  1453. while frame is not None:
  1454. # using __name__ here requires that we have __name__ in the
  1455. # __globals__ of the decorated string functions we make also.
  1456. # we generate this using {"__name__": fn.__module__}
  1457. if not stacklevel_found and not re.match(
  1458. _not_sa_pattern, frame.f_globals.get("__name__", "")
  1459. ):
  1460. # stop incrementing stack level if an out-of-SQLA line
  1461. # were found.
  1462. stacklevel_found = True
  1463. # however, for the warning tag thing, we have to keep
  1464. # scanning up the whole traceback
  1465. if frame.f_code in _warning_tags:
  1466. warning_tag_found = True
  1467. (_suffix, _category) = _warning_tags[frame.f_code]
  1468. category = category or _category
  1469. message = f"{message} ({_suffix})"
  1470. frame = frame.f_back # type: ignore[assignment]
  1471. if not stacklevel_found:
  1472. stacklevel += 1
  1473. elif stacklevel_found and warning_tag_found:
  1474. break
  1475. if category is not None:
  1476. warnings.warn(message, category, stacklevel=stacklevel + 1)
  1477. else:
  1478. warnings.warn(message, stacklevel=stacklevel + 1)
  1479. def only_once(
  1480. fn: Callable[..., _T], retry_on_exception: bool
  1481. ) -> Callable[..., Optional[_T]]:
  1482. """Decorate the given function to be a no-op after it is called exactly
  1483. once."""
  1484. once = [fn]
  1485. def go(*arg: Any, **kw: Any) -> Optional[_T]:
  1486. # strong reference fn so that it isn't garbage collected,
  1487. # which interferes with the event system's expectations
  1488. strong_fn = fn # noqa
  1489. if once:
  1490. once_fn = once.pop()
  1491. try:
  1492. return once_fn(*arg, **kw)
  1493. except:
  1494. if retry_on_exception:
  1495. once.insert(0, once_fn)
  1496. raise
  1497. return None
  1498. return go
  1499. _SQLA_RE = re.compile(r"sqlalchemy/([a-z_]+/){0,2}[a-z_]+\.py")
  1500. _UNITTEST_RE = re.compile(r"unit(?:2|test2?/)")
  1501. def chop_traceback(
  1502. tb: List[str],
  1503. exclude_prefix: re.Pattern[str] = _UNITTEST_RE,
  1504. exclude_suffix: re.Pattern[str] = _SQLA_RE,
  1505. ) -> List[str]:
  1506. """Chop extraneous lines off beginning and end of a traceback.
  1507. :param tb:
  1508. a list of traceback lines as returned by ``traceback.format_stack()``
  1509. :param exclude_prefix:
  1510. a regular expression object matching lines to skip at beginning of
  1511. ``tb``
  1512. :param exclude_suffix:
  1513. a regular expression object matching lines to skip at end of ``tb``
  1514. """
  1515. start = 0
  1516. end = len(tb) - 1
  1517. while start <= end and exclude_prefix.search(tb[start]):
  1518. start += 1
  1519. while start <= end and exclude_suffix.search(tb[end]):
  1520. end -= 1
  1521. return tb[start : end + 1]
  1522. NoneType = type(None)
  1523. def attrsetter(attrname):
  1524. code = "def set(obj, value):" " obj.%s = value" % attrname
  1525. env = locals().copy()
  1526. exec(code, env)
  1527. return env["set"]
  1528. class TypingOnly:
  1529. """A mixin class that marks a class as 'typing only', meaning it has
  1530. absolutely no methods, attributes, or runtime functionality whatsoever.
  1531. """
  1532. __slots__ = ()
  1533. def __init_subclass__(cls) -> None:
  1534. if TypingOnly in cls.__bases__:
  1535. remaining = set(cls.__dict__).difference(
  1536. {
  1537. "__module__",
  1538. "__doc__",
  1539. "__slots__",
  1540. "__orig_bases__",
  1541. "__annotations__",
  1542. }
  1543. )
  1544. if remaining:
  1545. raise AssertionError(
  1546. f"Class {cls} directly inherits TypingOnly but has "
  1547. f"additional attributes {remaining}."
  1548. )
  1549. super().__init_subclass__()
  1550. class EnsureKWArg:
  1551. r"""Apply translation of functions to accept \**kw arguments if they
  1552. don't already.
  1553. Used to ensure cross-compatibility with third party legacy code, for things
  1554. like compiler visit methods that need to accept ``**kw`` arguments,
  1555. but may have been copied from old code that didn't accept them.
  1556. """
  1557. ensure_kwarg: str
  1558. """a regular expression that indicates method names for which the method
  1559. should accept ``**kw`` arguments.
  1560. The class will scan for methods matching the name template and decorate
  1561. them if necessary to ensure ``**kw`` parameters are accepted.
  1562. """
  1563. def __init_subclass__(cls) -> None:
  1564. fn_reg = cls.ensure_kwarg
  1565. clsdict = cls.__dict__
  1566. if fn_reg:
  1567. for key in clsdict:
  1568. m = re.match(fn_reg, key)
  1569. if m:
  1570. fn = clsdict[key]
  1571. spec = compat.inspect_getfullargspec(fn)
  1572. if not spec.varkw:
  1573. wrapped = cls._wrap_w_kw(fn)
  1574. setattr(cls, key, wrapped)
  1575. super().__init_subclass__()
  1576. @classmethod
  1577. def _wrap_w_kw(cls, fn: Callable[..., Any]) -> Callable[..., Any]:
  1578. def wrap(*arg: Any, **kw: Any) -> Any:
  1579. return fn(*arg)
  1580. return update_wrapper(wrap, fn)
  1581. def wrap_callable(wrapper, fn):
  1582. """Augment functools.update_wrapper() to work with objects with
  1583. a ``__call__()`` method.
  1584. :param fn:
  1585. object with __call__ method
  1586. """
  1587. if hasattr(fn, "__name__"):
  1588. return update_wrapper(wrapper, fn)
  1589. else:
  1590. _f = wrapper
  1591. _f.__name__ = fn.__class__.__name__
  1592. if hasattr(fn, "__module__"):
  1593. _f.__module__ = fn.__module__
  1594. if hasattr(fn.__call__, "__doc__") and fn.__call__.__doc__:
  1595. _f.__doc__ = fn.__call__.__doc__
  1596. elif fn.__doc__:
  1597. _f.__doc__ = fn.__doc__
  1598. return _f
  1599. def quoted_token_parser(value):
  1600. """Parse a dotted identifier with accommodation for quoted names.
  1601. Includes support for SQL-style double quotes as a literal character.
  1602. E.g.::
  1603. >>> quoted_token_parser("name")
  1604. ["name"]
  1605. >>> quoted_token_parser("schema.name")
  1606. ["schema", "name"]
  1607. >>> quoted_token_parser('"Schema"."Name"')
  1608. ['Schema', 'Name']
  1609. >>> quoted_token_parser('"Schema"."Name""Foo"')
  1610. ['Schema', 'Name""Foo']
  1611. """
  1612. if '"' not in value:
  1613. return value.split(".")
  1614. # 0 = outside of quotes
  1615. # 1 = inside of quotes
  1616. state = 0
  1617. result: List[List[str]] = [[]]
  1618. idx = 0
  1619. lv = len(value)
  1620. while idx < lv:
  1621. char = value[idx]
  1622. if char == '"':
  1623. if state == 1 and idx < lv - 1 and value[idx + 1] == '"':
  1624. result[-1].append('"')
  1625. idx += 1
  1626. else:
  1627. state ^= 1
  1628. elif char == "." and state == 0:
  1629. result.append([])
  1630. else:
  1631. result[-1].append(char)
  1632. idx += 1
  1633. return ["".join(token) for token in result]
  1634. def add_parameter_text(params: Any, text: str) -> Callable[[_F], _F]:
  1635. params = _collections.to_list(params)
  1636. def decorate(fn):
  1637. doc = fn.__doc__ is not None and fn.__doc__ or ""
  1638. if doc:
  1639. doc = inject_param_text(doc, {param: text for param in params})
  1640. fn.__doc__ = doc
  1641. return fn
  1642. return decorate
  1643. def _dedent_docstring(text: str) -> str:
  1644. split_text = text.split("\n", 1)
  1645. if len(split_text) == 1:
  1646. return text
  1647. else:
  1648. firstline, remaining = split_text
  1649. if not firstline.startswith(" "):
  1650. return firstline + "\n" + textwrap.dedent(remaining)
  1651. else:
  1652. return textwrap.dedent(text)
  1653. def inject_docstring_text(
  1654. given_doctext: Optional[str], injecttext: str, pos: int
  1655. ) -> str:
  1656. doctext: str = _dedent_docstring(given_doctext or "")
  1657. lines = doctext.split("\n")
  1658. if len(lines) == 1:
  1659. lines.append("")
  1660. injectlines = textwrap.dedent(injecttext).split("\n")
  1661. if injectlines[0]:
  1662. injectlines.insert(0, "")
  1663. blanks = [num for num, line in enumerate(lines) if not line.strip()]
  1664. blanks.insert(0, 0)
  1665. inject_pos = blanks[min(pos, len(blanks) - 1)]
  1666. lines = lines[0:inject_pos] + injectlines + lines[inject_pos:]
  1667. return "\n".join(lines)
  1668. _param_reg = re.compile(r"(\s+):param (.+?):")
  1669. def inject_param_text(doctext: str, inject_params: Dict[str, str]) -> str:
  1670. doclines = collections.deque(doctext.splitlines())
  1671. lines = []
  1672. # TODO: this is not working for params like ":param case_sensitive=True:"
  1673. to_inject = None
  1674. while doclines:
  1675. line = doclines.popleft()
  1676. m = _param_reg.match(line)
  1677. if to_inject is None:
  1678. if m:
  1679. param = m.group(2).lstrip("*")
  1680. if param in inject_params:
  1681. # default indent to that of :param: plus one
  1682. indent = " " * len(m.group(1)) + " "
  1683. # but if the next line has text, use that line's
  1684. # indentation
  1685. if doclines:
  1686. m2 = re.match(r"(\s+)\S", doclines[0])
  1687. if m2:
  1688. indent = " " * len(m2.group(1))
  1689. to_inject = indent + inject_params[param]
  1690. elif m:
  1691. lines.extend(["\n", to_inject, "\n"])
  1692. to_inject = None
  1693. elif not line.rstrip():
  1694. lines.extend([line, to_inject, "\n"])
  1695. to_inject = None
  1696. elif line.endswith("::"):
  1697. # TODO: this still won't cover if the code example itself has
  1698. # blank lines in it, need to detect those via indentation.
  1699. lines.extend([line, doclines.popleft()])
  1700. continue
  1701. lines.append(line)
  1702. return "\n".join(lines)
  1703. def repr_tuple_names(names: List[str]) -> Optional[str]:
  1704. """Trims a list of strings from the middle and return a string of up to
  1705. four elements. Strings greater than 11 characters will be truncated"""
  1706. if len(names) == 0:
  1707. return None
  1708. flag = len(names) <= 4
  1709. names = names[0:4] if flag else names[0:3] + names[-1:]
  1710. res = ["%s.." % name[:11] if len(name) > 11 else name for name in names]
  1711. if flag:
  1712. return ", ".join(res)
  1713. else:
  1714. return "%s, ..., %s" % (", ".join(res[0:3]), res[-1])
  1715. def has_compiled_ext(raise_=False):
  1716. if HAS_CYEXTENSION:
  1717. return True
  1718. elif raise_:
  1719. raise ImportError(
  1720. "cython extensions were expected to be installed, "
  1721. "but are not present"
  1722. )
  1723. else:
  1724. return False