Debian Codegraph @

collections_extended/_util.py

raw
1 """util functions for collections_extended."""
2 from functools import wraps
3 import textwrap
4 import warnings
5
6 __all__ = ('hash_iterable', 'deprecated', 'deprecation_warning')
7
8
9 def hash_iterable(it):
10 """Perform a O(1) memory hash of an iterable of arbitrary length.
11
12 hash(tuple(it)) creates a temporary tuple containing all values from it
13 which could be a problem if it is large.
14
15 See discussion at:
16 https://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ
17 """
18 hash_value = hash(type(it))
19 for value in it:
20 hash_value = hash((hash_value, value))
21 return hash_value
22
23
24 def deprecation_warning(msg):
25 """Raise a deprecation warning."""
26 warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
27
28
29 def deprecated(msg, dep_version):
30 """Decorate a function, method or class to mark as deprecated.
31
32 Raise DeprecationWarning and add a deprecation notice to the docstring.
33
34 Args:
35 msg: The message to document
36 dep_version: The version in which this was deprecated
37 See:
38 https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-deprecated
39
40 """
41 def wrapper(func):
42 docstring = func.__doc__ or ''
43 docstring_msg = '.. deprecated:: {version} {msg}'.format(
44 version=dep_version,
45 msg=msg,
46 )
47 if docstring:
48 # We don't know how far to indent this message
49 # so instead we just dedent everything.
50 string_list = docstring.splitlines()
51 first_line = string_list[0]
52 remaining = textwrap.dedent(''.join(string_list[1:]))
53 docstring = '\n'.join([
54 first_line,
55 remaining,
56 '',
57 docstring_msg,
58 ])
59 else:
60 docstring = docstring_msg
61 func.__doc__ = docstring
62
63 @wraps(func)
64 def inner(*args, **kwargs):
65 deprecation_warning(msg)
66 return func(*args, **kwargs)
67
68 return inner
69
70 return wrapper