Python functools.partialmethod() Examples

The following are code examples for showing how to use functools.partialmethod(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: miniast   Author: cpcloud   File: base.py    Apache License 2.0 6 votes vote down vote up
def binary_operations(mapping, func):
    """Decorator providing default implementations of binary operations.

    Parameters
    ----------
    mapping : collections.Mapping
    func : callable

    Returns
    -------
    decorator : callable
    """
    def decorator(cls):
        for method_name, op in mapping.items():
            if method_name in SWAPPED_ARGUMENT_METHODS:
                f = functools.partialmethod(
                    lambda self, other, op: func(to_node(other), self, op),
                    op=op()
                )
            else:
                f = functools.partialmethod(func, op=op())
            setattr(cls, method_name, f)
        return cls
    return decorator 
Example 2
Project: influx-sansio   Author: miracle2k   File: abc.py    MIT License 6 votes vote down vote up
def set_query_pattern(cls, queries: Optional[Mapping] = None, **kwargs) -> None:
        """Defines custom methods to provide quick access to commonly used query patterns.

        Query patterns are passed as mappings, where the key is name name of
        the desired new method representing the query pattern and the value is the actual query pattern.
        Query patterns are plain strings, with optional the named placed holders. Named placed holders
        are processed as keyword arguments in ``str.format``. Positional arguments are also supported.

        Sample query pattern dictionary:

        {"host_load": "SELECT mean(load) FROM cpu_stats WHERE host = '{host}' AND time > now() - {days}d",
         "peak_load": "SELECT max(load) FROM cpu_stats WHERE host = '{host}' GROUP BY time(1d),host"}

        :param queries: Mapping (e.g. dictionary) containing query patterns.
            Can be used in conjunction with kwargs.
        :param kwargs: Alternative way to pass query patterns.
        """
        if queries is None:
            queries = {}
        restricted_kwargs = ('q', 'epoch', 'chunked' 'chunk_size')
        for name, query in {**queries, **kwargs}.items():
            if any(kw in restricted_kwargs for kw in re.findall('{(\w+)}', query)):
                warnings.warn(f'Ignoring invalid query pattern: {query}')
                continue
            setattr(cls, name, pm(cls.query, query)) 
Example 3
Project: django-more   Author: ashleywaite   File: orderbyfield.py    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 4
Project: aiohttp-swagger3   Author: hh-h   File: swagger_docs.py    Apache License 2.0 6 votes vote down vote up
def _wrap_handler(
        self, method: str, path: str, handler: _SwaggerHandler, *, is_method: bool
    ) -> _SwaggerHandler:
        if not handler.__doc__ or "---" not in handler.__doc__:
            return handler
        *_, spec = handler.__doc__.split("---")
        method_spec = yaml.safe_load(spec)
        self.spec["paths"][path][method] = method_spec
        self.spec_validate(self.spec)
        self._app[_SWAGGER_SPECIFICATION] = self.spec
        if not self.validate:
            return handler
        route = SwaggerRoute(method, path, handler, swagger=self)
        if is_method:
            return functools.partialmethod(  # type: ignore
                self._handle_swagger_method_call, route
            )
        return functools.partial(self._handle_swagger_call, route) 
Example 5
Project: PyVM   Author: ForceBru   File: util.py    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 6
Project: PyVM   Author: ForceBru   File: floating.py    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 7
Project: PyVM   Author: ForceBru   File: memory.py    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 8
Project: PyVM   Author: ForceBru   File: control.py    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 9
Project: annotated-py-asyncio   Author: hhstore   File: events.py    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 10
Project: NiujiaoDebugger   Author: MrSrc   File: format_helpers.py    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 11
Project: NiujiaoDebugger   Author: MrSrc   File: test_functools.py    GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_args(self):
        with self.assertRaises(TypeError):
            class B(object):
                method = functools.partialmethod(None, 1) 
Example 12
Project: NiujiaoDebugger   Author: MrSrc   File: test_functools.py    GNU General Public License v3.0 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 13
Project: NiujiaoDebugger   Author: MrSrc   File: test_functools.py    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 14
Project: NiujiaoDebugger   Author: MrSrc   File: test_inspect.py    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 15
Project: NiujiaoDebugger   Author: MrSrc   File: test_inspect.py    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'))

        class Spam:
            def test(self: 'anno', x):
                pass

            g = partialmethod(test, 1)

        self.assertEqual(self.signature(Spam.g),
                         ((('self', ..., 'anno', 'positional_or_keyword'),),
                          ...)) 
Example 16
Project: banruo   Author: yingshang   File: base.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def make_foreign_order_accessors(model, related_model):
    setattr(
        related_model,
        'get_%s_order' % model.__name__.lower(),
        partialmethod(method_get_order, model)
    )
    setattr(
        related_model,
        'set_%s_order' % model.__name__.lower(),
        partialmethod(method_set_order, model)
    )

########
# MISC #
######## 
Example 17
Project: Blockly-rduino-communication   Author: technologiescollege   File: events.py    GNU General Public License v3.0 5 votes vote down vote up
def _get_function_source(func):
    if compat.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 compat.PY34 and isinstance(func, functools.partialmethod):
        return _get_function_source(func.func)
    return None 
Example 18
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_functools.py    GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_args(self):
        with self.assertRaises(TypeError):
            class B(object):
                method = functools.partialmethod(None, 1) 
Example 19
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_functools.py    GNU General Public License v3.0 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 20
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_functools.py    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 21
Project: django-more   Author: ashleywaite   File: orderbyfield.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def contribute_to_related_class(self, cls, field):
        subs = {'name': self.name, 'model': self.model.__name__.lower(), 'remote_name': field.name}
        setattr(cls, self.func_remote_get_set % subs, partialmethod(self.get_group_order, field=field))
        setattr(cls, self.func_remote_set_set % subs, partialmethod(self.set_group_order, field=field)) 
Example 22
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: format_helpers.py    GNU General Public License v2.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 23
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_functools.py    GNU General Public License v2.0 5 votes vote down vote up
def test_invalid_args(self):
        with self.assertRaises(TypeError):
            class B(object):
                method = functools.partialmethod(None, 1)
        with self.assertRaises(TypeError):
            class B:
                method = functools.partialmethod()
        class B:
            method = functools.partialmethod(func=capture, a=1)
        b = B()
        self.assertEqual(b.method(2, x=3), ((b, 2), {'a': 1, 'x': 3})) 
Example 24
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_functools.py    GNU General Public License v2.0 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 25
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_functools.py    GNU General Public License v2.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 26
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_inspect.py    GNU General Public License v2.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 27
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_inspect.py    GNU General Public License v2.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'))

        class Spam:
            def test(self: 'anno', x):
                pass

            g = partialmethod(test, 1)

        self.assertEqual(self.signature(Spam.g),
                         ((('self', ..., 'anno', 'positional_or_keyword'),),
                          ...)) 
Example 28
Project: aws-lambda-runtime-pypy   Author: uscheller   File: events.py    Apache License 2.0 5 votes vote down vote up
def _get_function_source(func):
    if compat.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 compat.PY34 and isinstance(func, functools.partialmethod):
        return _get_function_source(func.func)
    return None 
Example 29
Project: news_proj   Author: TheoElia   File: base.py    MIT License 5 votes vote down vote up
def make_foreign_order_accessors(model, related_model):
    setattr(
        related_model,
        'get_%s_order' % model.__name__.lower(),
        partialmethod(method_get_order, model)
    )
    setattr(
        related_model,
        'set_%s_order' % model.__name__.lower(),
        partialmethod(method_set_order, model)
    )

########
# MISC #
######## 
Example 30
Project: scene-representation-networks   Author: vsitzmann   File: hyperlayers.py    MIT License 5 votes vote down vote up
def partialclass(cls, *args, **kwds):

    class NewCls(cls):
        __init__ = functools.partialmethod(cls.__init__, *args, **kwds)

    return NewCls 
Example 31
Project: setup   Author: mindbender-studio   File: events.py    MIT License 5 votes vote down vote up
def _get_function_source(func):
    if compat.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 compat.PY34 and isinstance(func, functools.partialmethod):
        return _get_function_source(func.func)
    return None 
Example 32
Project: vue-django-element-django   Author: jonathanmusto   File: base.py    MIT License 5 votes vote down vote up
def make_foreign_order_accessors(model, related_model):
    setattr(
        related_model,
        'get_%s_order' % model.__name__.lower(),
        partialmethod(method_get_order, model)
    )
    setattr(
        related_model,
        'set_%s_order' % model.__name__.lower(),
        partialmethod(method_set_order, model)
    )

########
# MISC #
######## 
Example 33
Project: sentinelsat   Author: sentinelsat   File: test_cli.py    GNU General Public License v3.0 5 votes vote down vote up
def test_download_single(run_cli, api, tmpdir, smallest_online_products, monkeypatch):
    # Change default arguments for quicker test.
    # Also, vcrpy is not threadsafe, so only one worker is used.
    monkeypatch.setattr(
        "sentinelsat.SentinelAPI.download_all",
        partialmethod(SentinelAPI.download_all, n_concurrent_dl=1, max_attempts=2),
    )

    product_id = smallest_online_products[0]["id"]
    command = ["--uuid", product_id, "--download", "--path", str(tmpdir)]

    run_cli(*command)

    # The file already exists, should not be re-downloaded
    run_cli(*command)

    # clean up
    for f in tmpdir.listdir():
        f.remove()

    # Prepare a response with an invalid checksum
    url = "https://scihub.copernicus.eu/apihub/odata/v1/Products('%s')?$format=json" % product_id
    json = api.session.get(url).json()
    json["d"]["Checksum"]["Value"] = "00000000000000000000000000000000"

    # Force the download to fail by providing an incorrect checksum
    with requests_mock.mock(real_http=True) as rqst:
        rqst.get(url, json=json)

        # md5 flag set (implicitly), should raise an exception
        run_cli(*command, must_raise=InvalidChecksumError)

    # clean up
    tmpdir.remove() 
Example 34
Project: sentinelsat   Author: sentinelsat   File: test_cli.py    GNU General Public License v3.0 5 votes vote down vote up
def test_download_many(run_cli, api, tmpdir, smallest_online_products, monkeypatch):
    # Change default arguments for quicker test.
    # Also, vcrpy is not threadsafe, so only one worker is used.
    monkeypatch.setattr(
        "sentinelsat.SentinelAPI.download_all",
        partialmethod(SentinelAPI.download_all, n_concurrent_dl=1, max_attempts=2),
    )

    ids = [product["id"] for product in smallest_online_products]

    command = ["--uuid", ",".join(ids), "--download", "--path", str(tmpdir)]

    # Download 3 tiny products
    run_cli(*command)

    # Should not re-download
    run_cli(*command)

    # clean up
    for f in tmpdir.listdir():
        f.remove()

    # Prepare a response with an invalid checksum
    product_id = ids[0]
    url = "https://scihub.copernicus.eu/apihub/odata/v1/Products('%s')?$format=json" % product_id
    json = api.session.get(url).json()
    json["d"]["Checksum"]["Value"] = "00000000000000000000000000000000"

    # Force one download to fail
    with requests_mock.mock(real_http=True) as rqst:
        rqst.get(url, json=json)
        # md5 flag set (implicitly), should raise an exception
        result = run_cli(*command)
        assert "is corrupted" in result.output

    assert tmpdir.join("corrupt_scenes.txt").check()
    with tmpdir.join("corrupt_scenes.txt").open() as f:
        assert product_id in f.read()

    # clean up
    tmpdir.remove() 
Example 35
Project: eperpus   Author: HilmiZul   File: base.py    MIT License 5 votes vote down vote up
def make_foreign_order_accessors(model, related_model):
    setattr(
        related_model,
        'get_%s_order' % model.__name__.lower(),
        partialmethod(method_get_order, model)
    )
    setattr(
        related_model,
        'set_%s_order' % model.__name__.lower(),
        partialmethod(method_set_order, model)
    )

########
# MISC #
######## 
Example 36
Project: sublime_debugger   Author: daveleroy   File: events.py    MIT License 5 votes vote down vote up
def _get_function_source(func):
    if compat.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 compat.PY34 and isinstance(func, functools.partialmethod):
        return _get_function_source(func.func)
    return None 
Example 37
Project: garage   Author: clchiou   File: bases.py    MIT License 5 votes vote down vote up
def def_f0(*funcs):
    """Define a 0-arg method."""
    return functools.partialmethod(_wrap_method(funcs)) 
Example 38
Project: aiohttp-swagger3   Author: hh-h   File: swagger_file.py    Apache License 2.0 5 votes vote down vote up
def add_route(
        self,
        method: str,
        path: str,
        handler: Union[_SwaggerHandler, Type[AbstractView]],
        *,
        name: Optional[str] = None,
        expect_handler: Optional[ExpectHandler] = None,
    ) -> web.AbstractRoute:
        if self.validate and path in self.spec["paths"]:
            if isinstance(handler, type) and issubclass(handler, AbstractView):
                for meth in hdrs.METH_ALL:
                    meth = meth.lower()
                    if meth not in self.spec["paths"][path]:
                        continue
                    handler_ = getattr(handler, meth, None)
                    if handler_ is None:
                        continue
                    route = SwaggerRoute(meth, path, handler_, swagger=self)
                    setattr(
                        handler,
                        meth,
                        functools.partialmethod(
                            self._handle_swagger_method_call, route
                        ),
                    )
            else:
                method_lower = method.lower()
                if method_lower in self.spec["paths"][path]:
                    route = SwaggerRoute(method_lower, path, handler, swagger=self)
                    handler = functools.partial(self._handle_swagger_call, route)

        return self._app.router.add_route(
            method, path, handler, name=name, expect_handler=expect_handler
        ) 
Example 39
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: base.py    MIT License 5 votes vote down vote up
def make_foreign_order_accessors(model, related_model):
    setattr(
        related_model,
        'get_%s_order' % model.__name__.lower(),
        partialmethod(method_get_order, model)
    )
    setattr(
        related_model,
        'set_%s_order' % model.__name__.lower(),
        partialmethod(method_set_order, model)
    )

########
# MISC #
######## 
Example 40
Project: PyVM   Author: ForceBru   File: bitwise.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            # NEG, NOT
            0xF6: [
                P(self.rm, _8bit=True, REG=3),  # NEG r/m8
                P(self.rm, _8bit=True, REG=2),  # NOT r/m8
                ],
            0xF7: [
                P(self.rm, _8bit=False, REG=3),  # NEG r/m
                P(self.rm, _8bit=False, REG=2),  # NOT r/m
                ]
            } 
Example 41
Project: PyVM   Author: ForceBru   File: bitwise.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            # SHL, SHR, SAR
            0xD0: [
                P(self.shift, operation=Shift.SHL, cnt=Shift.C_ONE, _8bit=True),
                P(self.shift, operation=Shift.SHR, cnt=Shift.C_ONE, _8bit=True),
                P(self.shift, operation=Shift.SAR, cnt=Shift.C_ONE, _8bit=True),
                ],
            0xD2: [
                P(self.shift, operation=Shift.SHL, cnt=Shift.C_CL, _8bit=True),
                P(self.shift, operation=Shift.SHR, cnt=Shift.C_CL, _8bit=True),
                P(self.shift, operation=Shift.SAR, cnt=Shift.C_CL, _8bit=True),
                ],
            0xC0: [
                P(self.shift, operation=Shift.SHL, cnt=Shift.C_imm8, _8bit=True),
                P(self.shift, operation=Shift.SHR, cnt=Shift.C_imm8, _8bit=True),
                P(self.shift, operation=Shift.SAR, cnt=Shift.C_imm8, _8bit=True),
                ],

            0xD1: [
                P(self.shift, operation=Shift.SHL, cnt=Shift.C_ONE, _8bit=False),
                P(self.shift, operation=Shift.SHR, cnt=Shift.C_ONE, _8bit=False),
                P(self.shift, operation=Shift.SAR, cnt=Shift.C_ONE, _8bit=False),
                ],
            0xD3: [
                P(self.shift, operation=Shift.SHL, cnt=Shift.C_CL, _8bit=False),
                P(self.shift, operation=Shift.SAR, cnt=Shift.C_CL, _8bit=False),
                P(self.shift, operation=Shift.SHR, cnt=Shift.C_CL, _8bit=False),
                ],
            0xC1: [
                P(self.shift, operation=Shift.SHL, cnt=Shift.C_imm8, _8bit=False),
                P(self.shift, operation=Shift.SHR, cnt=Shift.C_imm8, _8bit=False),
                P(self.shift, operation=Shift.SAR, cnt=Shift.C_imm8, _8bit=False)
                ]
            } 
Example 42
Project: PyVM   Author: ForceBru   File: bitwise.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            0x0FA4: P(self.shift, operation=Shift.SHL, cnt=Shift.C_imm8),
            0x0FA5: P(self.shift, operation=Shift.SHL, cnt=Shift.C_CL),

            0x0FAC: P(self.shift, operation=Shift.SHR, cnt=Shift.C_imm8),
            0x0FAD: P(self.shift, operation=Shift.SHR, cnt=Shift.C_CL)
        } 
Example 43
Project: PyVM   Author: ForceBru   File: math.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            0xF6: P(self.mul, _8bit=True),
            0xF7: P(self.mul, _8bit=False)
            } 
Example 44
Project: PyVM   Author: ForceBru   File: math.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            0xF6: [
                P(self.div, _8bit=True, REG=6),  # DIV r/m8
                P(self.div, _8bit=True, REG=7)  # IDIV r/m8
                ],
            0xF7: [
                P(self.div, _8bit=False, REG=6),  # DIV r/m
                P(self.div, _8bit=False, REG=7)   # IDIV r/m
                ]
            } 
Example 45
Project: PyVM   Author: ForceBru   File: math.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            0xF6  : P(self.rm, _8bit=True),
            0xF7  : P(self.rm, _8bit=False),

            0x0FAF: self.r_rm,

            0x6B  : P(self.r_rm_imm, _8bit_imm=True),
            0x69  : P(self.r_rm_imm, _8bit_imm=False)
            } 
Example 46
Project: PyVM   Author: ForceBru   File: floating.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            # FLD
            0xD9: P(self.m_fp, bits=32, REG=0),
            0xDD: P(self.m_fp, bits=64, REG=0),
            0xDB: P(self.m_fp, bits=80, REG=5),
            **{
                0xD9C0 + i: P(self.m_st, i=i)
                for i in range(8)
            }
        } 
Example 47
Project: PyVM   Author: ForceBru   File: floating.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            0xDB: P(self.m_int, is32bit=True, REG=0),
            0xDF: [
                P(self.m_int, is32bit=False, REG=0),
                P(self.m_int, is32bit=False, REG=5),
            ]
        } 
Example 48
Project: PyVM   Author: ForceBru   File: floating.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            0xDF: [
                P(self.fist, size=2, REG=2),  # FIST m16int
                P(self.fist, size=2, REG=3),  # FISTP m16int
                P(self.fist, size=8, REG=7),  # FISTP m64int
            ],
            0xDB: [
                P(self.fist, size=4, REG=2),  # FIST m32int
                P(self.fist, size=4, REG=3),  # FISTP m32int
            ]
        } 
Example 49
Project: PyVM   Author: ForceBru   File: floating.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            **{
                0xDEC8 + i: P(self.fmulp, i=i)
                for i in range(8)
            }
        } 
Example 50
Project: PyVM   Author: ForceBru   File: floating.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.opcodes = {
            **{
                0xDEC0 + i: P(self.faddp, i=i)
                for i in range(8)
            }
        }