• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python six.get_method_function函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中six.get_method_function函数的典型用法代码示例。如果您正苦于以下问题:Python get_method_function函数的具体用法?Python get_method_function怎么用?Python get_method_function使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get_method_function函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: executeMethod

    def executeMethod(self, interfaceObj, methodName, methodArguments, sender):
        m = getattr(self, 'dbus_' + methodName, None)

        iname = interfaceObj.name
        
        if m is None:
            m = self._getDecoratedMethod( iname, methodName )
            if m is None:
                raise NotImplementedError

        if hasattr(m, '_dbusInterface') and m._dbusInterface != iname:
            m = self._getDecoratedMethod( iname, methodName )
            if m is None:
                raise NotImplementedError

        if not hasattr(six.get_method_function(m), '_dbusCaller'):
            self._set_method_flags(m)

        if six.get_method_function(m)._dbusCaller:
            if methodArguments:
                return m( *methodArguments, dbusCaller = sender )
            else:
                return m( dbusCaller = sender )
        else:
            if methodArguments:
                return m( *methodArguments )
            else:
                return m()
开发者ID:alexander255,项目名称:txdbus,代码行数:28,代码来源:objects.py


示例2: save_instancemethod0

def save_instancemethod0(pickler, obj):  # example: cStringIO.StringI
    log.info("Me: %s" % obj)             # XXX: obj.__dict__ handled elsewhere?

    args = (get_method_function(obj), get_method_self(obj)) if PY3 \
        else (get_method_function(obj), get_method_self(obj), obj.im_class)

    pickler.save_reduce(MethodType, args, obj=obj)

    log.info("# Me")
开发者ID:wxiang7,项目名称:dill,代码行数:9,代码来源:dill.py


示例3: __eq__

    def __eq__(self, other):
        r"""
        Return whether ``self == other``.

        EXAMPLES::

            sage: C = IntegerListsLex(2, length=3)
            sage: D = IntegerListsLex(2, length=3); L = D.list();
            sage: E = IntegerListsLex(2, min_length=3)
            sage: F = IntegerListsLex(2, length=3, element_constructor=list)
            sage: G = IntegerListsLex(4, length=3)
            sage: C == C
            True
            sage: C == D
            True
            sage: C == E
            False
            sage: C == F
            False
            sage: C == None
            False
            sage: C == G
            False

        This is a minimal implementation enabling pickling tests. It
        is safe, but one would want the two following objects to be
        detected as equal::

            sage: C = IntegerListsLex(2, ceiling=[1,1,1])
            sage: D = IntegerListsLex(2, ceiling=[1,1,1])
            sage: C == D
            False

        TESTS:

        This used to fail due to poor equality testing. See
        :trac:`17979`, comment 433::

            sage: DisjointUnionEnumeratedSets(Family([2,2],
            ....:     lambda n: IntegerListsLex(n, length=2))).list()
            [[2, 0], [1, 1], [0, 2], [2, 0], [1, 1], [0, 2]]
            sage: DisjointUnionEnumeratedSets(Family([2,2],
            ....:     lambda n: IntegerListsLex(n, length=1))).list()
            [[2], [2]]
        """
        if self.__class__ != other.__class__:
            return False
        if self.backend != other.backend:
            return False
        a = self._element_constructor_
        b = other._element_constructor_
        if ismethod(a):
            a = get_method_function(a)
        if ismethod(b):
            b = get_method_function(b)
        return a == b
开发者ID:saraedum,项目名称:sage-renamed,代码行数:56,代码来源:lists.py


示例4: __init__

    def __init__(self):
        # defiain main tasklet
        self._main_coroutine = _coroutine_getmain()

        self._main_tasklet = _coroutine_getcurrent()
        self._main_tasklet.__class__ = tasklet
        six.get_method_function(self._main_tasklet._init)(self._main_tasklet,
                label='main')
        self._last_task = self._main_tasklet

        self.thread_id = thread.get_ident()
        self._callback = None
        self._run_calls = []
        self._squeue = deque()
        self.append(self._main_tasklet)
开发者ID:RonnyPfannschmidt,项目名称:flower,代码行数:15,代码来源:sched.py


示例5: _get_es_body

    def _get_es_body(self, for_count=False):
        # If to_es has been overridden, call it and raise a deprecation warning
        if isinstance(self.query, ElasticSearchQuery) and six.get_method_function(self.query.to_es) != ElasticSearchQuery.to_es:
            warnings.warn(
                "The .to_es() method on Elasticsearch query classes is deprecated. "
                "Please rename {class_name}.to_es() to {class_name}.get_query()".format(
                    class_name=self.query.__class__.__name__
                ),
                RemovedInWagtail14Warning, stacklevel=2)

            body = {
                'query': self.query.to_es(),
            }
        else:
            body = {
                'query': self.query.get_query()
            }

        if not for_count:
            sort = self.query.get_sort()

            if sort is not None:
                body['sort'] = sort

        return body
开发者ID:nrsimha,项目名称:wagtail,代码行数:25,代码来源:elasticsearch.py


示例6: get_op_handler

    def get_op_handler(self, operation):
        """ Import and load the operation handler """
        # Patch the unversioned sdk path to include the appropriate API version for the
        # resource type in question.
        from importlib import import_module
        import types

        from azure.cli.core.profiles import AZURE_API_PROFILES
        from azure.cli.core.profiles._shared import get_versioned_sdk_path

        for rt in AZURE_API_PROFILES[self.cli_ctx.cloud.profile]:
            if operation.startswith(rt.import_prefix + ".operations."):
                subs = operation[len(rt.import_prefix + ".operations."):]
                operation_group = subs[:subs.index('_operations')]
                operation = operation.replace(
                    rt.import_prefix,
                    get_versioned_sdk_path(self.cli_ctx.cloud.profile, rt, operation_group=operation_group))
            elif operation.startswith(rt.import_prefix):
                operation = operation.replace(rt.import_prefix,
                                              get_versioned_sdk_path(self.cli_ctx.cloud.profile, rt))

        try:
            mod_to_import, attr_path = operation.split('#')
            op = import_module(mod_to_import)
            for part in attr_path.split('.'):
                op = getattr(op, part)
            if isinstance(op, types.FunctionType):
                return op
            return six.get_method_function(op)
        except (ValueError, AttributeError):
            raise ValueError("The operation '{}' is invalid.".format(operation))
开发者ID:sptramer,项目名称:azure-cli,代码行数:31,代码来源:__init__.py


示例7: __details__

 def __details__(self):
     with utils.patch(
         six.get_method_function(self.tasks.service.destroy),
         '__doc__',
         self.__doc__ + (self.tasks.service.destroy.__doc__ or ''),
     ):
         return get_task_details(self.tasks.service.destroy)
开发者ID:renskiy,项目名称:fabricio,代码行数:7,代码来源:tasks.py


示例8: test_get_method_function

def test_get_method_function():
    class X(object):
        def m(self):
            pass
    x = X()
    assert six.get_method_function(x.m) is X.__dict__["m"]
    py.test.raises(AttributeError, six.get_method_function, hasattr)
开发者ID:A-Maze,项目名称:A-Pc,代码行数:7,代码来源:test_six.py


示例9: _init_function

    def _init_function(self, r):
        if isinstance(self.function, str):
            self.function = self.function.lower()
            _mapped = {'inverse': 'inverse_multiquadric',
                       'inverse multiquadric': 'inverse_multiquadric',
                       'thin-plate': 'thin_plate'}
            if self.function in _mapped:
                self.function = _mapped[self.function]

            func_name = "_h_" + self.function
            if hasattr(self, func_name):
                self._function = getattr(self, func_name)
            else:
                functionlist = [x[3:] for x in dir(self) if x.startswith('_h_')]
                raise ValueError("function must be a callable or one of " +
                                     ", ".join(functionlist))
            self._function = getattr(self, "_h_"+self.function)
        elif callable(self.function):
            allow_one = False
            if hasattr(self.function, 'func_code') or \
                   hasattr(self.function, '__code__'):
                val = self.function
                allow_one = True
            elif hasattr(self.function, "im_func"):
                val = get_method_function(self.function)
            elif hasattr(self.function, "__call__"):
                val = get_method_function(self.function.__call__)
            else:
                raise ValueError("Cannot determine number of arguments to function")

            argcount = get_function_code(val).co_argcount
            if allow_one and argcount == 1:
                self._function = self.function
            elif argcount == 2:
                if sys.version_info[0] >= 3:
                    self._function = self.function.__get__(self, Rbf)
                else:
                    import new
                    self._function = new.instancemethod(self.function, self,
                                                        Rbf)
            else:
                raise ValueError("Function argument must take 1 or 2 arguments.")

        a0 = self._function(r)
        if a0.shape != r.shape:
            raise ValueError("Callable must take array and return array of the same shape")
        return a0
开发者ID:jsren,项目名称:sdp-vision-env,代码行数:47,代码来源:rbf.py


示例10: __init__

    def __init__(self):
        # define the main tasklet
        self._main_coroutine = _coroutine_getmain()
        self._main_tasklet = _coroutine_getcurrent()
        self._main_tasklet.__class__ = tasklet
        six.get_method_function(self._main_tasklet._init)(self._main_tasklet,
                label='main')
        self._last_task = self._main_tasklet

        self.thread_id = thread_ident() # the scheduler thread id
        self._lock = threading.Lock() # global scheduler lock

        self._callback = None # scheduler callback
        self._run_calls = [] # runcalls. (tasks where run apply
        self.runnable = deque() # runnable tasks
        self.blocked = 0 # number of blocked/sleeping tasks
        self.append(self._main_tasklet)
开发者ID:benoitc,项目名称:flower,代码行数:17,代码来源:sched.py


示例11: object_build

 def object_build(self, node, obj):
     """recursive method which create a partial ast from real objects
      (only function, class, and method are handled)
     """
     if obj in self._done:
         return self._done[obj]
     self._done[obj] = node
     for name in dir(obj):
         try:
             member = getattr(obj, name)
         except AttributeError:
             # damned ExtensionClass.Base, I know you're there !
             attach_dummy_node(node, name)
             continue
         if ismethod(member):
             member = six.get_method_function(member)
         if isfunction(member):
             # verify this is not an imported function
             filename = getattr(six.get_function_code(member),
                                'co_filename', None)
             if filename is None:
                 assert isinstance(member, object)
                 object_build_methoddescriptor(node, member, name)
             elif filename != getattr(self._module, '__file__', None):
                 attach_dummy_node(node, name, member)
             else:
                 object_build_function(node, member, name)
         elif isbuiltin(member):
             if (not _io_discrepancy(member) and
                     self.imported_member(node, member, name)):
                 continue
             object_build_methoddescriptor(node, member, name)
         elif isclass(member):
             if self.imported_member(node, member, name):
                 continue
             if member in self._done:
                 class_node = self._done[member]
                 if not class_node in node.locals.get(name, ()):
                     node.add_local_node(class_node, name)
             else:
                 class_node = object_build_class(node, member, name)
                 # recursion
                 self.object_build(class_node, member)
             if name == '__class__' and class_node.parent is None:
                 class_node.parent = self._done[self._module]
         elif ismethoddescriptor(member):
             assert isinstance(member, object)
             object_build_methoddescriptor(node, member, name)
         elif isdatadescriptor(member):
             assert isinstance(member, object)
             object_build_datadescriptor(node, member, name)
         elif type(member) in _CONSTANTS:
             attach_const_node(node, name, member)
         else:
             # create an empty node so that the name is actually defined
             attach_dummy_node(node, name, member)
开发者ID:ArthurChiao,项目名称:vim_awesome,代码行数:56,代码来源:raw_building.py


示例12: _find_method

def _find_method(obj, func):
    if obj:
        try:
            func_self = six.get_method_self(func)
        except AttributeError:  # func has no __self__
            pass
        else:
            if func_self is obj:
                return six.get_method_function(func).__name__
    raise ValueError("Function %s is not a method of: %s" % (func, obj))
开发者ID:fighting-one-piece,项目名称:repository-python,代码行数:10,代码来源:mobileonlinescheduler.py


示例13: _validate_args

    def _validate_args(self, swfuncs, tailargs):
        if six.get_method_function(self.help) in swfuncs:
            raise ShowHelp()
        if six.get_method_function(self.version) in swfuncs:
            raise ShowVersion()

        requirements = {}
        exclusions = {}
        for swinfo in self._switches_by_func.values():
            if swinfo.mandatory and not swinfo.func in swfuncs:
                raise MissingMandatorySwitch(
                    "Switch %s is mandatory" % ("/".join(("-" if len(n) == 1 else "--") + n for n in swinfo.names),)
                )
            requirements[swinfo.func] = set(self._switches_by_name[req] for req in swinfo.requires)
            exclusions[swinfo.func] = set(self._switches_by_name[exc] for exc in swinfo.excludes)

        # TODO: compute topological order

        gotten = set(swfuncs.keys())
        for func in gotten:
            missing = set(f.func for f in requirements[func]) - gotten
            if missing:
                raise SwitchCombinationError(
                    "Given %s, the following are missing %r"
                    % (swfuncs[func].swname, [self._switches_by_func[f].names[0] for f in missing])
                )
            invalid = set(f.func for f in exclusions[func]) & gotten
            if invalid:
                raise SwitchCombinationError(
                    "Given %s, the following are invalid %r"
                    % (swfuncs[func].swname, [swfuncs[f].swname for f in invalid])
                )

        m_args, m_varargs, _, m_defaults = inspect.getargspec(self.main)
        max_args = six.MAXSIZE if m_varargs else len(m_args) - 1
        min_args = len(m_args) - 1 - (len(m_defaults) if m_defaults else 0)
        if len(tailargs) < min_args:
            raise PositionalArgumentsError("Expected at least %d positional arguments, got %r" % (min_args, tailargs))
        elif len(tailargs) > max_args:
            raise PositionalArgumentsError("Expected at most %d positional arguments, got %r" % (max_args, tailargs))

        ordered = [(f, a) for _, f, a in sorted([(sf.index, f, sf.val) for f, sf in swfuncs.items()])]
        return ordered, tailargs
开发者ID:biscuit13161,项目名称:plumbum,代码行数:43,代码来源:cli.py


示例14: __str__

    def __str__(self):

        d = self.__dict__
        d['sl'] = self.sl

        try:
            fn = six.get_method_function(self.encode)
            kwargs = {k: fn(v) for k, v in d.items()}
            return self.fmt.format(**kwargs)
        except (ValueError, KeyError) as e:
            raise ValueError('Bad value in {} for {}: {}'.format(d, self.fmt, e))
开发者ID:nmb10,项目名称:geoid,代码行数:11,代码来源:__init__.py


示例15: proxified_elt

def proxified_elt(proxy):
    """Get proxified element.

    :param proxy: proxy element from where get proxified element.
    :return: proxified element. None if proxy is not proxified.
    """

    if ismethod(proxy):
        proxy = get_method_function(proxy)
    result = getattr(proxy, __PROXIFIED__, None)

    return result
开发者ID:b3j0f,项目名称:utils,代码行数:12,代码来源:proxy.py


示例16: object_build

 def object_build(self, node, obj):
     """recursive method which create a partial ast from real objects
      (only function, class, and method are handled)
     """
     if obj in self._done:
         return self._done[obj]
     self._done[obj] = node
     for name in dir(obj):
         try:
             member = getattr(obj, name)
         except AttributeError:
             # damned ExtensionClass.Base, I know you're there !
             attach_dummy_node(node, name)
             continue
         if inspect.ismethod(member):
             member = six.get_method_function(member)
         if inspect.isfunction(member):
             _build_from_function(node, name, member, self._module)
         elif inspect.isbuiltin(member):
             if (not _io_discrepancy(member) and
                     self.imported_member(node, member, name)):
                 continue
             object_build_methoddescriptor(node, member, name)
         elif inspect.isclass(member):
             if self.imported_member(node, member, name):
                 continue
             if member in self._done:
                 class_node = self._done[member]
                 if class_node not in node.locals.get(name, ()):
                     node.add_local_node(class_node, name)
             else:
                 class_node = object_build_class(node, member, name)
                 # recursion
                 self.object_build(class_node, member)
             if name == '__class__' and class_node.parent is None:
                 class_node.parent = self._done[self._module]
         elif inspect.ismethoddescriptor(member):
             assert isinstance(member, object)
             object_build_methoddescriptor(node, member, name)
         elif inspect.isdatadescriptor(member):
             assert isinstance(member, object)
             object_build_datadescriptor(node, member, name)
         elif isinstance(member, _CONSTANTS):
             attach_const_node(node, name, member)
         elif inspect.isroutine(member):
             # This should be called for Jython, where some builtin
             # methods aren't caught by isbuiltin branch.
             _build_from_function(node, name, member, self._module)
         else:
             # create an empty node so that the name is actually defined
             attach_dummy_node(node, name, member)
     return None
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:52,代码来源:raw_building.py


示例17: item_function_wrapper

        def item_function_wrapper(*args, **kwargs):
            # Extract the function from the expression.
            locals_, globals_ = locals(), item_function_globals
            locals_.update(dict(zip(item_function_argspec.args, args)))
            locals_.update(kwargs)
            six.exec_('_function = %s' % expression, globals_, locals_)
            _function = locals_['_function']

            # Initialize benchmark process.
            props = {'times': list()}

            # Create a wrapper for the method to benchmark.
            @wraps(_function)
            def benchmark(*args, **kwargs):
                # nonlocal elapsed, real_iterations
                gc.collect()
                gc.disable()
                start = timer()
                result = _function(*args, **kwargs)
                finish = timer()
                gc.enable()
                props['times'].append(finish - start)
                return result

            # Replace the function with the wrapped function.
            locals_['benchmark'] = benchmark
            six.exec_('%s = benchmark' % expression, globals_, locals_)

            # Attempt to replace it in global scope as well.
            globals_.update(locals_)

            # Get the (unbound) function.
            try:
                locals_['function'] = six.get_method_function(item_function)

            except AttributeError:
                locals_['function'] = item_function

            # Iterate the set number of iterations.
            item.teardown()
            for _ in range(iterations):
                item.setup()
                locals_['args'] = args
                locals_['kwargs'] = kwargs
                six.exec_('function(*args, **kwargs)', globals_, locals_)
                item.teardown()

            # Restore the benchmarked function.
            six.exec_('%s = _function' % expression, globals_, locals_)

            # Construct a Benchmark instance to store the result.
            self._benchmarks.append(Benchmark(item, **props))
开发者ID:neglectedvalue,项目名称:pytest-bench,代码行数:52,代码来源:plugin.py


示例18: get_func_name

def get_func_name(func):
  """Returns name of passed callable."""
  _, func = tf_decorator.unwrap(func)
  if callable(func):
    if tf_inspect.isfunction(func):
      return func.__name__
    elif tf_inspect.ismethod(func):
      return '%s.%s' % (six.get_method_self(func).__class__.__name__,
                        six.get_method_function(func).__name__)
    else:  # Probably a class instance with __call__
      return str(type(func))
  else:
    raise ValueError('Argument must be callable')
开发者ID:JonathanRaiman,项目名称:tensorflow,代码行数:13,代码来源:function_utils.py


示例19: unpickleMethod

def unpickleMethod(im_name,
                   im_self,
                   im_class):
    'support function for copyreg to unpickle method refs'
    try:
        unbound = getattr(im_class, im_name)
        if im_self is None:
            return unbound
        bound = types.MethodType(get_method_function(unbound),
                                 im_self)
        return bound
    except AttributeError:
        # assert im_self is not None,"No recourse: no instance to guess from."
        # Attempt a common fix before bailing -- if classes have
        # changed around since we pickled this method, we may still be
        # able to get it by looking on the instance's current class.
        unbound = getattr(im_self.__class__, im_name)
        if im_self is None:
            return unbound
        bound = types.MethodType(get_method_function(unbound),
                                 im_self)
        return bound
开发者ID:mcognetta,项目名称:sage,代码行数:22,代码来源:fpickle_setup.py


示例20: __init__

    def __init__(self):
        self._cache_groups = dict()
        self._diff_running = False

        regex = re.compile(r'^_cache_(.+)$')

        for (_, m) in inspect.getmembers(type(self),
                                         predicate=lambda p:
                                         (inspect.ismethod or
                                         inspect.isdatadescriptor)):

            if hasattr(m, 'fget'):
                f = m.fget
            elif inspect.ismethod(m):
                f = six.get_method_function(m)
            elif inspect.isfunction(m):
                f = m
            else:
                continue

            fv = six.get_function_code(f).co_freevars

            try:
                closure = six.get_function_closure(f)
            except AttributeError:
                continue

            if closure is None:
                continue

            vs = dict(zip(fv, (c.cell_contents for c in closure)))

            # this is used to make sure we are in the right function
            # i'm not proud of that, by the way
            if '_cache_identifier_pj97YCjgnp' not in vs:
                continue

            try:
                groups = vs['groups']
                method_name = re.match(regex, vs['cache_var_name']).group(1)
            except KeyError:
                continue

            for g in groups:
                if g not in self._cache_groups:
                    self._cache_groups[g] = []
                self._cache_groups[g].append(method_name)

            setattr(self, '_cache_' + method_name, None)
            setattr(self, '_cached_' + method_name, False)
            setattr(self, '_cached_args_' + method_name, dict())
开发者ID:PMBio,项目名称:limix,代码行数:51,代码来源:_hcache.py



注:本文中的six.get_method_function函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python six.get_method_self函数代码示例发布时间:2022-05-27
下一篇:
Python six.get_function_globals函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap