langhelpers.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  1. # util/langhelpers.py
  2. # Copyright (C) 2005-2017 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: http://www.opensource.org/licenses/mit-license.php
  7. """Routines to help with the creation, loading and introspection of
  8. modules, classes, hierarchies, attributes, functions, and methods.
  9. """
  10. import itertools
  11. import inspect
  12. import operator
  13. import re
  14. import sys
  15. import types
  16. import warnings
  17. from functools import update_wrapper
  18. from .. import exc
  19. import hashlib
  20. from . import compat
  21. from . import _collections
  22. def md5_hex(x):
  23. if compat.py3k:
  24. x = x.encode('utf-8')
  25. m = hashlib.md5()
  26. m.update(x)
  27. return m.hexdigest()
  28. class safe_reraise(object):
  29. """Reraise an exception after invoking some
  30. handler code.
  31. Stores the existing exception info before
  32. invoking so that it is maintained across a potential
  33. coroutine context switch.
  34. e.g.::
  35. try:
  36. sess.commit()
  37. except:
  38. with safe_reraise():
  39. sess.rollback()
  40. """
  41. __slots__ = ('warn_only', '_exc_info')
  42. def __init__(self, warn_only=False):
  43. self.warn_only = warn_only
  44. def __enter__(self):
  45. self._exc_info = sys.exc_info()
  46. def __exit__(self, type_, value, traceback):
  47. # see #2703 for notes
  48. if type_ is None:
  49. exc_type, exc_value, exc_tb = self._exc_info
  50. self._exc_info = None # remove potential circular references
  51. if not self.warn_only:
  52. compat.reraise(exc_type, exc_value, exc_tb)
  53. else:
  54. if not compat.py3k and self._exc_info and self._exc_info[1]:
  55. # emulate Py3K's behavior of telling us when an exception
  56. # occurs in an exception handler.
  57. warn(
  58. "An exception has occurred during handling of a "
  59. "previous exception. The previous exception "
  60. "is:\n %s %s\n" % (self._exc_info[0], self._exc_info[1]))
  61. self._exc_info = None # remove potential circular references
  62. compat.reraise(type_, value, traceback)
  63. def decode_slice(slc):
  64. """decode a slice object as sent to __getitem__.
  65. takes into account the 2.5 __index__() method, basically.
  66. """
  67. ret = []
  68. for x in slc.start, slc.stop, slc.step:
  69. if hasattr(x, '__index__'):
  70. x = x.__index__()
  71. ret.append(x)
  72. return tuple(ret)
  73. def _unique_symbols(used, *bases):
  74. used = set(used)
  75. for base in bases:
  76. pool = itertools.chain((base,),
  77. compat.itertools_imap(lambda i: base + str(i),
  78. range(1000)))
  79. for sym in pool:
  80. if sym not in used:
  81. used.add(sym)
  82. yield sym
  83. break
  84. else:
  85. raise NameError("exhausted namespace for symbol base %s" % base)
  86. def map_bits(fn, n):
  87. """Call the given function given each nonzero bit from n."""
  88. while n:
  89. b = n & (~n + 1)
  90. yield fn(b)
  91. n ^= b
  92. def decorator(target):
  93. """A signature-matching decorator factory."""
  94. def decorate(fn):
  95. if not inspect.isfunction(fn):
  96. raise Exception("not a decoratable function")
  97. spec = compat.inspect_getfullargspec(fn)
  98. names = tuple(spec[0]) + spec[1:3] + (fn.__name__,)
  99. targ_name, fn_name = _unique_symbols(names, 'target', 'fn')
  100. metadata = dict(target=targ_name, fn=fn_name)
  101. metadata.update(format_argspec_plus(spec, grouped=False))
  102. metadata['name'] = fn.__name__
  103. code = """\
  104. def %(name)s(%(args)s):
  105. return %(target)s(%(fn)s, %(apply_kw)s)
  106. """ % metadata
  107. decorated = _exec_code_in_env(code,
  108. {targ_name: target, fn_name: fn},
  109. fn.__name__)
  110. decorated.__defaults__ = getattr(fn, 'im_func', fn).__defaults__
  111. decorated.__wrapped__ = fn
  112. return update_wrapper(decorated, fn)
  113. return update_wrapper(decorate, target)
  114. def _exec_code_in_env(code, env, fn_name):
  115. exec(code, env)
  116. return env[fn_name]
  117. def public_factory(target, location):
  118. """Produce a wrapping function for the given cls or classmethod.
  119. Rationale here is so that the __init__ method of the
  120. class can serve as documentation for the function.
  121. """
  122. if isinstance(target, type):
  123. fn = target.__init__
  124. callable_ = target
  125. doc = "Construct a new :class:`.%s` object. \n\n"\
  126. "This constructor is mirrored as a public API function; "\
  127. "see :func:`~%s` "\
  128. "for a full usage and argument description." % (
  129. target.__name__, location, )
  130. else:
  131. fn = callable_ = target
  132. doc = "This function is mirrored; see :func:`~%s` "\
  133. "for a description of arguments." % location
  134. location_name = location.split(".")[-1]
  135. spec = compat.inspect_getfullargspec(fn)
  136. del spec[0][0]
  137. metadata = format_argspec_plus(spec, grouped=False)
  138. metadata['name'] = location_name
  139. code = """\
  140. def %(name)s(%(args)s):
  141. return cls(%(apply_kw)s)
  142. """ % metadata
  143. env = {'cls': callable_, 'symbol': symbol}
  144. exec(code, env)
  145. decorated = env[location_name]
  146. decorated.__doc__ = fn.__doc__
  147. decorated.__module__ = "sqlalchemy" + location.rsplit(".", 1)[0]
  148. if compat.py2k or hasattr(fn, '__func__'):
  149. fn.__func__.__doc__ = doc
  150. else:
  151. fn.__doc__ = doc
  152. return decorated
  153. class PluginLoader(object):
  154. def __init__(self, group, auto_fn=None):
  155. self.group = group
  156. self.impls = {}
  157. self.auto_fn = auto_fn
  158. def load(self, name):
  159. if name in self.impls:
  160. return self.impls[name]()
  161. if self.auto_fn:
  162. loader = self.auto_fn(name)
  163. if loader:
  164. self.impls[name] = loader
  165. return loader()
  166. try:
  167. import pkg_resources
  168. except ImportError:
  169. pass
  170. else:
  171. for impl in pkg_resources.iter_entry_points(
  172. self.group, name):
  173. self.impls[name] = impl.load
  174. return impl.load()
  175. raise exc.NoSuchModuleError(
  176. "Can't load plugin: %s:%s" %
  177. (self.group, name))
  178. def register(self, name, modulepath, objname):
  179. def load():
  180. mod = compat.import_(modulepath)
  181. for token in modulepath.split(".")[1:]:
  182. mod = getattr(mod, token)
  183. return getattr(mod, objname)
  184. self.impls[name] = load
  185. def get_cls_kwargs(cls, _set=None):
  186. r"""Return the full set of inherited kwargs for the given `cls`.
  187. Probes a class's __init__ method, collecting all named arguments. If the
  188. __init__ defines a \**kwargs catch-all, then the constructor is presumed
  189. to pass along unrecognized keywords to its base classes, and the
  190. collection process is repeated recursively on each of the bases.
  191. Uses a subset of inspect.getargspec() to cut down on method overhead.
  192. No anonymous tuple arguments please !
  193. """
  194. toplevel = _set is None
  195. if toplevel:
  196. _set = set()
  197. ctr = cls.__dict__.get('__init__', False)
  198. has_init = ctr and isinstance(ctr, types.FunctionType) and \
  199. isinstance(ctr.__code__, types.CodeType)
  200. if has_init:
  201. names, has_kw = inspect_func_args(ctr)
  202. _set.update(names)
  203. if not has_kw and not toplevel:
  204. return None
  205. if not has_init or has_kw:
  206. for c in cls.__bases__:
  207. if get_cls_kwargs(c, _set) is None:
  208. break
  209. _set.discard('self')
  210. return _set
  211. try:
  212. # TODO: who doesn't have this constant?
  213. from inspect import CO_VARKEYWORDS
  214. def inspect_func_args(fn):
  215. co = fn.__code__
  216. nargs = co.co_argcount
  217. names = co.co_varnames
  218. args = list(names[:nargs])
  219. has_kw = bool(co.co_flags & CO_VARKEYWORDS)
  220. return args, has_kw
  221. except ImportError:
  222. def inspect_func_args(fn):
  223. names, _, has_kw, _ = inspect.getargspec(fn)
  224. return names, bool(has_kw)
  225. def get_func_kwargs(func):
  226. """Return the set of legal kwargs for the given `func`.
  227. Uses getargspec so is safe to call for methods, functions,
  228. etc.
  229. """
  230. return compat.inspect_getargspec(func)[0]
  231. def get_callable_argspec(fn, no_self=False, _is_init=False):
  232. """Return the argument signature for any callable.
  233. All pure-Python callables are accepted, including
  234. functions, methods, classes, objects with __call__;
  235. builtins and other edge cases like functools.partial() objects
  236. raise a TypeError.
  237. """
  238. if inspect.isbuiltin(fn):
  239. raise TypeError("Can't inspect builtin: %s" % fn)
  240. elif inspect.isfunction(fn):
  241. if _is_init and no_self:
  242. spec = compat.inspect_getargspec(fn)
  243. return compat.ArgSpec(spec.args[1:], spec.varargs,
  244. spec.keywords, spec.defaults)
  245. else:
  246. return compat.inspect_getargspec(fn)
  247. elif inspect.ismethod(fn):
  248. if no_self and (_is_init or fn.__self__):
  249. spec = compat.inspect_getargspec(fn.__func__)
  250. return compat.ArgSpec(spec.args[1:], spec.varargs,
  251. spec.keywords, spec.defaults)
  252. else:
  253. return compat.inspect_getargspec(fn.__func__)
  254. elif inspect.isclass(fn):
  255. return get_callable_argspec(
  256. fn.__init__, no_self=no_self, _is_init=True)
  257. elif hasattr(fn, '__func__'):
  258. return compat.inspect_getargspec(fn.__func__)
  259. elif hasattr(fn, '__call__'):
  260. if inspect.ismethod(fn.__call__):
  261. return get_callable_argspec(fn.__call__, no_self=no_self)
  262. else:
  263. raise TypeError("Can't inspect callable: %s" % fn)
  264. else:
  265. raise TypeError("Can't inspect callable: %s" % fn)
  266. def format_argspec_plus(fn, grouped=True):
  267. """Returns a dictionary of formatted, introspected function arguments.
  268. A enhanced variant of inspect.formatargspec to support code generation.
  269. fn
  270. An inspectable callable or tuple of inspect getargspec() results.
  271. grouped
  272. Defaults to True; include (parens, around, argument) lists
  273. Returns:
  274. args
  275. Full inspect.formatargspec for fn
  276. self_arg
  277. The name of the first positional argument, varargs[0], or None
  278. if the function defines no positional arguments.
  279. apply_pos
  280. args, re-written in calling rather than receiving syntax. Arguments are
  281. passed positionally.
  282. apply_kw
  283. Like apply_pos, except keyword-ish args are passed as keywords.
  284. Example::
  285. >>> format_argspec_plus(lambda self, a, b, c=3, **d: 123)
  286. {'args': '(self, a, b, c=3, **d)',
  287. 'self_arg': 'self',
  288. 'apply_kw': '(self, a, b, c=c, **d)',
  289. 'apply_pos': '(self, a, b, c, **d)'}
  290. """
  291. if compat.callable(fn):
  292. spec = compat.inspect_getfullargspec(fn)
  293. else:
  294. # we accept an existing argspec...
  295. spec = fn
  296. args = inspect.formatargspec(*spec)
  297. if spec[0]:
  298. self_arg = spec[0][0]
  299. elif spec[1]:
  300. self_arg = '%s[0]' % spec[1]
  301. else:
  302. self_arg = None
  303. if compat.py3k:
  304. apply_pos = inspect.formatargspec(spec[0], spec[1],
  305. spec[2], None, spec[4])
  306. num_defaults = 0
  307. if spec[3]:
  308. num_defaults += len(spec[3])
  309. if spec[4]:
  310. num_defaults += len(spec[4])
  311. name_args = spec[0] + spec[4]
  312. else:
  313. apply_pos = inspect.formatargspec(spec[0], spec[1], spec[2])
  314. num_defaults = 0
  315. if spec[3]:
  316. num_defaults += len(spec[3])
  317. name_args = spec[0]
  318. if num_defaults:
  319. defaulted_vals = name_args[0 - num_defaults:]
  320. else:
  321. defaulted_vals = ()
  322. apply_kw = inspect.formatargspec(name_args, spec[1], spec[2],
  323. defaulted_vals,
  324. formatvalue=lambda x: '=' + x)
  325. if grouped:
  326. return dict(args=args, self_arg=self_arg,
  327. apply_pos=apply_pos, apply_kw=apply_kw)
  328. else:
  329. return dict(args=args[1:-1], self_arg=self_arg,
  330. apply_pos=apply_pos[1:-1], apply_kw=apply_kw[1:-1])
  331. def format_argspec_init(method, grouped=True):
  332. """format_argspec_plus with considerations for typical __init__ methods
  333. Wraps format_argspec_plus with error handling strategies for typical
  334. __init__ cases::
  335. object.__init__ -> (self)
  336. other unreflectable (usually C) -> (self, *args, **kwargs)
  337. """
  338. if method is object.__init__:
  339. args = grouped and '(self)' or 'self'
  340. else:
  341. try:
  342. return format_argspec_plus(method, grouped=grouped)
  343. except TypeError:
  344. args = (grouped and '(self, *args, **kwargs)'
  345. or 'self, *args, **kwargs')
  346. return dict(self_arg='self', args=args, apply_pos=args, apply_kw=args)
  347. def getargspec_init(method):
  348. """inspect.getargspec with considerations for typical __init__ methods
  349. Wraps inspect.getargspec with error handling for typical __init__ cases::
  350. object.__init__ -> (self)
  351. other unreflectable (usually C) -> (self, *args, **kwargs)
  352. """
  353. try:
  354. return compat.inspect_getargspec(method)
  355. except TypeError:
  356. if method is object.__init__:
  357. return (['self'], None, None, None)
  358. else:
  359. return (['self'], 'args', 'kwargs', None)
  360. def unbound_method_to_callable(func_or_cls):
  361. """Adjust the incoming callable such that a 'self' argument is not
  362. required.
  363. """
  364. if isinstance(func_or_cls, types.MethodType) and not func_or_cls.__self__:
  365. return func_or_cls.__func__
  366. else:
  367. return func_or_cls
  368. def generic_repr(obj, additional_kw=(), to_inspect=None, omit_kwarg=()):
  369. """Produce a __repr__() based on direct association of the __init__()
  370. specification vs. same-named attributes present.
  371. """
  372. if to_inspect is None:
  373. to_inspect = [obj]
  374. else:
  375. to_inspect = _collections.to_list(to_inspect)
  376. missing = object()
  377. pos_args = []
  378. kw_args = _collections.OrderedDict()
  379. vargs = None
  380. for i, insp in enumerate(to_inspect):
  381. try:
  382. (_args, _vargs, vkw, defaults) = \
  383. compat.inspect_getargspec(insp.__init__)
  384. except TypeError:
  385. continue
  386. else:
  387. default_len = defaults and len(defaults) or 0
  388. if i == 0:
  389. if _vargs:
  390. vargs = _vargs
  391. if default_len:
  392. pos_args.extend(_args[1:-default_len])
  393. else:
  394. pos_args.extend(_args[1:])
  395. else:
  396. kw_args.update([
  397. (arg, missing) for arg in _args[1:-default_len]
  398. ])
  399. if default_len:
  400. kw_args.update([
  401. (arg, default)
  402. for arg, default
  403. in zip(_args[-default_len:], defaults)
  404. ])
  405. output = []
  406. output.extend(repr(getattr(obj, arg, None)) for arg in pos_args)
  407. if vargs is not None and hasattr(obj, vargs):
  408. output.extend([repr(val) for val in getattr(obj, vargs)])
  409. for arg, defval in kw_args.items():
  410. if arg in omit_kwarg:
  411. continue
  412. try:
  413. val = getattr(obj, arg, missing)
  414. if val is not missing and val != defval:
  415. output.append('%s=%r' % (arg, val))
  416. except Exception:
  417. pass
  418. if additional_kw:
  419. for arg, defval in additional_kw:
  420. try:
  421. val = getattr(obj, arg, missing)
  422. if val is not missing and val != defval:
  423. output.append('%s=%r' % (arg, val))
  424. except Exception:
  425. pass
  426. return "%s(%s)" % (obj.__class__.__name__, ", ".join(output))
  427. class portable_instancemethod(object):
  428. """Turn an instancemethod into a (parent, name) pair
  429. to produce a serializable callable.
  430. """
  431. __slots__ = 'target', 'name', 'kwargs', '__weakref__'
  432. def __getstate__(self):
  433. return {'target': self.target, 'name': self.name,
  434. 'kwargs': self.kwargs}
  435. def __setstate__(self, state):
  436. self.target = state['target']
  437. self.name = state['name']
  438. self.kwargs = state.get('kwargs', ())
  439. def __init__(self, meth, kwargs=()):
  440. self.target = meth.__self__
  441. self.name = meth.__name__
  442. self.kwargs = kwargs
  443. def __call__(self, *arg, **kw):
  444. kw.update(self.kwargs)
  445. return getattr(self.target, self.name)(*arg, **kw)
  446. def class_hierarchy(cls):
  447. """Return an unordered sequence of all classes related to cls.
  448. Traverses diamond hierarchies.
  449. Fibs slightly: subclasses of builtin types are not returned. Thus
  450. class_hierarchy(class A(object)) returns (A, object), not A plus every
  451. class systemwide that derives from object.
  452. Old-style classes are discarded and hierarchies rooted on them
  453. will not be descended.
  454. """
  455. if compat.py2k:
  456. if isinstance(cls, types.ClassType):
  457. return list()
  458. hier = set([cls])
  459. process = list(cls.__mro__)
  460. while process:
  461. c = process.pop()
  462. if compat.py2k:
  463. if isinstance(c, types.ClassType):
  464. continue
  465. bases = (_ for _ in c.__bases__
  466. if _ not in hier and not isinstance(_, types.ClassType))
  467. else:
  468. bases = (_ for _ in c.__bases__ if _ not in hier)
  469. for b in bases:
  470. process.append(b)
  471. hier.add(b)
  472. if compat.py3k:
  473. if c.__module__ == 'builtins' or not hasattr(c, '__subclasses__'):
  474. continue
  475. else:
  476. if c.__module__ == '__builtin__' or not hasattr(
  477. c, '__subclasses__'):
  478. continue
  479. for s in [_ for _ in c.__subclasses__() if _ not in hier]:
  480. process.append(s)
  481. hier.add(s)
  482. return list(hier)
  483. def iterate_attributes(cls):
  484. """iterate all the keys and attributes associated
  485. with a class, without using getattr().
  486. Does not use getattr() so that class-sensitive
  487. descriptors (i.e. property.__get__()) are not called.
  488. """
  489. keys = dir(cls)
  490. for key in keys:
  491. for c in cls.__mro__:
  492. if key in c.__dict__:
  493. yield (key, c.__dict__[key])
  494. break
  495. def monkeypatch_proxied_specials(into_cls, from_cls, skip=None, only=None,
  496. name='self.proxy', from_instance=None):
  497. """Automates delegation of __specials__ for a proxying type."""
  498. if only:
  499. dunders = only
  500. else:
  501. if skip is None:
  502. skip = ('__slots__', '__del__', '__getattribute__',
  503. '__metaclass__', '__getstate__', '__setstate__')
  504. dunders = [m for m in dir(from_cls)
  505. if (m.startswith('__') and m.endswith('__') and
  506. not hasattr(into_cls, m) and m not in skip)]
  507. for method in dunders:
  508. try:
  509. fn = getattr(from_cls, method)
  510. if not hasattr(fn, '__call__'):
  511. continue
  512. fn = getattr(fn, 'im_func', fn)
  513. except AttributeError:
  514. continue
  515. try:
  516. spec = compat.inspect_getargspec(fn)
  517. fn_args = inspect.formatargspec(spec[0])
  518. d_args = inspect.formatargspec(spec[0][1:])
  519. except TypeError:
  520. fn_args = '(self, *args, **kw)'
  521. d_args = '(*args, **kw)'
  522. py = ("def %(method)s%(fn_args)s: "
  523. "return %(name)s.%(method)s%(d_args)s" % locals())
  524. env = from_instance is not None and {name: from_instance} or {}
  525. compat.exec_(py, env)
  526. try:
  527. env[method].__defaults__ = fn.__defaults__
  528. except AttributeError:
  529. pass
  530. setattr(into_cls, method, env[method])
  531. def methods_equivalent(meth1, meth2):
  532. """Return True if the two methods are the same implementation."""
  533. return getattr(meth1, '__func__', meth1) is getattr(
  534. meth2, '__func__', meth2)
  535. def as_interface(obj, cls=None, methods=None, required=None):
  536. """Ensure basic interface compliance for an instance or dict of callables.
  537. Checks that ``obj`` implements public methods of ``cls`` or has members
  538. listed in ``methods``. If ``required`` is not supplied, implementing at
  539. least one interface method is sufficient. Methods present on ``obj`` that
  540. are not in the interface are ignored.
  541. If ``obj`` is a dict and ``dict`` does not meet the interface
  542. requirements, the keys of the dictionary are inspected. Keys present in
  543. ``obj`` that are not in the interface will raise TypeErrors.
  544. Raises TypeError if ``obj`` does not meet the interface criteria.
  545. In all passing cases, an object with callable members is returned. In the
  546. simple case, ``obj`` is returned as-is; if dict processing kicks in then
  547. an anonymous class is returned.
  548. obj
  549. A type, instance, or dictionary of callables.
  550. cls
  551. Optional, a type. All public methods of cls are considered the
  552. interface. An ``obj`` instance of cls will always pass, ignoring
  553. ``required``..
  554. methods
  555. Optional, a sequence of method names to consider as the interface.
  556. required
  557. Optional, a sequence of mandatory implementations. If omitted, an
  558. ``obj`` that provides at least one interface method is considered
  559. sufficient. As a convenience, required may be a type, in which case
  560. all public methods of the type are required.
  561. """
  562. if not cls and not methods:
  563. raise TypeError('a class or collection of method names are required')
  564. if isinstance(cls, type) and isinstance(obj, cls):
  565. return obj
  566. interface = set(methods or [m for m in dir(cls) if not m.startswith('_')])
  567. implemented = set(dir(obj))
  568. complies = operator.ge
  569. if isinstance(required, type):
  570. required = interface
  571. elif not required:
  572. required = set()
  573. complies = operator.gt
  574. else:
  575. required = set(required)
  576. if complies(implemented.intersection(interface), required):
  577. return obj
  578. # No dict duck typing here.
  579. if not isinstance(obj, dict):
  580. qualifier = complies is operator.gt and 'any of' or 'all of'
  581. raise TypeError("%r does not implement %s: %s" % (
  582. obj, qualifier, ', '.join(interface)))
  583. class AnonymousInterface(object):
  584. """A callable-holding shell."""
  585. if cls:
  586. AnonymousInterface.__name__ = 'Anonymous' + cls.__name__
  587. found = set()
  588. for method, impl in dictlike_iteritems(obj):
  589. if method not in interface:
  590. raise TypeError("%r: unknown in this interface" % method)
  591. if not compat.callable(impl):
  592. raise TypeError("%r=%r is not callable" % (method, impl))
  593. setattr(AnonymousInterface, method, staticmethod(impl))
  594. found.add(method)
  595. if complies(found, required):
  596. return AnonymousInterface
  597. raise TypeError("dictionary does not contain required keys %s" %
  598. ', '.join(required - found))
  599. class memoized_property(object):
  600. """A read-only @property that is only evaluated once."""
  601. def __init__(self, fget, doc=None):
  602. self.fget = fget
  603. self.__doc__ = doc or fget.__doc__
  604. self.__name__ = fget.__name__
  605. def __get__(self, obj, cls):
  606. if obj is None:
  607. return self
  608. obj.__dict__[self.__name__] = result = self.fget(obj)
  609. return result
  610. def _reset(self, obj):
  611. memoized_property.reset(obj, self.__name__)
  612. @classmethod
  613. def reset(cls, obj, name):
  614. obj.__dict__.pop(name, None)
  615. def memoized_instancemethod(fn):
  616. """Decorate a method memoize its return value.
  617. Best applied to no-arg methods: memoization is not sensitive to
  618. argument values, and will always return the same value even when
  619. called with different arguments.
  620. """
  621. def oneshot(self, *args, **kw):
  622. result = fn(self, *args, **kw)
  623. memo = lambda *a, **kw: result
  624. memo.__name__ = fn.__name__
  625. memo.__doc__ = fn.__doc__
  626. self.__dict__[fn.__name__] = memo
  627. return result
  628. return update_wrapper(oneshot, fn)
  629. class group_expirable_memoized_property(object):
  630. """A family of @memoized_properties that can be expired in tandem."""
  631. def __init__(self, attributes=()):
  632. self.attributes = []
  633. if attributes:
  634. self.attributes.extend(attributes)
  635. def expire_instance(self, instance):
  636. """Expire all memoized properties for *instance*."""
  637. stash = instance.__dict__
  638. for attribute in self.attributes:
  639. stash.pop(attribute, None)
  640. def __call__(self, fn):
  641. self.attributes.append(fn.__name__)
  642. return memoized_property(fn)
  643. def method(self, fn):
  644. self.attributes.append(fn.__name__)
  645. return memoized_instancemethod(fn)
  646. class MemoizedSlots(object):
  647. """Apply memoized items to an object using a __getattr__ scheme.
  648. This allows the functionality of memoized_property and
  649. memoized_instancemethod to be available to a class using __slots__.
  650. """
  651. __slots__ = ()
  652. def _fallback_getattr(self, key):
  653. raise AttributeError(key)
  654. def __getattr__(self, key):
  655. if key.startswith('_memoized'):
  656. raise AttributeError(key)
  657. elif hasattr(self, '_memoized_attr_%s' % key):
  658. value = getattr(self, '_memoized_attr_%s' % key)()
  659. setattr(self, key, value)
  660. return value
  661. elif hasattr(self, '_memoized_method_%s' % key):
  662. fn = getattr(self, '_memoized_method_%s' % key)
  663. def oneshot(*args, **kw):
  664. result = fn(*args, **kw)
  665. memo = lambda *a, **kw: result
  666. memo.__name__ = fn.__name__
  667. memo.__doc__ = fn.__doc__
  668. setattr(self, key, memo)
  669. return result
  670. oneshot.__doc__ = fn.__doc__
  671. return oneshot
  672. else:
  673. return self._fallback_getattr(key)
  674. def dependency_for(modulename):
  675. def decorate(obj):
  676. # TODO: would be nice to improve on this import silliness,
  677. # unfortunately importlib doesn't work that great either
  678. tokens = modulename.split(".")
  679. mod = compat.import_(
  680. ".".join(tokens[0:-1]), globals(), locals(), tokens[-1])
  681. mod = getattr(mod, tokens[-1])
  682. setattr(mod, obj.__name__, obj)
  683. return obj
  684. return decorate
  685. class dependencies(object):
  686. """Apply imported dependencies as arguments to a function.
  687. E.g.::
  688. @util.dependencies(
  689. "sqlalchemy.sql.widget",
  690. "sqlalchemy.engine.default"
  691. );
  692. def some_func(self, widget, default, arg1, arg2, **kw):
  693. # ...
  694. Rationale is so that the impact of a dependency cycle can be
  695. associated directly with the few functions that cause the cycle,
  696. and not pollute the module-level namespace.
  697. """
  698. def __init__(self, *deps):
  699. self.import_deps = []
  700. for dep in deps:
  701. tokens = dep.split(".")
  702. self.import_deps.append(
  703. dependencies._importlater(
  704. ".".join(tokens[0:-1]),
  705. tokens[-1]
  706. )
  707. )
  708. def __call__(self, fn):
  709. import_deps = self.import_deps
  710. spec = compat.inspect_getfullargspec(fn)
  711. spec_zero = list(spec[0])
  712. hasself = spec_zero[0] in ('self', 'cls')
  713. for i in range(len(import_deps)):
  714. spec[0][i + (1 if hasself else 0)] = "import_deps[%r]" % i
  715. inner_spec = format_argspec_plus(spec, grouped=False)
  716. for impname in import_deps:
  717. del spec_zero[1 if hasself else 0]
  718. spec[0][:] = spec_zero
  719. outer_spec = format_argspec_plus(spec, grouped=False)
  720. code = 'lambda %(args)s: fn(%(apply_kw)s)' % {
  721. "args": outer_spec['args'],
  722. "apply_kw": inner_spec['apply_kw']
  723. }
  724. decorated = eval(code, locals())
  725. decorated.__defaults__ = getattr(fn, 'im_func', fn).__defaults__
  726. return update_wrapper(decorated, fn)
  727. @classmethod
  728. def resolve_all(cls, path):
  729. for m in list(dependencies._unresolved):
  730. if m._full_path.startswith(path):
  731. m._resolve()
  732. _unresolved = set()
  733. _by_key = {}
  734. class _importlater(object):
  735. _unresolved = set()
  736. _by_key = {}
  737. def __new__(cls, path, addtl):
  738. key = path + "." + addtl
  739. if key in dependencies._by_key:
  740. return dependencies._by_key[key]
  741. else:
  742. dependencies._by_key[key] = imp = object.__new__(cls)
  743. return imp
  744. def __init__(self, path, addtl):
  745. self._il_path = path
  746. self._il_addtl = addtl
  747. dependencies._unresolved.add(self)
  748. @property
  749. def _full_path(self):
  750. return self._il_path + "." + self._il_addtl
  751. @memoized_property
  752. def module(self):
  753. if self in dependencies._unresolved:
  754. raise ImportError(
  755. "importlater.resolve_all() hasn't "
  756. "been called (this is %s %s)"
  757. % (self._il_path, self._il_addtl))
  758. return getattr(self._initial_import, self._il_addtl)
  759. def _resolve(self):
  760. dependencies._unresolved.discard(self)
  761. self._initial_import = compat.import_(
  762. self._il_path, globals(), locals(),
  763. [self._il_addtl])
  764. def __getattr__(self, key):
  765. if key == 'module':
  766. raise ImportError("Could not resolve module %s"
  767. % self._full_path)
  768. try:
  769. attr = getattr(self.module, key)
  770. except AttributeError:
  771. raise AttributeError(
  772. "Module %s has no attribute '%s'" %
  773. (self._full_path, key)
  774. )
  775. self.__dict__[key] = attr
  776. return attr
  777. # from paste.deploy.converters
  778. def asbool(obj):
  779. if isinstance(obj, compat.string_types):
  780. obj = obj.strip().lower()
  781. if obj in ['true', 'yes', 'on', 'y', 't', '1']:
  782. return True
  783. elif obj in ['false', 'no', 'off', 'n', 'f', '0']:
  784. return False
  785. else:
  786. raise ValueError("String is not true/false: %r" % obj)
  787. return bool(obj)
  788. def bool_or_str(*text):
  789. """Return a callable that will evaluate a string as
  790. boolean, or one of a set of "alternate" string values.
  791. """
  792. def bool_or_value(obj):
  793. if obj in text:
  794. return obj
  795. else:
  796. return asbool(obj)
  797. return bool_or_value
  798. def asint(value):
  799. """Coerce to integer."""
  800. if value is None:
  801. return value
  802. return int(value)
  803. def coerce_kw_type(kw, key, type_, flexi_bool=True):
  804. r"""If 'key' is present in dict 'kw', coerce its value to type 'type\_' if
  805. necessary. If 'flexi_bool' is True, the string '0' is considered false
  806. when coercing to boolean.
  807. """
  808. if key in kw and not isinstance(kw[key], type_) and kw[key] is not None:
  809. if type_ is bool and flexi_bool:
  810. kw[key] = asbool(kw[key])
  811. else:
  812. kw[key] = type_(kw[key])
  813. def constructor_copy(obj, cls, *args, **kw):
  814. """Instantiate cls using the __dict__ of obj as constructor arguments.
  815. Uses inspect to match the named arguments of ``cls``.
  816. """
  817. names = get_cls_kwargs(cls)
  818. kw.update(
  819. (k, obj.__dict__[k]) for k in names.difference(kw)
  820. if k in obj.__dict__)
  821. return cls(*args, **kw)
  822. def counter():
  823. """Return a threadsafe counter function."""
  824. lock = compat.threading.Lock()
  825. counter = itertools.count(1)
  826. # avoid the 2to3 "next" transformation...
  827. def _next():
  828. lock.acquire()
  829. try:
  830. return next(counter)
  831. finally:
  832. lock.release()
  833. return _next
  834. def duck_type_collection(specimen, default=None):
  835. """Given an instance or class, guess if it is or is acting as one of
  836. the basic collection types: list, set and dict. If the __emulates__
  837. property is present, return that preferentially.
  838. """
  839. if hasattr(specimen, '__emulates__'):
  840. # canonicalize set vs sets.Set to a standard: the builtin set
  841. if (specimen.__emulates__ is not None and
  842. issubclass(specimen.__emulates__, set)):
  843. return set
  844. else:
  845. return specimen.__emulates__
  846. isa = isinstance(specimen, type) and issubclass or isinstance
  847. if isa(specimen, list):
  848. return list
  849. elif isa(specimen, set):
  850. return set
  851. elif isa(specimen, dict):
  852. return dict
  853. if hasattr(specimen, 'append'):
  854. return list
  855. elif hasattr(specimen, 'add'):
  856. return set
  857. elif hasattr(specimen, 'set'):
  858. return dict
  859. else:
  860. return default
  861. def assert_arg_type(arg, argtype, name):
  862. if isinstance(arg, argtype):
  863. return arg
  864. else:
  865. if isinstance(argtype, tuple):
  866. raise exc.ArgumentError(
  867. "Argument '%s' is expected to be one of type %s, got '%s'" %
  868. (name, ' or '.join("'%s'" % a for a in argtype), type(arg)))
  869. else:
  870. raise exc.ArgumentError(
  871. "Argument '%s' is expected to be of type '%s', got '%s'" %
  872. (name, argtype, type(arg)))
  873. def dictlike_iteritems(dictlike):
  874. """Return a (key, value) iterator for almost any dict-like object."""
  875. if compat.py3k:
  876. if hasattr(dictlike, 'items'):
  877. return list(dictlike.items())
  878. else:
  879. if hasattr(dictlike, 'iteritems'):
  880. return dictlike.iteritems()
  881. elif hasattr(dictlike, 'items'):
  882. return iter(dictlike.items())
  883. getter = getattr(dictlike, '__getitem__', getattr(dictlike, 'get', None))
  884. if getter is None:
  885. raise TypeError(
  886. "Object '%r' is not dict-like" % dictlike)
  887. if hasattr(dictlike, 'iterkeys'):
  888. def iterator():
  889. for key in dictlike.iterkeys():
  890. yield key, getter(key)
  891. return iterator()
  892. elif hasattr(dictlike, 'keys'):
  893. return iter((key, getter(key)) for key in dictlike.keys())
  894. else:
  895. raise TypeError(
  896. "Object '%r' is not dict-like" % dictlike)
  897. class classproperty(property):
  898. """A decorator that behaves like @property except that operates
  899. on classes rather than instances.
  900. The decorator is currently special when using the declarative
  901. module, but note that the
  902. :class:`~.sqlalchemy.ext.declarative.declared_attr`
  903. decorator should be used for this purpose with declarative.
  904. """
  905. def __init__(self, fget, *arg, **kw):
  906. super(classproperty, self).__init__(fget, *arg, **kw)
  907. self.__doc__ = fget.__doc__
  908. def __get__(desc, self, cls):
  909. return desc.fget(cls)
  910. class hybridproperty(object):
  911. def __init__(self, func):
  912. self.func = func
  913. def __get__(self, instance, owner):
  914. if instance is None:
  915. clsval = self.func(owner)
  916. clsval.__doc__ = self.func.__doc__
  917. return clsval
  918. else:
  919. return self.func(instance)
  920. class hybridmethod(object):
  921. """Decorate a function as cls- or instance- level."""
  922. def __init__(self, func):
  923. self.func = func
  924. def __get__(self, instance, owner):
  925. if instance is None:
  926. return self.func.__get__(owner, owner.__class__)
  927. else:
  928. return self.func.__get__(instance, owner)
  929. class _symbol(int):
  930. def __new__(self, name, doc=None, canonical=None):
  931. """Construct a new named symbol."""
  932. assert isinstance(name, compat.string_types)
  933. if canonical is None:
  934. canonical = hash(name)
  935. v = int.__new__(_symbol, canonical)
  936. v.name = name
  937. if doc:
  938. v.__doc__ = doc
  939. return v
  940. def __reduce__(self):
  941. return symbol, (self.name, "x", int(self))
  942. def __str__(self):
  943. return repr(self)
  944. def __repr__(self):
  945. return "symbol(%r)" % self.name
  946. _symbol.__name__ = 'symbol'
  947. class symbol(object):
  948. """A constant symbol.
  949. >>> symbol('foo') is symbol('foo')
  950. True
  951. >>> symbol('foo')
  952. <symbol 'foo>
  953. A slight refinement of the MAGICCOOKIE=object() pattern. The primary
  954. advantage of symbol() is its repr(). They are also singletons.
  955. Repeated calls of symbol('name') will all return the same instance.
  956. The optional ``doc`` argument assigns to ``__doc__``. This
  957. is strictly so that Sphinx autoattr picks up the docstring we want
  958. (it doesn't appear to pick up the in-module docstring if the datamember
  959. is in a different module - autoattribute also blows up completely).
  960. If Sphinx fixes/improves this then we would no longer need
  961. ``doc`` here.
  962. """
  963. symbols = {}
  964. _lock = compat.threading.Lock()
  965. def __new__(cls, name, doc=None, canonical=None):
  966. cls._lock.acquire()
  967. try:
  968. sym = cls.symbols.get(name)
  969. if sym is None:
  970. cls.symbols[name] = sym = _symbol(name, doc, canonical)
  971. return sym
  972. finally:
  973. symbol._lock.release()
  974. _creation_order = 1
  975. def set_creation_order(instance):
  976. """Assign a '_creation_order' sequence to the given instance.
  977. This allows multiple instances to be sorted in order of creation
  978. (typically within a single thread; the counter is not particularly
  979. threadsafe).
  980. """
  981. global _creation_order
  982. instance._creation_order = _creation_order
  983. _creation_order += 1
  984. def warn_exception(func, *args, **kwargs):
  985. """executes the given function, catches all exceptions and converts to
  986. a warning.
  987. """
  988. try:
  989. return func(*args, **kwargs)
  990. except Exception:
  991. warn("%s('%s') ignored" % sys.exc_info()[0:2])
  992. def ellipses_string(value, len_=25):
  993. try:
  994. if len(value) > len_:
  995. return "%s..." % value[0:len_]
  996. else:
  997. return value
  998. except TypeError:
  999. return value
  1000. class _hash_limit_string(compat.text_type):
  1001. """A string subclass that can only be hashed on a maximum amount
  1002. of unique values.
  1003. This is used for warnings so that we can send out parameterized warnings
  1004. without the __warningregistry__ of the module, or the non-overridable
  1005. "once" registry within warnings.py, overloading memory,
  1006. """
  1007. def __new__(cls, value, num, args):
  1008. interpolated = (value % args) + \
  1009. (" (this warning may be suppressed after %d occurrences)" % num)
  1010. self = super(_hash_limit_string, cls).__new__(cls, interpolated)
  1011. self._hash = hash("%s_%d" % (value, hash(interpolated) % num))
  1012. return self
  1013. def __hash__(self):
  1014. return self._hash
  1015. def __eq__(self, other):
  1016. return hash(self) == hash(other)
  1017. def warn(msg):
  1018. """Issue a warning.
  1019. If msg is a string, :class:`.exc.SAWarning` is used as
  1020. the category.
  1021. """
  1022. warnings.warn(msg, exc.SAWarning, stacklevel=2)
  1023. def warn_limited(msg, args):
  1024. """Issue a warning with a paramterized string, limiting the number
  1025. of registrations.
  1026. """
  1027. if args:
  1028. msg = _hash_limit_string(msg, 10, args)
  1029. warnings.warn(msg, exc.SAWarning, stacklevel=2)
  1030. def only_once(fn):
  1031. """Decorate the given function to be a no-op after it is called exactly
  1032. once."""
  1033. once = [fn]
  1034. def go(*arg, **kw):
  1035. if once:
  1036. once_fn = once.pop()
  1037. return once_fn(*arg, **kw)
  1038. return go
  1039. _SQLA_RE = re.compile(r'sqlalchemy/([a-z_]+/){0,2}[a-z_]+\.py')
  1040. _UNITTEST_RE = re.compile(r'unit(?:2|test2?/)')
  1041. def chop_traceback(tb, exclude_prefix=_UNITTEST_RE, exclude_suffix=_SQLA_RE):
  1042. """Chop extraneous lines off beginning and end of a traceback.
  1043. :param tb:
  1044. a list of traceback lines as returned by ``traceback.format_stack()``
  1045. :param exclude_prefix:
  1046. a regular expression object matching lines to skip at beginning of
  1047. ``tb``
  1048. :param exclude_suffix:
  1049. a regular expression object matching lines to skip at end of ``tb``
  1050. """
  1051. start = 0
  1052. end = len(tb) - 1
  1053. while start <= end and exclude_prefix.search(tb[start]):
  1054. start += 1
  1055. while start <= end and exclude_suffix.search(tb[end]):
  1056. end -= 1
  1057. return tb[start:end + 1]
  1058. NoneType = type(None)
  1059. def attrsetter(attrname):
  1060. code = \
  1061. "def set(obj, value):"\
  1062. " obj.%s = value" % attrname
  1063. env = locals().copy()
  1064. exec(code, env)
  1065. return env['set']
  1066. class EnsureKWArgType(type):
  1067. """Apply translation of functions to accept **kw arguments if they
  1068. don't already.
  1069. """
  1070. def __init__(cls, clsname, bases, clsdict):
  1071. fn_reg = cls.ensure_kwarg
  1072. if fn_reg:
  1073. for key in clsdict:
  1074. m = re.match(fn_reg, key)
  1075. if m:
  1076. fn = clsdict[key]
  1077. spec = compat.inspect_getargspec(fn)
  1078. if not spec.keywords:
  1079. clsdict[key] = wrapped = cls._wrap_w_kw(fn)
  1080. setattr(cls, key, wrapped)
  1081. super(EnsureKWArgType, cls).__init__(clsname, bases, clsdict)
  1082. def _wrap_w_kw(self, fn):
  1083. def wrap(*arg, **kw):
  1084. return fn(*arg)
  1085. return update_wrapper(wrap, fn)
  1086. def wrap_callable(wrapper, fn):
  1087. """Augment functools.update_wrapper() to work with objects with
  1088. a ``__call__()`` method.
  1089. :param fn:
  1090. object with __call__ method
  1091. """
  1092. if hasattr(fn, '__name__'):
  1093. return update_wrapper(wrapper, fn)
  1094. else:
  1095. _f = wrapper
  1096. _f.__name__ = fn.__class__.__name__
  1097. if hasattr(fn, '__module__'):
  1098. _f.__module__ = fn.__module__
  1099. if hasattr(fn.__call__, '__doc__') and fn.__call__.__doc__:
  1100. _f.__doc__ = fn.__call__.__doc__
  1101. elif fn.__doc__:
  1102. _f.__doc__ = fn.__doc__
  1103. return _f