Python functools.partialmethod() Examples

The following are 30 code examples of functools.partialmethod(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module functools , or try the search function .
Example #1
Source File: test_partialmethod.py    From async_lru with MIT License 7 votes vote down vote up
def test_partialmethod_partial(check_lru, loop):
    class Obj:
        def __init__(self):
            self.coro = alru_cache(partial(self._coro, 2), loop=loop)

        async def __coro(self, val1, val2):
            return val1 + val2

        _coro = partialmethod(__coro, 1)

    obj = Obj()

    coros = [obj.coro() for _ in range(5)]

    check_lru(obj.coro, hits=0, misses=0, cache=0, tasks=0)

    ret = await asyncio.gather(*coros, loop=loop)

    check_lru(obj.coro, hits=4, misses=1, cache=1, tasks=0)

    assert ret == [3, 3, 3, 3, 3] 
Example #2
Source File: test_partialmethod.py    From async_lru with MIT License 7 votes vote down vote up
def test_partialmethod_basic(check_lru, loop):
    class Obj:
        async def _coro(self, val):
            return val

        coro = alru_cache(partialmethod(_coro, 2), loop=loop)

    obj = Obj()

    coros = [obj.coro() for _ in range(5)]

    check_lru(obj.coro, hits=0, misses=0, cache=0, tasks=0)

    ret = await asyncio.gather(*coros, loop=loop)

    check_lru(obj.coro, hits=4, misses=1, cache=1, tasks=0)

    assert ret == [2, 2, 2, 2, 2] 
Example #3
Source File: floating.py    From PyVM with MIT License 6 votes vote down vote up
def __init__(self):
        self.opcodes = {
            **{
                0xD8F0 + i: P(self.fdiv, i=i, reverse=True)
                for i in range(8)
            },
            **{
                0xDCF8 + i: P(self.fdiv, i=i, reverse=False)
                for i in range(8)
            },

            **{
                0xDEF8 + i: P(self.fdivp, i=i)
                for i in range(8)
            },
        } 
Example #4
Source File: test_partialmethod.py    From async_lru with MIT License 6 votes vote down vote up
def test_partialmethod_cls_loop(check_lru, loop):
    class Obj:
        def __init__(self, loop):
            self._loop = loop

        async def _coro(self, val):
            return val

        coro = alru_cache(partialmethod(_coro, 2), cls=True, loop='_loop')

    obj = Obj(loop=loop)

    coros = [obj.coro() for _ in range(5)]

    check_lru(obj.coro, hits=0, misses=0, cache=0, tasks=0)

    ret = await asyncio.gather(*coros, loop=loop)

    check_lru(obj.coro, hits=4, misses=1, cache=1, tasks=0)

    assert ret == [2, 2, 2, 2, 2] 
Example #5
Source File: test_partialmethod.py    From async_lru with MIT License 6 votes vote down vote up
def test_partialmethod_kwargs_loop(check_lru, loop):
    class Obj:
        async def _coro(self, val, *, _loop):
            return val

        coro = alru_cache(partialmethod(_coro, 2), kwargs=True, loop='_loop')

    obj = Obj()

    coros = [obj.coro(_loop=loop) for _ in range(5)]

    check_lru(obj.coro, hits=0, misses=0, cache=0, tasks=0)

    ret = await asyncio.gather(*coros, loop=loop)

    check_lru(obj.coro, hits=4, misses=1, cache=1, tasks=0)

    assert ret == [2, 2, 2, 2, 2] 
Example #6
Source File: orderbyfield.py    From django-more with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def contribute_to_class(self, cls, *args, **kwargs):
        super().contribute_to_class(cls, *args, **kwargs)

        # Add order related methods to model
        # Applying partialmethod() to already bound methods will retain self and add the model_instance bound to
        subs = {'name': self.name, 'model': self.model.__name__.lower()}
        setattr(cls, self.func_local_next % subs, partialmethod(self.get_next_or_previous_in_order, is_next=True))
        setattr(cls, self.func_local_previous % subs, partialmethod(self.get_next_or_previous_in_order, is_next=False))
        setattr(cls, self.func_local_get_set % subs, partialmethod(self.get_group_order))
        setattr(cls, self.func_local_set_set % subs, partialmethod(self.set_group_order))
        if self.unique_for_fields:
            # Declare that this field has dependencies
            self.has_dependencies = True
            # Queue rest of work for when model is fully loaded
            cls._meta.apps.lazy_model_operation(
                self._lazy_contribute_to_class,
                (cls._meta.app_label, cls._meta.model_name)) 
Example #7
Source File: events.py    From annotated-py-projects with MIT License 6 votes vote down vote up
def _get_function_source(func):
    if _PY34:
        func = inspect.unwrap(func)
    elif hasattr(func, '__wrapped__'):
        func = func.__wrapped__

    if inspect.isfunction(func):
        code = func.__code__
        return (code.co_filename, code.co_firstlineno)

    if isinstance(func, functools.partial):
        return _get_function_source(func.func)

    if _PY34 and isinstance(func, functools.partialmethod):
        return _get_function_source(func.func)
    return None 
Example #8
Source File: util.py    From PyVM with MIT License 6 votes vote down vote up
def load_instruction(cls, instruction, opcode, implementation):
        try:
            impl_name = implementation.__name__
        except AttributeError:
            if isinstance(implementation, functools.partialmethod):
                rand = os.urandom(4).hex()

                try:
                    impl_name = f"{implementation.func.__name__}_{rand}"
                except AttributeError:
                    # TODO: WTF is happening here? Eg. when wrapping a MagicMock
                    impl_name = rand
            else:
                # TODO: WTF is happening here? Eg. with a MagicMock
                impl_name = os.urandom(4).hex()

        concrete_name = f"i_{instruction.__name__}_{impl_name}"

        while concrete_name in cls.concrete_names:
            concrete_name += os.urandom(4).hex()

        cls.concrete_names.append(concrete_name)

        setattr(cls, concrete_name, implementation)
        cls.opcodes_names.setdefault(opcode, []).append(concrete_name) 
Example #9
Source File: control.py    From PyVM with MIT License 6 votes vote down vote up
def __init__(self):
        self.opcodes = {
            0xEB: P(self.rel, _8bit=True, jump=_JMP),
            0xE9: P(self.rel, _8bit=False, jump=_JMP),

            0xFF: self.rm_m,
            0xEA: P(self.ptr, _8bit=False),

            0xE3: P(self.rel, _8bit=True, jump=JCXZ),

            **{
                opcode: P(self.rel, _8bit=True, jump=JUMPS[opcode % 0x70])
                for opcode in range(0x70, 0x80)
            },

            **{
                opcode: P(self.rel, _8bit=False, jump=JUMPS[opcode % 0x0F80])
                for opcode in range(0x0F80, 0x0F90)
            }
        } 
Example #10
Source File: memory.py    From PyVM with MIT License 6 votes vote down vote up
def __init__(self):
        self.opcodes = {
            **{
                o: self.r
                for o in range(0x50, 0x58)
                },
            0xFF  : self.rm,

            0x6A  : P(self.imm, _8bit=True),
            0x68  : P(self.imm, _8bit=False),

            0x0E  : P(self.sreg, 'CS'),
            0x16  : P(self.sreg, 'SS'),
            0x1E  : P(self.sreg, 'DS'),
            0x06  : P(self.sreg, 'ES'),

            0x0FA0: P(self.sreg, 'FS'),
            0x0FA8: P(self.sreg, 'GS')
            } 
Example #11
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def register_tests(test_class, method_name, test_func, exclude=()):
    """
    Dynamically create serializer tests to ensure that all registered
    serializers are automatically tested.
    """
    for format_ in serializers.get_serializer_formats():
        if format_ == 'geojson' or format_ in exclude:
            continue
        decorated_func = skipIf(
            isinstance(serializers.get_serializer(format_), serializers.BadSerializer),
            'The Python library for the %s serializer is not installed.' % format_,
        )(test_func)
        setattr(test_class, method_name % format_, partialmethod(decorated_func, format_)) 
Example #12
Source File: test_inspect.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_signature_on_partialmethod(self):
        from functools import partialmethod

        class Spam:
            def test():
                pass
            ham = partialmethod(test)

        with self.assertRaisesRegex(ValueError, "has incorrect arguments"):
            inspect.signature(Spam.ham)

        class Spam:
            def test(it, a, *, c) -> 'spam':
                pass
            ham = partialmethod(test, c=1)

        self.assertEqual(self.signature(Spam.ham),
                         ((('it', ..., ..., 'positional_or_keyword'),
                           ('a', ..., ..., 'positional_or_keyword'),
                           ('c', 1, ..., 'keyword_only')),
                          'spam'))

        self.assertEqual(self.signature(Spam().ham),
                         ((('a', ..., ..., 'positional_or_keyword'),
                           ('c', 1, ..., 'keyword_only')),
                          'spam')) 
Example #13
Source File: test_inspect.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_signature_without_self(self):
        def test_args_only(*args):  # NOQA
            pass

        def test_args_kwargs_only(*args, **kwargs):  # NOQA
            pass

        class A:
            @classmethod
            def test_classmethod(*args):  # NOQA
                pass

            @staticmethod
            def test_staticmethod(*args):  # NOQA
                pass

            f1 = functools.partialmethod((test_classmethod), 1)
            f2 = functools.partialmethod((test_args_only), 1)
            f3 = functools.partialmethod((test_staticmethod), 1)
            f4 = functools.partialmethod((test_args_kwargs_only),1)

        self.assertEqual(self.signature(test_args_only),
                         ((('args', ..., ..., 'var_positional'),), ...))
        self.assertEqual(self.signature(test_args_kwargs_only),
                         ((('args', ..., ..., 'var_positional'),
                           ('kwargs', ..., ..., 'var_keyword')), ...))
        self.assertEqual(self.signature(A.f1),
                         ((('args', ..., ..., 'var_positional'),), ...))
        self.assertEqual(self.signature(A.f2),
                         ((('args', ..., ..., 'var_positional'),), ...))
        self.assertEqual(self.signature(A.f3),
                         ((('args', ..., ..., 'var_positional'),), ...))
        self.assertEqual(self.signature(A.f4), 
                         ((('args', ..., ..., 'var_positional'),
                            ('kwargs', ..., ..., 'var_keyword')), ...)) 
Example #14
Source File: test_functools.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_abstract(self):
        class Abstract(abc.ABCMeta):

            @abc.abstractmethod
            def add(self, x, y):
                pass

            add5 = functools.partialmethod(add, 5)

        self.assertTrue(Abstract.add.__isabstractmethod__)
        self.assertTrue(Abstract.add5.__isabstractmethod__)

        for func in [self.A.static, self.A.cls, self.A.over_partial, self.A.nested, self.A.both]:
            self.assertFalse(getattr(func, '__isabstractmethod__', False)) 
Example #15
Source File: format_helpers.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def _get_function_source(func):
    func = inspect.unwrap(func)
    if inspect.isfunction(func):
        code = func.__code__
        return (code.co_filename, code.co_firstlineno)
    if isinstance(func, functools.partial):
        return _get_function_source(func.func)
    if isinstance(func, functools.partialmethod):
        return _get_function_source(func.func)
    return None 
Example #16
Source File: tests.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_name_from_func_partialmethod_bound():
    class X(object):
        def x(self, x):
            pass

        p = partialmethod(x, "x")

    assert "partial(tests.utils.tests.x)" == get_name_from_func(X().p) 
Example #17
Source File: format_helpers.py    From android_universal with MIT License 5 votes vote down vote up
def _get_function_source(func):
    func = inspect.unwrap(func)
    if inspect.isfunction(func):
        code = func.__code__
        return (code.co_filename, code.co_firstlineno)
    if isinstance(func, functools.partial):
        return _get_function_source(func.func)
    if isinstance(func, functools.partialmethod):
        return _get_function_source(func.func)
    return None 
Example #18
Source File: tests.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_name_from_func_partialmethod_unbound():
    class X(object):
        def x(self, x):
            pass

        p = partialmethod(x, "x")

    assert "partial(tests.utils.tests.x)" == get_name_from_func(X.p) 
Example #19
Source File: repeatables.py    From PyVM with MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            0xAA: P(self.m, _8bit=True),
            0xAB: P(self.m, _8bit=False)
        } 
Example #20
Source File: control.py    From PyVM with MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            opcode: P(self.rm8, cond=JUMPS[opcode % 0x0F90])
            for opcode in range(0x0F90, 0x0FA0)
        } 
Example #21
Source File: test_functools.py    From android_universal with MIT License 5 votes vote down vote up
def test_invalid_args(self):
        with self.assertRaises(TypeError):
            class B(object):
                method = functools.partialmethod(None, 1) 
Example #22
Source File: memory.py    From PyVM with MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            0xF8: P(self.set_stuff, 'CF', 0),
            0xFC: P(self.set_stuff, 'DF', 0),
            0xF9: P(self.set_stuff, 'CF', 1),
            0xFD: P(self.set_stuff, 'DF', 1),
            } 
Example #23
Source File: memory.py    From PyVM with MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            0xA4: P(self.movs, _8bit=True),
            0xA5: P(self.movs, _8bit=False)
            } 
Example #24
Source File: memory.py    From PyVM with MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            0x0FB0: P(self.rm_r, _8bit=True),
            0x0FB1: P(self.rm_r, _8bit=False)
        } 
Example #25
Source File: memory.py    From PyVM with MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            **{
                o: self.r
                for o in range(0x58, 0x60)
                },
            0x8F  : self.rm,

            0x1F  : P(self.sreg, 'DS'),
            0x07  : P(self.sreg, 'ES'),
            0x17  : P(self.sreg, 'SS'),

            0x0FA1: P(self.sreg, 'FS', _32bit=True),
            0x0FA9: P(self.sreg, 'GS', _32bit=True)
            } 
Example #26
Source File: test_functools.py    From android_universal with MIT License 5 votes vote down vote up
def test_repr(self):
        self.assertEqual(repr(vars(self.A)['both']),
                         'functools.partialmethod({}, 3, b=4)'.format(capture)) 
Example #27
Source File: memory.py    From PyVM with MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            0x0FBE: P(self.r_rm, _8bit=True, movsxd=False),
            0x0FBF: P(self.r_rm, _8bit=False, movsxd=False),

            0x63: P(self.r_rm, _8bit=False, movsxd=True),

            0x0FB6: P(self.r_rm_movzx, _8bit=True),
            0x0FB7: P(self.r_rm_movzx, _8bit=False),
        } 
Example #28
Source File: memory.py    From PyVM with MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            **{
                o: P(self.r_imm, _8bit=True)
                for o in range(0xB0, 0xB8)
                },
            **{
                o: P(self.r_imm, _8bit=False)
                for o in range(0xB8, 0xC0)
                },
            0xC6: P(self.rm_imm, _8bit=True),
            0xC7: P(self.rm_imm, _8bit=False),

            0x88: P(self.rm_r, _8bit=True, reverse=False),
            0x89: P(self.rm_r, _8bit=False, reverse=False),

            0x8A: P(self.rm_r, _8bit=True, reverse=True),
            0x8B: P(self.rm_r, _8bit=False, reverse=True),

            0x8C: P(self.sreg_rm, reverse=True),
            0x8E: P(self.sreg_rm, reverse=False),

            0xA0: P(self.r_moffs, reverse=False, _8bit=True),
            0xA1: P(self.r_moffs, reverse=False, _8bit=False),

            0xA2: P(self.r_moffs, reverse=True, _8bit=True),
            0xA3: P(self.r_moffs, reverse=True, _8bit=False),
            } 
Example #29
Source File: floating.py    From PyVM with MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            0xD9C8 + i: P(self.fxch, i=i)
            for i in range(8)
        } 
Example #30
Source File: test_functools.py    From android_universal with MIT License 5 votes vote down vote up
def test_abstract(self):
        class Abstract(abc.ABCMeta):

            @abc.abstractmethod
            def add(self, x, y):
                pass

            add5 = functools.partialmethod(add, 5)

        self.assertTrue(Abstract.add.__isabstractmethod__)
        self.assertTrue(Abstract.add5.__isabstractmethod__)

        for func in [self.A.static, self.A.cls, self.A.over_partial, self.A.nested, self.A.both]:
            self.assertFalse(getattr(func, '__isabstractmethod__', False))