Esempio n. 1
0
class Operable(_AdderClass):
    @_AdderClass.decorate(classmethod)
    @_AdderClass.decorate(_lru_cache(maxsize=32))
    def get_operator(cls, operator):  # pylint: disable=E0213,R0201
        if isinstance(operator, str):
            if operator in OPS:
                if operator in _REVOPS:
                    raise ValueError
                    # operator = operator[1:]
                    # operands = operands[::-1]
                operator = getattr(_operator, f"__{operator}__")
            else:
                raise KeyError(operator)
        return operator

    @_AdderClass.decorate(classmethod)
    @_AdderClass.decorate(_abstractmethod)
    def operate(cls, operator, *args, **kwargs) -> object:  # pylint: disable=E0213 R0201
        '''Carries out the actual operation and returns the result.'''
        raise TypeError("This method is abstract and should never be called.")

    def _op(self, other=None, /, *, operator, rev=False, **kwargs):
        operator = self.get_operator(operator)
        if other is None:
            return self.operate(operator, self, **kwargs)
        if rev:
            return self.operate(operator, other, self, **kwargs)
        return self.operate(operator, self, other, **kwargs)
Esempio n. 2
0
    def __call__(self, fn):
        # type: (T) -> T
        # assert (self.cached_function is not None) == (self.uncached_function is not None)

        if self.cached_function is None:
            self.uncached_function = fn  # type: T
            self.cached_function = _lru_cache(maxsize=self.maxsize)(fn)
        else:
            assert self.uncached_function == fn  # pragma: no cover  # defensive approach, this should not happen

        return typing.cast(T, self.cached_function)
Esempio n. 3
0
"""This module contains backports to support older Python versions."""
#
# (C) Pywikibot team, 2020-2021
#
# Distributed under the terms of the MIT license.
#
from pywikibot.tools import PYTHON_VERSION

# functools.cache
if PYTHON_VERSION >= (3, 9):
    from functools import cache
else:
    from functools import lru_cache as _lru_cache
    cache = _lru_cache(None)

# typing
if PYTHON_VERSION < (3, 5, 2):
    from typing import Dict as DefaultDict
elif PYTHON_VERSION < (3, 9):
    from typing import DefaultDict
else:
    from collections import defaultdict as DefaultDict  # noqa: N812

if PYTHON_VERSION >= (3, 9):
    from collections.abc import Iterable, Sequence
    Dict = dict
    FrozenSet = frozenset
    List = list
    Set = set
    Tuple = tuple
else:
Esempio n. 4
0
# All portions of the code written by reddit are Copyright (c) 2006-2015 reddit
# Inc. All Rights Reserved.
###############################################################################

import asyncio as _asyncio
from collections import OrderedDict as _OrderedDict
from functools import lru_cache as _lru_cache
from itertools import tee as _tee
import re as _re
from types import GeneratorType as _GeneratorType
import urllib.parse

from async_timeout import timeout as _timeout

_Tee = _tee([], 1)[0].__class__
memoize = _lru_cache(maxsize=None)
_LOOP = _asyncio.get_event_loop()


def timeout(coroutine, timeout=30):
    async def inner_timeout():
        async with _timeout(timeout):
            return await coroutine
        return None

    return _LOOP.run_until_complete(inner_timeout())


def generator_memoize(f):
    # https://stackoverflow.com/a/10726355/1378440
    cache = {}
Esempio n. 5
0
 def cached(func):
     """Wraps functools.lru_cache with maxsize=None"""
     return _lru_cache(None)(func)
Esempio n. 6
0
 def lru_cache(func, maxsize=512):
     return _lru_cache(maxsize=maxsize)(func)
Esempio n. 7
0
    def operate(cls, operator, *args, **kwargs) -> object:  # pylint: disable=E0213 R0201
        '''Carries out the actual operation and returns the result.'''
        raise TypeError("This method is abstract and should never be called.")

    def _op(self, other=None, /, *, operator, rev=False, **kwargs):
        operator = self.get_operator(operator)
        if other is None:
            return self.operate(operator, self, **kwargs)
        if rev:
            return self.operate(operator, other, self, **kwargs)
        return self.operate(operator, self, other, **kwargs)

    def apply(self, operator, **kwargs):
        return self._op(operator=operator, **kwargs)

    @_AdderClass.decorate(_lru_cache(maxsize=64))
    def transform(self, operator, **kwargs):
        return _partial(self._op, operator=operator, **kwargs)

    ### BINARY ###

    def __add__(self, other):
        return self._op(other, operator='add')

    def __sub__(self, other):
        return self._op(other, operator='sub')

    def __mul__(self, other):
        return self._op(other, operator='mul')

    def __matmul__(self, other):
Esempio n. 8
0
 def __init__(self, func):
     self.decorator = _lru_cache(maxsize=None, typed=False)(func)
Esempio n. 9
0
 def lru_cache(func):
     '''A least recently used cache: keeps the 512 most recent results of
     function in cache'''
     return _lru_cache(maxsize=512)(func)
Esempio n. 10
0
 def lru_cache(func):
     '''A least recently used cache: keeps the 512 most recent results of
     function in cache'''
     return _lru_cache(maxsize=512)(func)
Esempio n. 11
0
 def lru_cache(func, maxsize=512):
     return _lru_cache(maxsize=maxsize)(func)
Esempio n. 12
0
 def cached(func):
     """Wraps functools.lru_cache with maxsize=None"""
     return _lru_cache(None)(func)