import contextlib, sys
__all__ = ['formatDocstring', 'maxrecursion', 'translateKwds', 'unique']
# The recursive-descent processing of ICurry necessitates a larger recursion
# limit. Since Python 3.12 the limit counts only Python frames; the C stack is
# guarded separately, so a large limit no longer risks a SEGV from pure-Python
# recursion. This value is still a compromise against runaway recursion.
MAX_RECURSION_LIMIT = 1<<14
[docs]
@contextlib.contextmanager
def maxrecursion(limit=MAX_RECURSION_LIMIT):
prevlimit = sys.getrecursionlimit()
try:
sys.setrecursionlimit(limit)
yield
finally:
sys.setrecursionlimit(prevlimit)
[docs]
def translateKwds(kwmap):
'''
For compatibility. This decorator can be used to translate old argument
names to new ones.
'''
def dec(f):
def replacement(*args, **kwds):
for name in kwmap:
if name in kwds:
kwds[kwmap[name]] = kwds.pop(name)
return f(*args, **kwds)
return replacement
return dec
[docs]
def unique(iterator, key=lambda x: x):
'''Transform an iterator to filter out duplicate items.'''
seen = set()
for x in iterator:
k = key(x)
if k not in seen:
seen.add(k)
yield x