PageRenderTime 32ms CodeModel.GetById 0ms RepoModel.GetById 1ms app.codeStats 0ms

/library/sqlalchemy/util.py

https://github.com/jsmiller84/CouchPotato
Python | 1656 lines | 1476 code | 78 blank | 102 comment | 82 complexity | 774fdbb52c7def7d87697c83f297f3ce MD5 | raw file
  1. # util.py
  2. # Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Michael Bayer mike_mp@zzzcomputing.com
  3. #
  4. # This module is part of SQLAlchemy and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. import inspect, itertools, operator, sys, warnings, weakref, gc
  7. # Py2K
  8. import __builtin__
  9. # end Py2K
  10. types = __import__('types')
  11. from sqlalchemy import exc
  12. try:
  13. import threading
  14. except ImportError:
  15. import dummy_threading as threading
  16. py3k = getattr(sys, 'py3kwarning', False) or sys.version_info >= (3, 0)
  17. jython = sys.platform.startswith('java')
  18. win32 = sys.platform.startswith('win')
  19. if py3k:
  20. set_types = set
  21. elif sys.version_info < (2, 6):
  22. import sets
  23. set_types = set, sets.Set
  24. else:
  25. # 2.6 deprecates sets.Set, but we still need to be able to detect them
  26. # in user code and as return values from DB-APIs
  27. ignore = ('ignore', None, DeprecationWarning, None, 0)
  28. try:
  29. warnings.filters.insert(0, ignore)
  30. except Exception:
  31. import sets
  32. else:
  33. import sets
  34. warnings.filters.remove(ignore)
  35. set_types = set, sets.Set
  36. EMPTY_SET = frozenset()
  37. NoneType = type(None)
  38. if py3k:
  39. import pickle
  40. else:
  41. try:
  42. import cPickle as pickle
  43. except ImportError:
  44. import pickle
  45. # Py2K
  46. # a controversial feature, required by MySQLdb currently
  47. def buffer(x):
  48. return x
  49. buffer = getattr(__builtin__, 'buffer', buffer)
  50. # end Py2K
  51. if sys.version_info >= (2, 5):
  52. class PopulateDict(dict):
  53. """A dict which populates missing values via a creation function.
  54. Note the creation function takes a key, unlike
  55. collections.defaultdict.
  56. """
  57. def __init__(self, creator):
  58. self.creator = creator
  59. def __missing__(self, key):
  60. self[key] = val = self.creator(key)
  61. return val
  62. else:
  63. class PopulateDict(dict):
  64. """A dict which populates missing values via a creation function."""
  65. def __init__(self, creator):
  66. self.creator = creator
  67. def __getitem__(self, key):
  68. try:
  69. return dict.__getitem__(self, key)
  70. except KeyError:
  71. self[key] = value = self.creator(key)
  72. return value
  73. if py3k:
  74. def callable(fn):
  75. return hasattr(fn, '__call__')
  76. def cmp(a, b):
  77. return (a > b) - (a < b)
  78. from functools import reduce
  79. else:
  80. callable = __builtin__.callable
  81. cmp = __builtin__.cmp
  82. reduce = __builtin__.reduce
  83. try:
  84. from collections import defaultdict
  85. except ImportError:
  86. class defaultdict(dict):
  87. def __init__(self, default_factory=None, *a, **kw):
  88. if (default_factory is not None and
  89. not hasattr(default_factory, '__call__')):
  90. raise TypeError('first argument must be callable')
  91. dict.__init__(self, *a, **kw)
  92. self.default_factory = default_factory
  93. def __getitem__(self, key):
  94. try:
  95. return dict.__getitem__(self, key)
  96. except KeyError:
  97. return self.__missing__(key)
  98. def __missing__(self, key):
  99. if self.default_factory is None:
  100. raise KeyError(key)
  101. self[key] = value = self.default_factory()
  102. return value
  103. def __reduce__(self):
  104. if self.default_factory is None:
  105. args = tuple()
  106. else:
  107. args = self.default_factory,
  108. return type(self), args, None, None, self.iteritems()
  109. def copy(self):
  110. return self.__copy__()
  111. def __copy__(self):
  112. return type(self)(self.default_factory, self)
  113. def __deepcopy__(self, memo):
  114. import copy
  115. return type(self)(self.default_factory,
  116. copy.deepcopy(self.items()))
  117. def __repr__(self):
  118. return 'defaultdict(%s, %s)' % (self.default_factory,
  119. dict.__repr__(self))
  120. class frozendict(dict):
  121. @property
  122. def _blocked_attribute(obj):
  123. raise AttributeError, "A frozendict cannot be modified."
  124. __delitem__ = __setitem__ = clear = _blocked_attribute
  125. pop = popitem = setdefault = update = _blocked_attribute
  126. def __new__(cls, *args):
  127. new = dict.__new__(cls)
  128. dict.__init__(new, *args)
  129. return new
  130. def __init__(self, *args):
  131. pass
  132. def __reduce__(self):
  133. return frozendict, (dict(self), )
  134. def union(self, d):
  135. if not self:
  136. return frozendict(d)
  137. else:
  138. d2 = self.copy()
  139. d2.update(d)
  140. return frozendict(d2)
  141. def __repr__(self):
  142. return "frozendict(%s)" % dict.__repr__(self)
  143. def to_list(x, default=None):
  144. if x is None:
  145. return default
  146. if not isinstance(x, (list, tuple)):
  147. return [x]
  148. else:
  149. return x
  150. def to_set(x):
  151. if x is None:
  152. return set()
  153. if not isinstance(x, set):
  154. return set(to_list(x))
  155. else:
  156. return x
  157. def to_column_set(x):
  158. if x is None:
  159. return column_set()
  160. if not isinstance(x, column_set):
  161. return column_set(to_list(x))
  162. else:
  163. return x
  164. try:
  165. from functools import update_wrapper
  166. except ImportError:
  167. def update_wrapper(wrapper, wrapped,
  168. assigned=('__doc__', '__module__', '__name__'),
  169. updated=('__dict__',)):
  170. for attr in assigned:
  171. setattr(wrapper, attr, getattr(wrapped, attr))
  172. for attr in updated:
  173. getattr(wrapper, attr).update(getattr(wrapped, attr, ()))
  174. return wrapper
  175. try:
  176. from functools import partial
  177. except:
  178. def partial(func, *args, **keywords):
  179. def newfunc(*fargs, **fkeywords):
  180. newkeywords = keywords.copy()
  181. newkeywords.update(fkeywords)
  182. return func(*(args + fargs), **newkeywords)
  183. return newfunc
  184. def accepts_a_list_as_starargs(list_deprecation=None):
  185. def decorate(fn):
  186. spec = inspect.getargspec(fn)
  187. assert spec[1], 'Decorated function does not accept *args'
  188. def _deprecate():
  189. if list_deprecation:
  190. if list_deprecation == 'pending':
  191. warning_type = exc.SAPendingDeprecationWarning
  192. else:
  193. warning_type = exc.SADeprecationWarning
  194. msg = (
  195. "%s%s now accepts multiple %s arguments as a "
  196. "variable argument list. Supplying %s as a single "
  197. "list is deprecated and support will be removed "
  198. "in a future release." % (
  199. fn.func_name,
  200. inspect.formatargspec(*spec),
  201. spec[1], spec[1]))
  202. warnings.warn(msg, warning_type, stacklevel=3)
  203. def go(fn, *args, **kw):
  204. if isinstance(args[-1], list):
  205. _deprecate()
  206. return fn(*(list(args[0:-1]) + args[-1]), **kw)
  207. else:
  208. return fn(*args, **kw)
  209. return decorator(go)(fn)
  210. return decorate
  211. def unique_symbols(used, *bases):
  212. used = set(used)
  213. for base in bases:
  214. pool = itertools.chain((base,),
  215. itertools.imap(lambda i: base + str(i),
  216. xrange(1000)))
  217. for sym in pool:
  218. if sym not in used:
  219. used.add(sym)
  220. yield sym
  221. break
  222. else:
  223. raise NameError("exhausted namespace for symbol base %s" % base)
  224. def decorator(target):
  225. """A signature-matching decorator factory."""
  226. def decorate(fn):
  227. spec = inspect.getargspec(fn)
  228. names = tuple(spec[0]) + spec[1:3] + (fn.func_name,)
  229. targ_name, fn_name = unique_symbols(names, 'target', 'fn')
  230. metadata = dict(target=targ_name, fn=fn_name)
  231. metadata.update(format_argspec_plus(spec, grouped=False))
  232. code = 'lambda %(args)s: %(target)s(%(fn)s, %(apply_kw)s)' % (
  233. metadata)
  234. decorated = eval(code, {targ_name:target, fn_name:fn})
  235. decorated.func_defaults = getattr(fn, 'im_func', fn).func_defaults
  236. return update_wrapper(decorated, fn)
  237. return update_wrapper(decorate, target)
  238. if sys.version_info >= (2, 5):
  239. def decode_slice(slc):
  240. """decode a slice object as sent to __getitem__.
  241. takes into account the 2.5 __index__() method, basically.
  242. """
  243. ret = []
  244. for x in slc.start, slc.stop, slc.step:
  245. if hasattr(x, '__index__'):
  246. x = x.__index__()
  247. ret.append(x)
  248. return tuple(ret)
  249. else:
  250. def decode_slice(slc):
  251. return (slc.start, slc.stop, slc.step)
  252. def update_copy(d, _new=None, **kw):
  253. """Copy the given dict and update with the given values."""
  254. d = d.copy()
  255. if _new:
  256. d.update(_new)
  257. d.update(**kw)
  258. return d
  259. def flatten_iterator(x):
  260. """Given an iterator of which further sub-elements may also be
  261. iterators, flatten the sub-elements into a single iterator.
  262. """
  263. for elem in x:
  264. if not isinstance(elem, basestring) and hasattr(elem, '__iter__'):
  265. for y in flatten_iterator(elem):
  266. yield y
  267. else:
  268. yield elem
  269. def get_cls_kwargs(cls):
  270. """Return the full set of inherited kwargs for the given `cls`.
  271. Probes a class's __init__ method, collecting all named arguments. If the
  272. __init__ defines a \**kwargs catch-all, then the constructor is presumed to
  273. pass along unrecognized keywords to it's base classes, and the collection
  274. process is repeated recursively on each of the bases.
  275. """
  276. for c in cls.__mro__:
  277. if '__init__' in c.__dict__:
  278. stack = set([c])
  279. break
  280. else:
  281. return []
  282. args = set()
  283. while stack:
  284. class_ = stack.pop()
  285. ctr = class_.__dict__.get('__init__', False)
  286. if not ctr or not isinstance(ctr, types.FunctionType):
  287. stack.update(class_.__bases__)
  288. continue
  289. names, _, has_kw, _ = inspect.getargspec(ctr)
  290. args.update(names)
  291. if has_kw:
  292. stack.update(class_.__bases__)
  293. args.discard('self')
  294. return args
  295. def get_func_kwargs(func):
  296. """Return the full set of legal kwargs for the given `func`."""
  297. return inspect.getargspec(func)[0]
  298. def format_argspec_plus(fn, grouped=True):
  299. """Returns a dictionary of formatted, introspected function arguments.
  300. A enhanced variant of inspect.formatargspec to support code generation.
  301. fn
  302. An inspectable callable or tuple of inspect getargspec() results.
  303. grouped
  304. Defaults to True; include (parens, around, argument) lists
  305. Returns:
  306. args
  307. Full inspect.formatargspec for fn
  308. self_arg
  309. The name of the first positional argument, varargs[0], or None
  310. if the function defines no positional arguments.
  311. apply_pos
  312. args, re-written in calling rather than receiving syntax. Arguments are
  313. passed positionally.
  314. apply_kw
  315. Like apply_pos, except keyword-ish args are passed as keywords.
  316. Example::
  317. >>> format_argspec_plus(lambda self, a, b, c=3, **d: 123)
  318. {'args': '(self, a, b, c=3, **d)',
  319. 'self_arg': 'self',
  320. 'apply_kw': '(self, a, b, c=c, **d)',
  321. 'apply_pos': '(self, a, b, c, **d)'}
  322. """
  323. spec = callable(fn) and inspect.getargspec(fn) or fn
  324. args = inspect.formatargspec(*spec)
  325. if spec[0]:
  326. self_arg = spec[0][0]
  327. elif spec[1]:
  328. self_arg = '%s[0]' % spec[1]
  329. else:
  330. self_arg = None
  331. apply_pos = inspect.formatargspec(spec[0], spec[1], spec[2])
  332. defaulted_vals = spec[3] is not None and spec[0][0-len(spec[3]):] or ()
  333. apply_kw = inspect.formatargspec(spec[0], spec[1], spec[2], defaulted_vals,
  334. formatvalue=lambda x: '=' + x)
  335. if grouped:
  336. return dict(args=args, self_arg=self_arg,
  337. apply_pos=apply_pos, apply_kw=apply_kw)
  338. else:
  339. return dict(args=args[1:-1], self_arg=self_arg,
  340. apply_pos=apply_pos[1:-1], apply_kw=apply_kw[1:-1])
  341. def format_argspec_init(method, grouped=True):
  342. """format_argspec_plus with considerations for typical __init__ methods
  343. Wraps format_argspec_plus with error handling strategies for typical
  344. __init__ cases::
  345. object.__init__ -> (self)
  346. other unreflectable (usually C) -> (self, *args, **kwargs)
  347. """
  348. try:
  349. return format_argspec_plus(method, grouped=grouped)
  350. except TypeError:
  351. self_arg = 'self'
  352. if method is object.__init__:
  353. args = grouped and '(self)' or 'self'
  354. else:
  355. args = (grouped and '(self, *args, **kwargs)'
  356. or 'self, *args, **kwargs')
  357. return dict(self_arg='self', args=args, apply_pos=args, apply_kw=args)
  358. def getargspec_init(method):
  359. """inspect.getargspec with considerations for typical __init__ methods
  360. Wraps inspect.getargspec with error handling for typical __init__ cases::
  361. object.__init__ -> (self)
  362. other unreflectable (usually C) -> (self, *args, **kwargs)
  363. """
  364. try:
  365. return inspect.getargspec(method)
  366. except TypeError:
  367. if method is object.__init__:
  368. return (['self'], None, None, None)
  369. else:
  370. return (['self'], 'args', 'kwargs', None)
  371. def unbound_method_to_callable(func_or_cls):
  372. """Adjust the incoming callable such that a 'self' argument is not required."""
  373. if isinstance(func_or_cls, types.MethodType) and not func_or_cls.im_self:
  374. return func_or_cls.im_func
  375. else:
  376. return func_or_cls
  377. class portable_instancemethod(object):
  378. """Turn an instancemethod into a (parent, name) pair
  379. to produce a serializable callable.
  380. """
  381. def __init__(self, meth):
  382. self.target = meth.im_self
  383. self.name = meth.__name__
  384. def __call__(self, *arg, **kw):
  385. return getattr(self.target, self.name)(*arg, **kw)
  386. def class_hierarchy(cls):
  387. """Return an unordered sequence of all classes related to cls.
  388. Traverses diamond hierarchies.
  389. Fibs slightly: subclasses of builtin types are not returned. Thus
  390. class_hierarchy(class A(object)) returns (A, object), not A plus every
  391. class systemwide that derives from object.
  392. Old-style classes are discarded and hierarchies rooted on them
  393. will not be descended.
  394. """
  395. # Py2K
  396. if isinstance(cls, types.ClassType):
  397. return list()
  398. # end Py2K
  399. hier = set([cls])
  400. process = list(cls.__mro__)
  401. while process:
  402. c = process.pop()
  403. # Py2K
  404. if isinstance(c, types.ClassType):
  405. continue
  406. for b in (_ for _ in c.__bases__
  407. if _ not in hier and not isinstance(_, types.ClassType)):
  408. # end Py2K
  409. # Py3K
  410. #for b in (_ for _ in c.__bases__
  411. # if _ not in hier):
  412. process.append(b)
  413. hier.add(b)
  414. # Py3K
  415. #if c.__module__ == 'builtins' or not hasattr(c, '__subclasses__'):
  416. # continue
  417. # Py2K
  418. if c.__module__ == '__builtin__' or not hasattr(c, '__subclasses__'):
  419. continue
  420. # end Py2K
  421. for s in [_ for _ in c.__subclasses__() if _ not in hier]:
  422. process.append(s)
  423. hier.add(s)
  424. return list(hier)
  425. def iterate_attributes(cls):
  426. """iterate all the keys and attributes associated
  427. with a class, without using getattr().
  428. Does not use getattr() so that class-sensitive
  429. descriptors (i.e. property.__get__()) are not called.
  430. """
  431. keys = dir(cls)
  432. for key in keys:
  433. for c in cls.__mro__:
  434. if key in c.__dict__:
  435. yield (key, c.__dict__[key])
  436. break
  437. # from paste.deploy.converters
  438. def asbool(obj):
  439. if isinstance(obj, (str, unicode)):
  440. obj = obj.strip().lower()
  441. if obj in ['true', 'yes', 'on', 'y', 't', '1']:
  442. return True
  443. elif obj in ['false', 'no', 'off', 'n', 'f', '0']:
  444. return False
  445. else:
  446. raise ValueError("String is not true/false: %r" % obj)
  447. return bool(obj)
  448. def coerce_kw_type(kw, key, type_, flexi_bool=True):
  449. """If 'key' is present in dict 'kw', coerce its value to type 'type\_' if
  450. necessary. If 'flexi_bool' is True, the string '0' is considered false
  451. when coercing to boolean.
  452. """
  453. if key in kw and type(kw[key]) is not type_ and kw[key] is not None:
  454. if type_ is bool and flexi_bool:
  455. kw[key] = asbool(kw[key])
  456. else:
  457. kw[key] = type_(kw[key])
  458. def duck_type_collection(specimen, default=None):
  459. """Given an instance or class, guess if it is or is acting as one of
  460. the basic collection types: list, set and dict. If the __emulates__
  461. property is present, return that preferentially.
  462. """
  463. if hasattr(specimen, '__emulates__'):
  464. # canonicalize set vs sets.Set to a standard: the builtin set
  465. if (specimen.__emulates__ is not None and
  466. issubclass(specimen.__emulates__, set_types)):
  467. return set
  468. else:
  469. return specimen.__emulates__
  470. isa = isinstance(specimen, type) and issubclass or isinstance
  471. if isa(specimen, list):
  472. return list
  473. elif isa(specimen, set_types):
  474. return set
  475. elif isa(specimen, dict):
  476. return dict
  477. if hasattr(specimen, 'append'):
  478. return list
  479. elif hasattr(specimen, 'add'):
  480. return set
  481. elif hasattr(specimen, 'set'):
  482. return dict
  483. else:
  484. return default
  485. def dictlike_iteritems(dictlike):
  486. """Return a (key, value) iterator for almost any dict-like object."""
  487. # Py3K
  488. #if hasattr(dictlike, 'items'):
  489. # return dictlike.items()
  490. # Py2K
  491. if hasattr(dictlike, 'iteritems'):
  492. return dictlike.iteritems()
  493. elif hasattr(dictlike, 'items'):
  494. return iter(dictlike.items())
  495. # end Py2K
  496. getter = getattr(dictlike, '__getitem__', getattr(dictlike, 'get', None))
  497. if getter is None:
  498. raise TypeError(
  499. "Object '%r' is not dict-like" % dictlike)
  500. if hasattr(dictlike, 'iterkeys'):
  501. def iterator():
  502. for key in dictlike.iterkeys():
  503. yield key, getter(key)
  504. return iterator()
  505. elif hasattr(dictlike, 'keys'):
  506. return iter((key, getter(key)) for key in dictlike.keys())
  507. else:
  508. raise TypeError(
  509. "Object '%r' is not dict-like" % dictlike)
  510. def assert_arg_type(arg, argtype, name):
  511. if isinstance(arg, argtype):
  512. return arg
  513. else:
  514. if isinstance(argtype, tuple):
  515. raise exc.ArgumentError(
  516. "Argument '%s' is expected to be one of type %s, got '%s'" %
  517. (name, ' or '.join("'%s'" % a for a in argtype), type(arg)))
  518. else:
  519. raise exc.ArgumentError(
  520. "Argument '%s' is expected to be of type '%s', got '%s'" %
  521. (name, argtype, type(arg)))
  522. _creation_order = 1
  523. def set_creation_order(instance):
  524. """Assign a '_creation_order' sequence to the given instance.
  525. This allows multiple instances to be sorted in order of creation
  526. (typically within a single thread; the counter is not particularly
  527. threadsafe).
  528. """
  529. global _creation_order
  530. instance._creation_order = _creation_order
  531. _creation_order +=1
  532. def warn_exception(func, *args, **kwargs):
  533. """executes the given function, catches all exceptions and converts to a warning."""
  534. try:
  535. return func(*args, **kwargs)
  536. except:
  537. warn("%s('%s') ignored" % sys.exc_info()[0:2])
  538. def monkeypatch_proxied_specials(into_cls, from_cls, skip=None, only=None,
  539. name='self.proxy', from_instance=None):
  540. """Automates delegation of __specials__ for a proxying type."""
  541. if only:
  542. dunders = only
  543. else:
  544. if skip is None:
  545. skip = ('__slots__', '__del__', '__getattribute__',
  546. '__metaclass__', '__getstate__', '__setstate__')
  547. dunders = [m for m in dir(from_cls)
  548. if (m.startswith('__') and m.endswith('__') and
  549. not hasattr(into_cls, m) and m not in skip)]
  550. for method in dunders:
  551. try:
  552. fn = getattr(from_cls, method)
  553. if not hasattr(fn, '__call__'):
  554. continue
  555. fn = getattr(fn, 'im_func', fn)
  556. except AttributeError:
  557. continue
  558. try:
  559. spec = inspect.getargspec(fn)
  560. fn_args = inspect.formatargspec(spec[0])
  561. d_args = inspect.formatargspec(spec[0][1:])
  562. except TypeError:
  563. fn_args = '(self, *args, **kw)'
  564. d_args = '(*args, **kw)'
  565. py = ("def %(method)s%(fn_args)s: "
  566. "return %(name)s.%(method)s%(d_args)s" % locals())
  567. env = from_instance is not None and {name: from_instance} or {}
  568. exec py in env
  569. try:
  570. env[method].func_defaults = fn.func_defaults
  571. except AttributeError:
  572. pass
  573. setattr(into_cls, method, env[method])
  574. class NamedTuple(tuple):
  575. """tuple() subclass that adds labeled names.
  576. Is also pickleable.
  577. """
  578. def __new__(cls, vals, labels=None):
  579. vals = list(vals)
  580. t = tuple.__new__(cls, vals)
  581. if labels:
  582. t.__dict__ = dict(itertools.izip(labels, vals))
  583. t._labels = labels
  584. return t
  585. def keys(self):
  586. return self._labels
  587. class OrderedProperties(object):
  588. """An object that maintains the order in which attributes are set upon it.
  589. Also provides an iterator and a very basic getitem/setitem
  590. interface to those attributes.
  591. (Not really a dict, since it iterates over values, not keys. Not really
  592. a list, either, since each value must have a key associated; hence there is
  593. no append or extend.)
  594. """
  595. def __init__(self):
  596. self.__dict__['_data'] = OrderedDict()
  597. def __len__(self):
  598. return len(self._data)
  599. def __iter__(self):
  600. return self._data.itervalues()
  601. def __add__(self, other):
  602. return list(self) + list(other)
  603. def __setitem__(self, key, object):
  604. self._data[key] = object
  605. def __getitem__(self, key):
  606. return self._data[key]
  607. def __delitem__(self, key):
  608. del self._data[key]
  609. def __setattr__(self, key, object):
  610. self._data[key] = object
  611. def __getstate__(self):
  612. return {'_data': self.__dict__['_data']}
  613. def __setstate__(self, state):
  614. self.__dict__['_data'] = state['_data']
  615. def __getattr__(self, key):
  616. try:
  617. return self._data[key]
  618. except KeyError:
  619. raise AttributeError(key)
  620. def __contains__(self, key):
  621. return key in self._data
  622. def update(self, value):
  623. self._data.update(value)
  624. def get(self, key, default=None):
  625. if key in self:
  626. return self[key]
  627. else:
  628. return default
  629. def keys(self):
  630. return self._data.keys()
  631. def has_key(self, key):
  632. return key in self._data
  633. def clear(self):
  634. self._data.clear()
  635. class OrderedDict(dict):
  636. """A dict that returns keys/values/items in the order they were added."""
  637. def __init__(self, ____sequence=None, **kwargs):
  638. self._list = []
  639. if ____sequence is None:
  640. if kwargs:
  641. self.update(**kwargs)
  642. else:
  643. self.update(____sequence, **kwargs)
  644. def clear(self):
  645. self._list = []
  646. dict.clear(self)
  647. def copy(self):
  648. return self.__copy__()
  649. def __copy__(self):
  650. return OrderedDict(self)
  651. def sort(self, *arg, **kw):
  652. self._list.sort(*arg, **kw)
  653. def update(self, ____sequence=None, **kwargs):
  654. if ____sequence is not None:
  655. if hasattr(____sequence, 'keys'):
  656. for key in ____sequence.keys():
  657. self.__setitem__(key, ____sequence[key])
  658. else:
  659. for key, value in ____sequence:
  660. self[key] = value
  661. if kwargs:
  662. self.update(kwargs)
  663. def setdefault(self, key, value):
  664. if key not in self:
  665. self.__setitem__(key, value)
  666. return value
  667. else:
  668. return self.__getitem__(key)
  669. def __iter__(self):
  670. return iter(self._list)
  671. def values(self):
  672. return [self[key] for key in self._list]
  673. def itervalues(self):
  674. return iter(self.values())
  675. def keys(self):
  676. return list(self._list)
  677. def iterkeys(self):
  678. return iter(self.keys())
  679. def items(self):
  680. return [(key, self[key]) for key in self.keys()]
  681. def iteritems(self):
  682. return iter(self.items())
  683. def __setitem__(self, key, object):
  684. if key not in self:
  685. try:
  686. self._list.append(key)
  687. except AttributeError:
  688. # work around Python pickle loads() with
  689. # dict subclass (seems to ignore __setstate__?)
  690. self._list = [key]
  691. dict.__setitem__(self, key, object)
  692. def __delitem__(self, key):
  693. dict.__delitem__(self, key)
  694. self._list.remove(key)
  695. def pop(self, key, *default):
  696. present = key in self
  697. value = dict.pop(self, key, *default)
  698. if present:
  699. self._list.remove(key)
  700. return value
  701. def popitem(self):
  702. item = dict.popitem(self)
  703. self._list.remove(item[0])
  704. return item
  705. class OrderedSet(set):
  706. def __init__(self, d=None):
  707. set.__init__(self)
  708. self._list = []
  709. if d is not None:
  710. self.update(d)
  711. def add(self, element):
  712. if element not in self:
  713. self._list.append(element)
  714. set.add(self, element)
  715. def remove(self, element):
  716. set.remove(self, element)
  717. self._list.remove(element)
  718. def insert(self, pos, element):
  719. if element not in self:
  720. self._list.insert(pos, element)
  721. set.add(self, element)
  722. def discard(self, element):
  723. if element in self:
  724. self._list.remove(element)
  725. set.remove(self, element)
  726. def clear(self):
  727. set.clear(self)
  728. self._list = []
  729. def __getitem__(self, key):
  730. return self._list[key]
  731. def __iter__(self):
  732. return iter(self._list)
  733. def __repr__(self):
  734. return '%s(%r)' % (self.__class__.__name__, self._list)
  735. __str__ = __repr__
  736. def update(self, iterable):
  737. add = self.add
  738. for i in iterable:
  739. add(i)
  740. return self
  741. __ior__ = update
  742. def union(self, other):
  743. result = self.__class__(self)
  744. result.update(other)
  745. return result
  746. __or__ = union
  747. def intersection(self, other):
  748. other = set(other)
  749. return self.__class__(a for a in self if a in other)
  750. __and__ = intersection
  751. def symmetric_difference(self, other):
  752. other = set(other)
  753. result = self.__class__(a for a in self if a not in other)
  754. result.update(a for a in other if a not in self)
  755. return result
  756. __xor__ = symmetric_difference
  757. def difference(self, other):
  758. other = set(other)
  759. return self.__class__(a for a in self if a not in other)
  760. __sub__ = difference
  761. def intersection_update(self, other):
  762. other = set(other)
  763. set.intersection_update(self, other)
  764. self._list = [ a for a in self._list if a in other]
  765. return self
  766. __iand__ = intersection_update
  767. def symmetric_difference_update(self, other):
  768. set.symmetric_difference_update(self, other)
  769. self._list = [ a for a in self._list if a in self]
  770. self._list += [ a for a in other._list if a in self]
  771. return self
  772. __ixor__ = symmetric_difference_update
  773. def difference_update(self, other):
  774. set.difference_update(self, other)
  775. self._list = [ a for a in self._list if a in self]
  776. return self
  777. __isub__ = difference_update
  778. class IdentitySet(object):
  779. """A set that considers only object id() for uniqueness.
  780. This strategy has edge cases for builtin types- it's possible to have
  781. two 'foo' strings in one of these sets, for example. Use sparingly.
  782. """
  783. _working_set = set
  784. def __init__(self, iterable=None):
  785. self._members = dict()
  786. if iterable:
  787. for o in iterable:
  788. self.add(o)
  789. def add(self, value):
  790. self._members[id(value)] = value
  791. def __contains__(self, value):
  792. return id(value) in self._members
  793. def remove(self, value):
  794. del self._members[id(value)]
  795. def discard(self, value):
  796. try:
  797. self.remove(value)
  798. except KeyError:
  799. pass
  800. def pop(self):
  801. try:
  802. pair = self._members.popitem()
  803. return pair[1]
  804. except KeyError:
  805. raise KeyError('pop from an empty set')
  806. def clear(self):
  807. self._members.clear()
  808. def __cmp__(self, other):
  809. raise TypeError('cannot compare sets using cmp()')
  810. def __eq__(self, other):
  811. if isinstance(other, IdentitySet):
  812. return self._members == other._members
  813. else:
  814. return False
  815. def __ne__(self, other):
  816. if isinstance(other, IdentitySet):
  817. return self._members != other._members
  818. else:
  819. return True
  820. def issubset(self, iterable):
  821. other = type(self)(iterable)
  822. if len(self) > len(other):
  823. return False
  824. for m in itertools.ifilterfalse(other._members.__contains__,
  825. self._members.iterkeys()):
  826. return False
  827. return True
  828. def __le__(self, other):
  829. if not isinstance(other, IdentitySet):
  830. return NotImplemented
  831. return self.issubset(other)
  832. def __lt__(self, other):
  833. if not isinstance(other, IdentitySet):
  834. return NotImplemented
  835. return len(self) < len(other) and self.issubset(other)
  836. def issuperset(self, iterable):
  837. other = type(self)(iterable)
  838. if len(self) < len(other):
  839. return False
  840. for m in itertools.ifilterfalse(self._members.__contains__,
  841. other._members.iterkeys()):
  842. return False
  843. return True
  844. def __ge__(self, other):
  845. if not isinstance(other, IdentitySet):
  846. return NotImplemented
  847. return self.issuperset(other)
  848. def __gt__(self, other):
  849. if not isinstance(other, IdentitySet):
  850. return NotImplemented
  851. return len(self) > len(other) and self.issuperset(other)
  852. def union(self, iterable):
  853. result = type(self)()
  854. # testlib.pragma exempt:__hash__
  855. result._members.update(
  856. self._working_set(self._member_id_tuples()).union(_iter_id(iterable)))
  857. return result
  858. def __or__(self, other):
  859. if not isinstance(other, IdentitySet):
  860. return NotImplemented
  861. return self.union(other)
  862. def update(self, iterable):
  863. self._members = self.union(iterable)._members
  864. def __ior__(self, other):
  865. if not isinstance(other, IdentitySet):
  866. return NotImplemented
  867. self.update(other)
  868. return self
  869. def difference(self, iterable):
  870. result = type(self)()
  871. # testlib.pragma exempt:__hash__
  872. result._members.update(
  873. self._working_set(self._member_id_tuples()).difference(_iter_id(iterable)))
  874. return result
  875. def __sub__(self, other):
  876. if not isinstance(other, IdentitySet):
  877. return NotImplemented
  878. return self.difference(other)
  879. def difference_update(self, iterable):
  880. self._members = self.difference(iterable)._members
  881. def __isub__(self, other):
  882. if not isinstance(other, IdentitySet):
  883. return NotImplemented
  884. self.difference_update(other)
  885. return self
  886. def intersection(self, iterable):
  887. result = type(self)()
  888. # testlib.pragma exempt:__hash__
  889. result._members.update(
  890. self._working_set(self._member_id_tuples()).intersection(_iter_id(iterable)))
  891. return result
  892. def __and__(self, other):
  893. if not isinstance(other, IdentitySet):
  894. return NotImplemented
  895. return self.intersection(other)
  896. def intersection_update(self, iterable):
  897. self._members = self.intersection(iterable)._members
  898. def __iand__(self, other):
  899. if not isinstance(other, IdentitySet):
  900. return NotImplemented
  901. self.intersection_update(other)
  902. return self
  903. def symmetric_difference(self, iterable):
  904. result = type(self)()
  905. # testlib.pragma exempt:__hash__
  906. result._members.update(
  907. self._working_set(self._member_id_tuples()).symmetric_difference(_iter_id(iterable)))
  908. return result
  909. def _member_id_tuples(self):
  910. return ((id(v), v) for v in self._members.itervalues())
  911. def __xor__(self, other):
  912. if not isinstance(other, IdentitySet):
  913. return NotImplemented
  914. return self.symmetric_difference(other)
  915. def symmetric_difference_update(self, iterable):
  916. self._members = self.symmetric_difference(iterable)._members
  917. def __ixor__(self, other):
  918. if not isinstance(other, IdentitySet):
  919. return NotImplemented
  920. self.symmetric_difference(other)
  921. return self
  922. def copy(self):
  923. return type(self)(self._members.itervalues())
  924. __copy__ = copy
  925. def __len__(self):
  926. return len(self._members)
  927. def __iter__(self):
  928. return self._members.itervalues()
  929. def __hash__(self):
  930. raise TypeError('set objects are unhashable')
  931. def __repr__(self):
  932. return '%s(%r)' % (type(self).__name__, self._members.values())
  933. class OrderedIdentitySet(IdentitySet):
  934. class _working_set(OrderedSet):
  935. # a testing pragma: exempt the OIDS working set from the test suite's
  936. # "never call the user's __hash__" assertions. this is a big hammer,
  937. # but it's safe here: IDS operates on (id, instance) tuples in the
  938. # working set.
  939. __sa_hash_exempt__ = True
  940. def __init__(self, iterable=None):
  941. IdentitySet.__init__(self)
  942. self._members = OrderedDict()
  943. if iterable:
  944. for o in iterable:
  945. self.add(o)
  946. def _iter_id(iterable):
  947. """Generator: ((id(o), o) for o in iterable)."""
  948. for item in iterable:
  949. yield id(item), item
  950. # define collections that are capable of storing
  951. # ColumnElement objects as hashable keys/elements.
  952. column_set = set
  953. column_dict = dict
  954. ordered_column_set = OrderedSet
  955. populate_column_dict = PopulateDict
  956. def unique_list(seq, compare_with=set):
  957. seen = compare_with()
  958. return [x for x in seq if x not in seen and not seen.add(x)]
  959. class UniqueAppender(object):
  960. """Appends items to a collection ensuring uniqueness.
  961. Additional appends() of the same object are ignored. Membership is
  962. determined by identity (``is a``) not equality (``==``).
  963. """
  964. def __init__(self, data, via=None):
  965. self.data = data
  966. self._unique = IdentitySet()
  967. if via:
  968. self._data_appender = getattr(data, via)
  969. elif hasattr(data, 'append'):
  970. self._data_appender = data.append
  971. elif hasattr(data, 'add'):
  972. # TODO: we think its a set here. bypass unneeded uniquing logic ?
  973. self._data_appender = data.add
  974. def append(self, item):
  975. if item not in self._unique:
  976. self._data_appender(item)
  977. self._unique.add(item)
  978. def __iter__(self):
  979. return iter(self.data)
  980. class ScopedRegistry(object):
  981. """A Registry that can store one or multiple instances of a single
  982. class on a per-thread scoped basis, or on a customized scope.
  983. createfunc
  984. a callable that returns a new object to be placed in the registry
  985. scopefunc
  986. a callable that will return a key to store/retrieve an object.
  987. """
  988. def __init__(self, createfunc, scopefunc):
  989. self.createfunc = createfunc
  990. self.scopefunc = scopefunc
  991. self.registry = {}
  992. def __call__(self):
  993. key = self.scopefunc()
  994. try:
  995. return self.registry[key]
  996. except KeyError:
  997. return self.registry.setdefault(key, self.createfunc())
  998. def has(self):
  999. return self.scopefunc() in self.registry
  1000. def set(self, obj):
  1001. self.registry[self.scopefunc()] = obj
  1002. def clear(self):
  1003. try:
  1004. del self.registry[self.scopefunc()]
  1005. except KeyError:
  1006. pass
  1007. class ThreadLocalRegistry(ScopedRegistry):
  1008. def __init__(self, createfunc):
  1009. self.createfunc = createfunc
  1010. self.registry = threading.local()
  1011. def __call__(self):
  1012. try:
  1013. return self.registry.value
  1014. except AttributeError:
  1015. val = self.registry.value = self.createfunc()
  1016. return val
  1017. def has(self):
  1018. return hasattr(self.registry, "value")
  1019. def set(self, obj):
  1020. self.registry.value = obj
  1021. def clear(self):
  1022. try:
  1023. del self.registry.value
  1024. except AttributeError:
  1025. pass
  1026. class _symbol(object):
  1027. def __init__(self, name):
  1028. """Construct a new named symbol."""
  1029. assert isinstance(name, str)
  1030. self.name = name
  1031. def __reduce__(self):
  1032. return symbol, (self.name,)
  1033. def __repr__(self):
  1034. return "<symbol '%s>" % self.name
  1035. _symbol.__name__ = 'symbol'
  1036. class symbol(object):
  1037. """A constant symbol.
  1038. >>> symbol('foo') is symbol('foo')
  1039. True
  1040. >>> symbol('foo')
  1041. <symbol 'foo>
  1042. A slight refinement of the MAGICCOOKIE=object() pattern. The primary
  1043. advantage of symbol() is its repr(). They are also singletons.
  1044. Repeated calls of symbol('name') will all return the same instance.
  1045. """
  1046. symbols = {}
  1047. _lock = threading.Lock()
  1048. def __new__(cls, name):
  1049. cls._lock.acquire()
  1050. try:
  1051. sym = cls.symbols.get(name)
  1052. if sym is None:
  1053. cls.symbols[name] = sym = _symbol(name)
  1054. return sym
  1055. finally:
  1056. symbol._lock.release()
  1057. def as_interface(obj, cls=None, methods=None, required=None):
  1058. """Ensure basic interface compliance for an instance or dict of callables.
  1059. Checks that ``obj`` implements public methods of ``cls`` or has members
  1060. listed in ``methods``. If ``required`` is not supplied, implementing at
  1061. least one interface method is sufficient. Methods present on ``obj`` that
  1062. are not in the interface are ignored.
  1063. If ``obj`` is a dict and ``dict`` does not meet the interface
  1064. requirements, the keys of the dictionary are inspected. Keys present in
  1065. ``obj`` that are not in the interface will raise TypeErrors.
  1066. Raises TypeError if ``obj`` does not meet the interface criteria.
  1067. In all passing cases, an object with callable members is returned. In the
  1068. simple case, ``obj`` is returned as-is; if dict processing kicks in then
  1069. an anonymous class is returned.
  1070. obj
  1071. A type, instance, or dictionary of callables.
  1072. cls
  1073. Optional, a type. All public methods of cls are considered the
  1074. interface. An ``obj`` instance of cls will always pass, ignoring
  1075. ``required``..
  1076. methods
  1077. Optional, a sequence of method names to consider as the interface.
  1078. required
  1079. Optional, a sequence of mandatory implementations. If omitted, an
  1080. ``obj`` that provides at least one interface method is considered
  1081. sufficient. As a convenience, required may be a type, in which case
  1082. all public methods of the type are required.
  1083. """
  1084. if not cls and not methods:
  1085. raise TypeError('a class or collection of method names are required')
  1086. if isinstance(cls, type) and isinstance(obj, cls):
  1087. return obj
  1088. interface = set(methods or [m for m in dir(cls) if not m.startswith('_')])
  1089. implemented = set(dir(obj))
  1090. complies = operator.ge
  1091. if isinstance(required, type):
  1092. required = interface
  1093. elif not required:
  1094. required = set()
  1095. complies = operator.gt
  1096. else:
  1097. required = set(required)
  1098. if complies(implemented.intersection(interface), required):
  1099. return obj
  1100. # No dict duck typing here.
  1101. if not type(obj) is dict:
  1102. qualifier = complies is operator.gt and 'any of' or 'all of'
  1103. raise TypeError("%r does not implement %s: %s" % (
  1104. obj, qualifier, ', '.join(interface)))
  1105. class AnonymousInterface(object):
  1106. """A callable-holding shell."""
  1107. if cls:
  1108. AnonymousInterface.__name__ = 'Anonymous' + cls.__name__
  1109. found = set()
  1110. for method, impl in dictlike_iteritems(obj):
  1111. if method not in interface:
  1112. raise TypeError("%r: unknown in this interface" % method)
  1113. if not callable(impl):
  1114. raise TypeError("%r=%r is not callable" % (method, impl))
  1115. setattr(AnonymousInterface, method, staticmethod(impl))
  1116. found.add(method)
  1117. if complies(found, required):
  1118. return AnonymousInterface
  1119. raise TypeError("dictionary does not contain required keys %s" %
  1120. ', '.join(required - found))
  1121. def function_named(fn, name):
  1122. """Return a function with a given __name__.
  1123. Will assign to __name__ and return the original function if possible on
  1124. the Python implementation, otherwise a new function will be constructed.
  1125. """
  1126. try:
  1127. fn.__name__ = name
  1128. except TypeError:
  1129. fn = types.FunctionType(fn.func_code, fn.func_globals, name,
  1130. fn.func_defaults, fn.func_closure)
  1131. return fn
  1132. class memoized_property(object):
  1133. """A read-only @property that is only evaluated once."""
  1134. def __init__(self, fget, doc=None):
  1135. self.fget = fget
  1136. self.__doc__ = doc or fget.__doc__
  1137. self.__name__ = fget.__name__
  1138. def __get__(self, obj, cls):
  1139. if obj is None:
  1140. return None
  1141. obj.__dict__[self.__name__] = result = self.fget(obj)
  1142. return result
  1143. class memoized_instancemethod(object):
  1144. """Decorate a method memoize its return value.
  1145. Best applied to no-arg methods: memoization is not sensitive to
  1146. argument values, and will always return the same value even when
  1147. called with different arguments.
  1148. """
  1149. def __init__(self, fget, doc=None):
  1150. self.fget = fget
  1151. self.__doc__ = doc or fget.__doc__
  1152. self.__name__ = fget.__name__
  1153. def __get__(self, obj, cls):
  1154. if obj is None:
  1155. return None
  1156. def oneshot(*args, **kw):
  1157. result = self.fget(obj, *args, **kw)
  1158. memo = lambda *a, **kw: result
  1159. memo.__name__ = self.__name__
  1160. memo.__doc__ = self.__doc__
  1161. obj.__dict__[self.__name__] = memo
  1162. return result
  1163. oneshot.__name__ = self.__name__
  1164. oneshot.__doc__ = self.__doc__
  1165. return oneshot
  1166. def reset_memoized(instance, name):
  1167. instance.__dict__.pop(name, None)
  1168. class WeakIdentityMapping(weakref.WeakKeyDictionary):
  1169. """A WeakKeyDictionary with an object identity index.
  1170. Adds a .by_id dictionary to a regular WeakKeyDictionary. Trades
  1171. performance during mutation operations for accelerated lookups by id().
  1172. The usual cautions about weak dictionaries and iteration also apply to
  1173. this subclass.
  1174. """
  1175. _none = symbol('none')
  1176. def __init__(self):
  1177. weakref.WeakKeyDictionary.__init__(self)
  1178. self.by_id = {}
  1179. self._weakrefs = {}
  1180. def __setitem__(self, object, value):
  1181. oid = id(object)
  1182. self.by_id[oid] = value
  1183. if oid not in self._weakrefs:
  1184. self._weakrefs[oid] = self._ref(object)
  1185. weakref.WeakKeyDictionary.__setitem__(self, object, value)
  1186. def __delitem__(self, object):
  1187. del self._weakrefs[id(object)]
  1188. del self.by_id[id(object)]
  1189. weakref.WeakKeyDictionary.__delitem__(self, object)
  1190. def setdefault(self, object, default=None):
  1191. value = weakref.WeakKeyDictionary.setdefault(self, object, default)
  1192. oid = id(object)
  1193. if value is default:
  1194. self.by_id[oid] = default
  1195. if oid not in self._weakrefs:
  1196. self._weakrefs[oid] = self._ref(object)
  1197. return value
  1198. def pop(self, object, default=_none):
  1199. if default is self._none:
  1200. value = weakref.WeakKeyDictionary.pop(self, object)
  1201. else:
  1202. value = weakref.WeakKeyDictionary.pop(self, object, default)
  1203. if id(object) in self.by_id:
  1204. del self._weakrefs[id(object)]
  1205. del self.by_id[id(object)]
  1206. return value
  1207. def popitem(self):
  1208. item = weakref.WeakKeyDictionary.popitem(self)
  1209. oid = id(item[0])
  1210. del self._weakrefs[oid]
  1211. del self.by_id[oid]
  1212. return item
  1213. def clear(self):
  1214. # Py2K
  1215. # in 3k, MutableMapping calls popitem()
  1216. self._weakrefs.clear()
  1217. self.by_id.clear()
  1218. # end Py2K
  1219. weakref.WeakKeyDictionary.clear(self)
  1220. def update(self, *a, **kw):
  1221. raise NotImplementedError
  1222. def _cleanup(self, wr, key=None):
  1223. if key is None:
  1224. key = wr.key
  1225. try:
  1226. del self._weakrefs[key]
  1227. except (KeyError, AttributeError): # pragma: no cover
  1228. pass # pragma: no cover
  1229. try:
  1230. del self.by_id[key]
  1231. except (KeyError, AttributeError): # pragma: no cover
  1232. pass # pragma: no cover
  1233. class _keyed_weakref(weakref.ref):
  1234. def __init__(self, object, callback):
  1235. weakref.ref.__init__(self, object, callback)
  1236. self.key = id(object)
  1237. def _ref(self, object):
  1238. return self._keyed_weakref(object, self._cleanup)
  1239. import time
  1240. if win32 or jython:
  1241. time_func = time.clock
  1242. else:
  1243. time_func = time.time
  1244. class LRUCache(dict):
  1245. """Dictionary with 'squishy' removal of least
  1246. recently used items.
  1247. """
  1248. def __init__(self, capacity=100, threshold=.5):
  1249. self.capacity = capacity
  1250. self.threshold = threshold
  1251. def __getitem__(self, key):
  1252. item = dict.__getitem__(self, key)
  1253. item[2] = time_func()
  1254. return item[1]
  1255. def values(self):
  1256. return [i[1] for i in dict.values(self)]
  1257. def setdefault(self, key, value):
  1258. if key in self:
  1259. return self[key]
  1260. else:
  1261. self[key] = value
  1262. return value
  1263. def __setitem__(self, key, value):
  1264. item = dict.get(self, key)
  1265. if item is None:
  1266. item = [key, value, time_func()]
  1267. dict.__setitem__(self, key, item)
  1268. else:
  1269. item[1] = value
  1270. self._manage_size()
  1271. def _manage_size(self):
  1272. while len(self) > self.capacity + self.capacity * self.threshold:
  1273. bytime = sorted(dict.values(self),
  1274. key=operator.itemgetter(2),
  1275. reverse=True)
  1276. for item in bytime[self.capacity:]:
  1277. try:
  1278. del self[item[0]]
  1279. except KeyError:
  1280. # if we couldnt find a key, most
  1281. # likely some other thread broke in
  1282. # on us. loop around and try again
  1283. break
  1284. def warn(msg, stacklevel=3):
  1285. if isinstance(msg, basestring):
  1286. warnings.warn(msg, exc.SAWarning, stacklevel=stacklevel)
  1287. else:
  1288. warnings.warn(msg, stacklevel=stacklevel)
  1289. def warn_deprecated(msg, stacklevel=3):
  1290. warnings.warn(msg, exc.SADeprecationWarning, stacklevel=stacklevel)
  1291. def warn_pending_deprecation(msg, stacklevel=3):
  1292. warnings.warn(msg, exc.SAPendingDeprecationWarning, stacklevel=stacklevel)
  1293. def deprecated(message=None, add_deprecation_to_docstring=True):
  1294. """Decorates a function and issues a deprecation warning on use.
  1295. message
  1296. If provided, issue message in the warning. A sensible default
  1297. is used if not provided.
  1298. add_deprecation_to_docstring
  1299. Default True. If False, the wrapped function's __doc__ is left
  1300. as-is. If True, the 'message' is prepended to the docs if
  1301. provided, or sensible default if message is omitted.
  1302. """
  1303. if add_deprecation_to_docstring:
  1304. header = message is not None and message or 'Deprecated.'
  1305. else:
  1306. header = None
  1307. if message is None:
  1308. message = "Call to deprecated function %(func)s"
  1309. def decorate(fn):
  1310. return _decorate_with_warning(
  1311. fn, exc.SADeprecationWarning,
  1312. message % dict(func=fn.__name__), header)
  1313. return decorate
  1314. def pending_deprecation(version, message=None,
  1315. add_deprecation_to_docstring=True):
  1316. """Decorates a function and issues a pending deprecation warning on use.
  1317. version
  1318. An approximate future version at which point the pending deprecation
  1319. will become deprecated. Not used in messaging.
  1320. message
  1321. If provided, issue message in the warning. A sensible default
  1322. is used if not provided.
  1323. add_deprecation_to_docstring
  1324. Default True. If False, the wrapped function's __doc__ is left
  1325. as-is. If True, the 'message' is prepended to the docs if
  1326. provided, or sensible default if message is omitted.
  1327. """
  1328. if add_deprecation_to_docst