pax_global_header00006660000000000000000000000064141375430640014521gustar00rootroot0000000000000052 comment=19bd102e32a501e7e3041194a448cd37e50fec03 jaraco.functools-3.4.0/000077500000000000000000000000001413754306400147775ustar00rootroot00000000000000jaraco.functools-3.4.0/.coveragerc000066400000000000000000000001431413754306400171160ustar00rootroot00000000000000[run] omit = # leading `*/` for pytest-dev/pytest-cov#456 */.tox/* [report] show_missing = True jaraco.functools-3.4.0/.editorconfig000066400000000000000000000003301413754306400174500ustar00rootroot00000000000000root = true [*] charset = utf-8 indent_style = tab indent_size = 4 insert_final_newline = true end_of_line = lf [*.py] indent_style = space max_line_length = 88 [*.{yml,yaml}] indent_style = space indent_size = 2 jaraco.functools-3.4.0/.flake8000066400000000000000000000002101413754306400161430ustar00rootroot00000000000000[flake8] max-line-length = 88 # jaraco/skeleton#34 max-complexity = 10 extend-ignore = # Black creates whitespace before colon E203 jaraco.functools-3.4.0/.github/000077500000000000000000000000001413754306400163375ustar00rootroot00000000000000jaraco.functools-3.4.0/.github/dependabot.yml000066400000000000000000000002241413754306400211650ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "pip" directory: "/" schedule: interval: "daily" allow: - dependency-type: "all" jaraco.functools-3.4.0/.github/workflows/000077500000000000000000000000001413754306400203745ustar00rootroot00000000000000jaraco.functools-3.4.0/.github/workflows/main.yml000066400000000000000000000021001413754306400220340ustar00rootroot00000000000000name: tests on: [push, pull_request] jobs: test: strategy: matrix: python: - 3.6 - 3.9 - "3.10" platform: - ubuntu-latest - macos-latest - windows-latest runs-on: ${{ matrix.platform }} steps: - uses: actions/checkout@v2 - name: Setup Python uses: actions/setup-python@v2 with: python-version: ${{ matrix.python }} - name: Install tox run: | python -m pip install tox - name: Run tests run: tox release: needs: test if: github.event_name == 'push' && contains(github.ref, 'refs/tags/') runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Setup Python uses: actions/setup-python@v2 with: python-version: "3.10" - name: Install tox run: | python -m pip install tox - name: Release run: tox -e release env: TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} jaraco.functools-3.4.0/.pre-commit-config.yaml000066400000000000000000000001211413754306400212520ustar00rootroot00000000000000repos: - repo: https://github.com/psf/black rev: 20.8b1 hooks: - id: black jaraco.functools-3.4.0/.readthedocs.yml000066400000000000000000000001171413754306400200640ustar00rootroot00000000000000version: 2 python: install: - path: . extra_requirements: - docs jaraco.functools-3.4.0/CHANGES.rst000066400000000000000000000050001413754306400165740ustar00rootroot00000000000000v3.4.0 ====== ``apply`` now uses ``functools.wraps`` to ensure docstring passthrough. v3.3.0 ====== #18: In method_cache, support cache_clear before cache is initialized. v3.2.1 ====== Refreshed package metadata. v3.2.0 ====== Switched to PEP 420 for ``jaraco`` namespace. v3.1.0 ====== Added ``except_`` decorator. v3.0.1 ====== #14: Removed unnecessary compatibility libraries in testing. v3.0.0 ====== Require Python 3.6 or later. 2.0 === Switch to `pkgutil namespace technique `_ for the ``jaraco`` namespace. 1.20 ==== Added ``save_method_args``, adopted from ``irc.functools``. 1.19 ==== Added ``.reset`` support to ``once``. 1.18 ==== Add ``result_invoke`` decorator. 1.17 ==== Add ``retry`` decorator. 1.16 ==== #7: ``retry_call`` now accepts infinity for the ``retries`` parameter. 1.15.2 ====== Refresh packaging. 1.15.1 ====== Fix assign_params on Python 2. 1.15 ==== Add ``assign_params`` function. 1.14 ==== Add ``pass_none`` decorator function. 1.13 ==== Add ``print_yielded`` func implementing the func of the same name found in autocommand docs. 1.12 ==== Issue #6: Added a bit of documentation and xfail tests showing that the ``method_cache`` can't be used with other decorators such as ``property``. 1.11 ==== Include dates and links in changelog. 1.10 ==== Use Github for continuous deployment to PyPI. 1.9 === Add ``retry_call``, a general-purpose function retry mechanism. See ``test_functools`` for tests and example usage. 1.8 === More generous handling of missing lru_cache when installed on Python 2 and older pip. Now all functools except ``method_cache`` will continue to work even if ``backports.functools_lru_cache`` is not installed. Also allows functools32 as a fallback if available. 1.7 === Moved hosting to github. 1.6 === ``method_cache`` now accepts a cache_wrapper parameter, allowing for custom parameters to an ``lru_cache`` or an entirely different cache implementation. Use ``backports.functools_lru_cache`` to provide ``lru_cache`` for Python 2. 1.5 === Implement ``Throttler`` as a descriptor so it may be used to decorate methods. Introduces ``first_invoke`` function. Fixed failure in Throttler on Python 2 due to improper use of integer division. 1.4 === Added ``Throttler`` class from `irc `_. 1.3 === Added ``call_aside`` decorator. 1.2 === Added ``apply`` decorator. 1.0 === Initial release drawn from jaraco.util. jaraco.functools-3.4.0/LICENSE000066400000000000000000000020321413754306400160010ustar00rootroot00000000000000Copyright Jason R. Coombs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. jaraco.functools-3.4.0/README.rst000066400000000000000000000017211413754306400164670ustar00rootroot00000000000000.. image:: https://img.shields.io/pypi/v/jaraco.functools.svg :target: `PyPI link`_ .. image:: https://img.shields.io/pypi/pyversions/jaraco.functools.svg .. image:: https://img.shields.io/travis/jaraco/jaraco.functools/master.svg :target: `PyPI link`_ .. _PyPI link: https://pypi.org/project/jaraco.functools .. image:: https://github.com/jaraco/jaraco.functools/workflows/tests/badge.svg :target: https://github.com/jaraco/jaraco.functools/actions?query=workflow%3A%22tests%22 :alt: tests .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/psf/black :alt: Code style: Black .. image:: https://readthedocs.org/projects/jaracofunctools/badge/?version=latest :target: https://jaracofunctools.readthedocs.io/en/latest/?badge=latest .. image:: https://img.shields.io/badge/skeleton-2021-informational :target: https://blog.jaraco.com/skeleton Additional functools in the spirit of stdlib's functools. jaraco.functools-3.4.0/conftest.py000066400000000000000000000012361413754306400172000ustar00rootroot00000000000000import sys import re import jaraco.functools def pytest_configure(): patch_for_issue_12() def patch_for_issue_12(): # pragma: nocover """ Issue #12 revealed that Python 3.7.3 had a subtle change in the C implementation of functools that broke the assumptions around the method_cache (or any caller using possibly empty keyword arguments). This patch adjusts the docstring for that test so it can pass on that Python version. """ affected_ver = 3, 7, 3 if sys.version_info[:3] != affected_ver: return mc = jaraco.functools.method_cache mc.__doc__ = re.sub(r'^(\s+)75', r'\g<1>76', mc.__doc__, flags=re.M) jaraco.functools-3.4.0/docs/000077500000000000000000000000001413754306400157275ustar00rootroot00000000000000jaraco.functools-3.4.0/docs/conf.py000066400000000000000000000017631413754306400172350ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- extensions = ['sphinx.ext.autodoc', 'jaraco.packaging.sphinx', 'rst.linker'] master_doc = "index" link_files = { '../CHANGES.rst': dict( using=dict(GH='https://github.com'), replace=[ dict( pattern=r'(Issue #|\B#)(?P\d+)', url='{package_url}/issues/{issue}', ), dict( pattern=r'(?m:^((?Pv?\d+(\.\d+){1,2}))\n[-=]+\n)', with_scm='{text}\n{rev[timestamp]:%d %b %Y}\n', ), dict( pattern=r'PEP[- ](?P\d+)', url='https://www.python.org/dev/peps/pep-{pep_number:0>4}/', ), ], ) } # Be strict about any broken references: nitpicky = True # Include Python intersphinx mapping to prevent failures # jaraco/skeleton#51 extensions += ['sphinx.ext.intersphinx'] intersphinx_mapping = { 'python': ('https://docs.python.org/3', None), } jaraco.functools-3.4.0/docs/history.rst000066400000000000000000000001211413754306400201540ustar00rootroot00000000000000:tocdepth: 2 .. _changes: History ******* .. include:: ../CHANGES (links).rst jaraco.functools-3.4.0/docs/index.rst000066400000000000000000000004541413754306400175730ustar00rootroot00000000000000Welcome to |project| documentation! =================================== .. toctree:: :maxdepth: 1 history .. automodule:: jaraco.functools :members: :undoc-members: :show-inheritance: Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` jaraco.functools-3.4.0/jaraco/000077500000000000000000000000001413754306400162365ustar00rootroot00000000000000jaraco.functools-3.4.0/jaraco/functools.py000066400000000000000000000315361413754306400206340ustar00rootroot00000000000000import functools import time import inspect import collections import types import itertools import more_itertools def compose(*funcs): """ Compose any number of unary functions into a single unary function. >>> import textwrap >>> expected = str.strip(textwrap.dedent(compose.__doc__)) >>> strip_and_dedent = compose(str.strip, textwrap.dedent) >>> strip_and_dedent(compose.__doc__) == expected True Compose also allows the innermost function to take arbitrary arguments. >>> round_three = lambda x: round(x, ndigits=3) >>> f = compose(round_three, int.__truediv__) >>> [f(3*x, x+1) for x in range(1,10)] [1.5, 2.0, 2.25, 2.4, 2.5, 2.571, 2.625, 2.667, 2.7] """ def compose_two(f1, f2): return lambda *args, **kwargs: f1(f2(*args, **kwargs)) return functools.reduce(compose_two, funcs) def method_caller(method_name, *args, **kwargs): """ Return a function that will call a named method on the target object with optional positional and keyword arguments. >>> lower = method_caller('lower') >>> lower('MyString') 'mystring' """ def call_method(target): func = getattr(target, method_name) return func(*args, **kwargs) return call_method def once(func): """ Decorate func so it's only ever called the first time. This decorator can ensure that an expensive or non-idempotent function will not be expensive on subsequent calls and is idempotent. >>> add_three = once(lambda a: a+3) >>> add_three(3) 6 >>> add_three(9) 6 >>> add_three('12') 6 To reset the stored value, simply clear the property ``saved_result``. >>> del add_three.saved_result >>> add_three(9) 12 >>> add_three(8) 12 Or invoke 'reset()' on it. >>> add_three.reset() >>> add_three(-3) 0 >>> add_three(0) 0 """ @functools.wraps(func) def wrapper(*args, **kwargs): if not hasattr(wrapper, 'saved_result'): wrapper.saved_result = func(*args, **kwargs) return wrapper.saved_result wrapper.reset = lambda: vars(wrapper).__delitem__('saved_result') return wrapper def method_cache(method, cache_wrapper=None): """ Wrap lru_cache to support storing the cache data in the object instances. Abstracts the common paradigm where the method explicitly saves an underscore-prefixed protected property on first call and returns that subsequently. >>> class MyClass: ... calls = 0 ... ... @method_cache ... def method(self, value): ... self.calls += 1 ... return value >>> a = MyClass() >>> a.method(3) 3 >>> for x in range(75): ... res = a.method(x) >>> a.calls 75 Note that the apparent behavior will be exactly like that of lru_cache except that the cache is stored on each instance, so values in one instance will not flush values from another, and when an instance is deleted, so are the cached values for that instance. >>> b = MyClass() >>> for x in range(35): ... res = b.method(x) >>> b.calls 35 >>> a.method(0) 0 >>> a.calls 75 Note that if method had been decorated with ``functools.lru_cache()``, a.calls would have been 76 (due to the cached value of 0 having been flushed by the 'b' instance). Clear the cache with ``.cache_clear()`` >>> a.method.cache_clear() Same for a method that hasn't yet been called. >>> c = MyClass() >>> c.method.cache_clear() Another cache wrapper may be supplied: >>> cache = functools.lru_cache(maxsize=2) >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache) >>> a = MyClass() >>> a.method2() 3 Caution - do not subsequently wrap the method with another decorator, such as ``@property``, which changes the semantics of the function. See also http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/ for another implementation and additional justification. """ cache_wrapper = cache_wrapper or functools.lru_cache() def wrapper(self, *args, **kwargs): # it's the first call, replace the method with a cached, bound method bound_method = types.MethodType(method, self) cached_method = cache_wrapper(bound_method) setattr(self, method.__name__, cached_method) return cached_method(*args, **kwargs) # Support cache clear even before cache has been created. wrapper.cache_clear = lambda: None return _special_method_cache(method, cache_wrapper) or wrapper def _special_method_cache(method, cache_wrapper): """ Because Python treats special methods differently, it's not possible to use instance attributes to implement the cached methods. Instead, install the wrapper method under a different name and return a simple proxy to that wrapper. https://github.com/jaraco/jaraco.functools/issues/5 """ name = method.__name__ special_names = '__getattr__', '__getitem__' if name not in special_names: return wrapper_name = '__cached' + name def proxy(self, *args, **kwargs): if wrapper_name not in vars(self): bound = types.MethodType(method, self) cache = cache_wrapper(bound) setattr(self, wrapper_name, cache) else: cache = getattr(self, wrapper_name) return cache(*args, **kwargs) return proxy def apply(transform): """ Decorate a function with a transform function that is invoked on results returned from the decorated function. >>> @apply(reversed) ... def get_numbers(start): ... "doc for get_numbers" ... return range(start, start+3) >>> list(get_numbers(4)) [6, 5, 4] >>> get_numbers.__doc__ 'doc for get_numbers' """ def wrap(func): return functools.wraps(func)(compose(transform, func)) return wrap def result_invoke(action): r""" Decorate a function with an action function that is invoked on the results returned from the decorated function (for its side-effect), then return the original result. >>> @result_invoke(print) ... def add_two(a, b): ... return a + b >>> x = add_two(2, 3) 5 >>> x 5 """ def wrap(func): @functools.wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) action(result) return result return wrapper return wrap def call_aside(f, *args, **kwargs): """ Call a function for its side effect after initialization. >>> @call_aside ... def func(): print("called") called >>> func() called Use functools.partial to pass parameters to the initial call >>> @functools.partial(call_aside, name='bingo') ... def func(name): print("called with", name) called with bingo """ f(*args, **kwargs) return f class Throttler: """ Rate-limit a function (or other callable) """ def __init__(self, func, max_rate=float('Inf')): if isinstance(func, Throttler): func = func.func self.func = func self.max_rate = max_rate self.reset() def reset(self): self.last_called = 0 def __call__(self, *args, **kwargs): self._wait() return self.func(*args, **kwargs) def _wait(self): "ensure at least 1/max_rate seconds from last call" elapsed = time.time() - self.last_called must_wait = 1 / self.max_rate - elapsed time.sleep(max(0, must_wait)) self.last_called = time.time() def __get__(self, obj, type=None): return first_invoke(self._wait, functools.partial(self.func, obj)) def first_invoke(func1, func2): """ Return a function that when invoked will invoke func1 without any parameters (for its side-effect) and then invoke func2 with whatever parameters were passed, returning its result. """ def wrapper(*args, **kwargs): func1() return func2(*args, **kwargs) return wrapper def retry_call(func, cleanup=lambda: None, retries=0, trap=()): """ Given a callable func, trap the indicated exceptions for up to 'retries' times, invoking cleanup on the exception. On the final attempt, allow any exceptions to propagate. """ attempts = itertools.count() if retries == float('inf') else range(retries) for attempt in attempts: try: return func() except trap: cleanup() return func() def retry(*r_args, **r_kwargs): """ Decorator wrapper for retry_call. Accepts arguments to retry_call except func and then returns a decorator for the decorated function. Ex: >>> @retry(retries=3) ... def my_func(a, b): ... "this is my funk" ... print(a, b) >>> my_func.__doc__ 'this is my funk' """ def decorate(func): @functools.wraps(func) def wrapper(*f_args, **f_kwargs): bound = functools.partial(func, *f_args, **f_kwargs) return retry_call(bound, *r_args, **r_kwargs) return wrapper return decorate def print_yielded(func): """ Convert a generator into a function that prints all yielded elements >>> @print_yielded ... def x(): ... yield 3; yield None >>> x() 3 None """ print_all = functools.partial(map, print) print_results = compose(more_itertools.consume, print_all, func) return functools.wraps(func)(print_results) def pass_none(func): """ Wrap func so it's not called if its first param is None >>> print_text = pass_none(print) >>> print_text('text') text >>> print_text(None) """ @functools.wraps(func) def wrapper(param, *args, **kwargs): if param is not None: return func(param, *args, **kwargs) return wrapper def assign_params(func, namespace): """ Assign parameters from namespace where func solicits. >>> def func(x, y=3): ... print(x, y) >>> assigned = assign_params(func, dict(x=2, z=4)) >>> assigned() 2 3 The usual errors are raised if a function doesn't receive its required parameters: >>> assigned = assign_params(func, dict(y=3, z=4)) >>> assigned() Traceback (most recent call last): TypeError: func() ...argument... It even works on methods: >>> class Handler: ... def meth(self, arg): ... print(arg) >>> assign_params(Handler().meth, dict(arg='crystal', foo='clear'))() crystal """ sig = inspect.signature(func) params = sig.parameters.keys() call_ns = {k: namespace[k] for k in params if k in namespace} return functools.partial(func, **call_ns) def save_method_args(method): """ Wrap a method such that when it is called, the args and kwargs are saved on the method. >>> class MyClass: ... @save_method_args ... def method(self, a, b): ... print(a, b) >>> my_ob = MyClass() >>> my_ob.method(1, 2) 1 2 >>> my_ob._saved_method.args (1, 2) >>> my_ob._saved_method.kwargs {} >>> my_ob.method(a=3, b='foo') 3 foo >>> my_ob._saved_method.args () >>> my_ob._saved_method.kwargs == dict(a=3, b='foo') True The arguments are stored on the instance, allowing for different instance to save different args. >>> your_ob = MyClass() >>> your_ob.method({str('x'): 3}, b=[4]) {'x': 3} [4] >>> your_ob._saved_method.args ({'x': 3},) >>> my_ob._saved_method.args () """ args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs') @functools.wraps(method) def wrapper(self, *args, **kwargs): attr_name = '_saved_' + method.__name__ attr = args_and_kwargs(args, kwargs) setattr(self, attr_name, attr) return method(self, *args, **kwargs) return wrapper def except_(*exceptions, replace=None, use=None): """ Replace the indicated exceptions, if raised, with the indicated literal replacement or evaluated expression (if present). >>> safe_int = except_(ValueError)(int) >>> safe_int('five') >>> safe_int('5') 5 Specify a literal replacement with ``replace``. >>> safe_int_r = except_(ValueError, replace=0)(int) >>> safe_int_r('five') 0 Provide an expression to ``use`` to pass through particular parameters. >>> safe_int_pt = except_(ValueError, use='args[0]')(int) >>> safe_int_pt('five') 'five' """ def decorate(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except exceptions: try: return eval(use) except TypeError: return replace return wrapper return decorate jaraco.functools-3.4.0/mypy.ini000066400000000000000000000000451413754306400164750ustar00rootroot00000000000000[mypy] ignore_missing_imports = True jaraco.functools-3.4.0/pyproject.toml000066400000000000000000000005461413754306400177200ustar00rootroot00000000000000[build-system] requires = ["setuptools>=56", "setuptools_scm[toml]>=3.4.1"] build-backend = "setuptools.build_meta" [tool.black] skip-string-normalization = true [tool.setuptools_scm] [pytest.enabler.black] addopts = "--black" [pytest.enabler.mypy] addopts = "--mypy" [pytest.enabler.flake8] addopts = "--flake8" [pytest.enabler.cov] addopts = "--cov" jaraco.functools-3.4.0/pytest.ini000066400000000000000000000006201413754306400170260ustar00rootroot00000000000000[pytest] norecursedirs=dist build .tox .eggs # doctests disabled due to pytest-dev/pytest#3396 # addopts=--doctest-modules doctest_optionflags=ALLOW_UNICODE ELLIPSIS filterwarnings= # Suppress deprecation warning in flake8 ignore:SelectableGroups dict interface is deprecated::flake8 # Suppress deprecation warning in pypa/packaging#433 ignore:The distutils package is deprecated::packaging.tags jaraco.functools-3.4.0/setup.cfg000066400000000000000000000021001413754306400166110ustar00rootroot00000000000000[metadata] name = jaraco.functools author = Jason R. Coombs author_email = jaraco@jaraco.com description = Functools like those found in stdlib long_description = file:README.rst url = https://github.com/jaraco/jaraco.functools classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: MIT License Programming Language :: Python :: 3 Programming Language :: Python :: 3 :: Only [options] packages = find_namespace: include_package_data = true python_requires = >=3.6 install_requires = more_itertools [options.packages.find] exclude = build* dist* docs* tests* [options.extras_require] testing = # upstream pytest >= 6 pytest-checkdocs >= 2.4 pytest-flake8 pytest-black >= 0.3.7; \ # workaround for jaraco/skeleton#22 python_implementation != "PyPy" pytest-cov pytest-mypy; \ # workaround for jaraco/skeleton#22 python_implementation != "PyPy" pytest-enabler >= 1.0.1 # local jaraco.classes docs = # upstream sphinx jaraco.packaging >= 8.2 rst.linker >= 1.9 # local [options.entry_points] jaraco.functools-3.4.0/setup.py000066400000000000000000000001341413754306400165070ustar00rootroot00000000000000#!/usr/bin/env python import setuptools if __name__ == "__main__": setuptools.setup() jaraco.functools-3.4.0/test_functools.py000066400000000000000000000160611413754306400204300ustar00rootroot00000000000000import os import itertools import time import copy import random import functools import platform from unittest import mock import pytest from jaraco.classes import properties from jaraco.functools import Throttler, method_cache, retry_call, retry class TestThrottler: @pytest.mark.xfail( os.environ.get('GITHUB_ACTIONS') # type: ignore and platform.system() == 'Darwin', reason="Performance is heavily throttled on Github Actions Mac runs", ) def test_function_throttled(self): """ Ensure the throttler actually throttles calls. """ # set up a function to be called counter = itertools.count() # set up a version of `next` that is only called 30 times per second limited_next = Throttler(next, 30) # for one second, call next as fast as possible deadline = time.time() + 1 while time.time() < deadline: limited_next(counter) # ensure the counter was advanced about 30 times assert 28 <= next(counter) <= 32 # ensure that another burst of calls after some idle period will also # get throttled time.sleep(1) deadline = time.time() + 1 counter = itertools.count() while time.time() < deadline: limited_next(counter) assert 28 <= next(counter) <= 32 def test_reconstruct_unwraps(self): """ The throttler should be re-usable - if one wants to throttle a function that's aready throttled, the original function should be used. """ wrapped = Throttler(next, 30) wrapped_again = Throttler(wrapped, 60) assert wrapped_again.func is next assert wrapped_again.max_rate == 60 def test_throttled_method(self): class ThrottledMethodClass: @Throttler def echo(self, arg): return arg tmc = ThrottledMethodClass() assert tmc.echo('foo') == 'foo' class TestMethodCache: bad_vers = '(3, 5, 0) <= sys.version_info < (3, 5, 2)' @pytest.mark.skipif(bad_vers, reason="https://bugs.python.org/issue25447") def test_deepcopy(self): """ A deepcopy of an object with a method cache should still succeed. """ class ClassUnderTest: calls = 0 @method_cache def method(self, value): self.calls += 1 return value ob = ClassUnderTest() copy.deepcopy(ob) ob.method(1) copy.deepcopy(ob) def test_special_methods(self): """ Test method_cache with __getitem__ and __getattr__. """ class ClassUnderTest: getitem_calls = 0 getattr_calls = 0 @method_cache def __getitem__(self, item): self.getitem_calls += 1 return item @method_cache def __getattr__(self, name): self.getattr_calls += 1 return name ob = ClassUnderTest() # __getitem__ ob[1] + ob[1] assert ob.getitem_calls == 1 # __getattr__ ob.one + ob.one assert ob.getattr_calls == 1 @pytest.mark.xfail(reason="can't replace property with cache; #6") def test_property(self): """ Can a method_cache decorated method also be a property? """ class ClassUnderTest: @property @method_cache def mything(self): # pragma: nocover return random.random() ob = ClassUnderTest() assert ob.mything == ob.mything @pytest.mark.xfail(reason="can't replace property with cache; #6") def test_non_data_property(self): """ A non-data property also does not work because the property gets replaced with a method. """ class ClassUnderTest: @properties.NonDataProperty @method_cache def mything(self): return random.random() ob = ClassUnderTest() assert ob.mything == ob.mything class TestRetry: def attempt(self, arg=None): if next(self.fails_left): raise ValueError("Failed!") if arg: arg.touch() return "Success" def set_to_fail(self, times): self.fails_left = itertools.count(times, -1) def test_set_to_fail(self): """ Test this test's internal failure mechanism. """ self.set_to_fail(times=2) with pytest.raises(ValueError): self.attempt() with pytest.raises(ValueError): self.attempt() assert self.attempt() == 'Success' def test_retry_call_succeeds(self): self.set_to_fail(times=2) res = retry_call(self.attempt, retries=2, trap=ValueError) assert res == "Success" def test_retry_call_fails(self): """ Failing more than the number of retries should raise the underlying error. """ self.set_to_fail(times=3) with pytest.raises(ValueError) as res: retry_call(self.attempt, retries=2, trap=ValueError) assert str(res.value) == 'Failed!' def test_retry_multiple_exceptions(self): self.set_to_fail(times=2) errors = ValueError, NameError res = retry_call(self.attempt, retries=2, trap=errors) assert res == "Success" def test_retry_exception_superclass(self): self.set_to_fail(times=2) res = retry_call(self.attempt, retries=2, trap=Exception) assert res == "Success" def test_default_traps_nothing(self): self.set_to_fail(times=1) with pytest.raises(ValueError): retry_call(self.attempt, retries=1) def test_default_does_not_retry(self): self.set_to_fail(times=1) with pytest.raises(ValueError): retry_call(self.attempt, trap=Exception) def test_cleanup_called_on_exception(self): calls = random.randint(1, 10) cleanup = mock.Mock() self.set_to_fail(times=calls) retry_call(self.attempt, retries=calls, cleanup=cleanup, trap=Exception) assert cleanup.call_count == calls assert cleanup.called_with() def test_infinite_retries(self): self.set_to_fail(times=999) cleanup = mock.Mock() retry_call(self.attempt, retries=float('inf'), cleanup=cleanup, trap=Exception) assert cleanup.call_count == 999 def test_with_arg(self): self.set_to_fail(times=0) arg = mock.Mock() bound = functools.partial(self.attempt, arg) res = retry_call(bound) assert res == 'Success' assert arg.touch.called def test_decorator(self): self.set_to_fail(times=1) attempt = retry(retries=1, trap=Exception)(self.attempt) res = attempt() assert res == "Success" def test_decorator_with_arg(self): self.set_to_fail(times=0) attempt = retry()(self.attempt) arg = mock.Mock() res = attempt(arg) assert res == 'Success' assert arg.touch.called jaraco.functools-3.4.0/tox.ini000066400000000000000000000013661413754306400163200ustar00rootroot00000000000000[tox] envlist = python minversion = 3.2 # https://github.com/jaraco/skeleton/issues/6 tox_pip_extensions_ext_venv_update = true toxworkdir={env:TOX_WORK_DIR:.tox} [testenv] deps = commands = pytest {posargs} usedevelop = True extras = testing passenv = GITHUB_ACTIONS [testenv:docs] extras = docs testing changedir = docs commands = python -m sphinx -W --keep-going . {toxinidir}/build/html [testenv:release] skip_install = True deps = build twine>=3 jaraco.develop>=7.1 passenv = TWINE_PASSWORD GITHUB_TOKEN setenv = TWINE_USERNAME = {env:TWINE_USERNAME:__token__} commands = python -c "import shutil; shutil.rmtree('dist', ignore_errors=True)" python -m build python -m twine upload dist/* python -m jaraco.develop.create-github-release