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

Python six.callable函数代码示例

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

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



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

示例1: add_state

    def add_state(self, state, on_enter=None, on_exit=None,
            target=None, terminal=None):
        """Adds a given state to the state machine.

        The on_enter and on_exit callbacks, if provided will be expected to
        take two positional parameters, these being the state being exited (for
        on_exit) or the state being entered (for on_enter) and a second
        parameter which is the event that is being processed that caused the
        state transition.
        """
        if state in self._states:
            raise excp.Duplicate(_("State '%s' already defined") % state)
        if on_enter is not None:
            if not six.callable(on_enter):
                raise ValueError(_("On enter callback must be callable"))
        if on_exit is not None:
            if not six.callable(on_exit):
                raise ValueError(_("On exit callback must be callable"))
        if target is not None and target not in self._states:
            raise excp.InvalidState(_("Target state '%s' does not exist")
                    % target)

        self._states[state] = {
            'terminal': bool(terminal),
            'reactions': {},
            'on_enter': on_enter,
            'on_exit': on_exit,
            'target': target,
        }
        self._transitions[state] = OrderedDict()
开发者ID:ramineni,项目名称:myironic,代码行数:30,代码来源:fsm.py


示例2: add_state

    def add_state(self, state, terminal=False, on_enter=None, on_exit=None):
        """Adds a given state to the state machine.

        The on_enter and on_exit callbacks, if provided will be expected to
        take two positional parameters, these being the state being exited (for
        on_exit) or the state being entered (for on_enter) and a second
        parameter which is the event that is being processed that caused the
        state transition.
        """
        if self.frozen:
            raise excp.FrozenMachine()
        if state in self._states:
            raise excp.Duplicate("State '%s' already defined" % state)
        if on_enter is not None:
            if not six.callable(on_enter):
                raise ValueError("On enter callback must be callable")
        if on_exit is not None:
            if not six.callable(on_exit):
                raise ValueError("On exit callback must be callable")
        self._states[state] = {
            'terminal': bool(terminal),
            'reactions': {},
            'on_enter': on_enter,
            'on_exit': on_exit,
        }
        self._transitions[state] = collections.OrderedDict()
开发者ID:overcastcloud,项目名称:automaton,代码行数:26,代码来源:machines.py


示例3: _select_function

def _select_function(sort, typ):
    if typ in ['F','D']:
        if callable(sort):
            #assume the user knows what they're doing
            sfunction = sort
        elif sort == 'lhp':
            sfunction = lambda x,y: (np.real(x/y) < 0.0)
        elif sort == 'rhp':
            sfunction = lambda x,y: (np.real(x/y) >= 0.0)
        elif sort == 'iuc':
            sfunction = lambda x,y: (abs(x/y) <= 1.0)
        elif sort == 'ouc':
            sfunction = lambda x,y: (abs(x/y) > 1.0)
        else:
            raise ValueError("sort parameter must be None, a callable, or "
                "one of ('lhp','rhp','iuc','ouc')")
    elif typ in ['f','d']:
        if callable(sort):
            #assume the user knows what they're doing
            sfunction = sort
        elif sort == 'lhp':
            sfunction = lambda x,y,z: (np.real((x+y*1j)/z) < 0.0)
        elif sort == 'rhp':
            sfunction = lambda x,y,z: (np.real((x+y*1j)/z) >= 0.0)
        elif sort == 'iuc':
            sfunction = lambda x,y,z: (abs((x+y*1j)/z) <= 1.0)
        elif sort == 'ouc':
            sfunction = lambda x,y,z: (abs((x+y*1j)/z) > 1.0)
        else:
            raise ValueError("sort parameter must be None, a callable, or "
                "one of ('lhp','rhp','iuc','ouc')")
    else: # to avoid an error later
        raise ValueError("dtype %s not understood" % typ)
    return sfunction
开发者ID:jsren,项目名称:sdp-vision-env,代码行数:34,代码来源:_decomp_qz.py


示例4: register

    def register(self, event_type, callback, args=None, kwargs=None, details_filter=None):
        """Register a callback to be called when event of a given type occurs.

        Callback will be called with provided ``args`` and ``kwargs`` and
        when event type occurs (or on any event if ``event_type`` equals to
        :attr:`.ANY`). It will also get additional keyword argument,
        ``details``, that will hold event details provided to the
        :meth:`.notify` method (if a details filter callback is provided then
        the target callback will *only* be triggered if the details filter
        callback returns a truthy value).

        :param event_type: event type input
        :param callback: function callback to be registered.
        :param args: non-keyworded arguments
        :type args: list
        :param kwargs: key-value pair arguments
        :type kwargs: dictionary
        """
        if not six.callable(callback):
            raise ValueError("Event callback must be callable")
        if details_filter is not None:
            if not six.callable(details_filter):
                raise ValueError("Details filter must be callable")
        if not self.can_be_registered(event_type):
            raise ValueError("Disallowed event type '%s' can not have a" " callback registered" % event_type)
        if self.is_registered(event_type, callback, details_filter=details_filter):
            raise ValueError("Event callback already registered with" " equivalent details filter")
        if kwargs:
            for k in self.RESERVED_KEYS:
                if k in kwargs:
                    raise KeyError("Reserved key '%s' not allowed in " "kwargs" % k)
        self._topics[event_type].append(Listener(callback, args=args, kwargs=kwargs, details_filter=details_filter))
开发者ID:FedericoCeratto,项目名称:taskflow,代码行数:32,代码来源:notifier.py


示例5: add_state

    def add_state(self, state, terminal=False, on_enter=None, on_exit=None):
        """Adds a given state to the state machine.

        :param on_enter: callback, if provided will be expected to take
                         two positional parameters, these being state being
                         entered and the second parameter is the event that is
                         being processed that caused the state transition
        :param on_exit: callback, if provided will be expected to take
                         two positional parameters, these being state being
                         entered and the second parameter is the event that is
                         being processed that caused the state transition
        :param state: state being entered or exited
        :type state: string
        """
        if state in self._states:
            raise excp.Duplicate("State '%s' already defined" % state)
        if on_enter is not None:
            if not six.callable(on_enter):
                raise ValueError("On enter callback must be callable")
        if on_exit is not None:
            if not six.callable(on_exit):
                raise ValueError("On exit callback must be callable")
        self._states[state] = {
            'terminal': bool(terminal),
            'reactions': {},
            'on_enter': on_enter,
            'on_exit': on_exit,
        }
        self._transitions[state] = OrderedDict()
开发者ID:Dynavisor,项目名称:taskflow,代码行数:29,代码来源:fsm.py


示例6: __init__

    def __init__(self, execute, name=None, provides=None,
                 requires=None, auto_extract=True, rebind=None, revert=None,
                 version=None, inject=None):
        if not six.callable(execute):
            raise ValueError("Function to use for executing must be"
                             " callable")
        if revert is not None:
            if not six.callable(revert):
                raise ValueError("Function to use for reverting must"
                                 " be callable")
        if name is None:
            name = reflection.get_callable_name(execute)
        super(FunctorTask, self).__init__(name, provides=provides,
                                          inject=inject)
        self._execute = execute
        self._revert = revert
        if version is not None:
            self.version = version
        mapping = self._build_arg_mapping(execute, requires, rebind,
                                          auto_extract)
        self.rebind, exec_requires, self.optional = mapping

        if revert:
            revert_mapping = self._build_arg_mapping(revert, requires, rebind,
                                                     auto_extract)
        else:
            revert_mapping = (self.rebind, exec_requires, self.optional)
        (self.revert_rebind, revert_requires,
         self.revert_optional) = revert_mapping
        self.requires = exec_requires.union(revert_requires)
开发者ID:paperandsoap,项目名称:taskflow,代码行数:30,代码来源:task.py


示例7: _set_obj_extra_data_key

 def _set_obj_extra_data_key(obj, eng):
     my_value = value
     my_key = key
     if callable(my_value):
         while callable(my_value):
             my_value = my_value(obj, eng)
     if callable(my_key):
         while callable(my_key):
             my_key = my_key(obj, eng)
     obj.extra_data[str(my_key)] = my_value
开发者ID:dset0x,项目名称:invenio,代码行数:10,代码来源:marcxml_tasks.py


示例8: _prepare

 def _prepare(cls, elem, attr):
     if not isinstance(elem, six.binary_type):
         serialize = getattr(elem, 'serialize', None)
         if six.callable(serialize):
             return serialize()
         attr_class = cls._get_attr_class(attr)
         serialize = getattr(attr_class, 'serialize', None)
         if six.callable(serialize):
             return serialize(elem)
     return elem
开发者ID:aburan28,项目名称:python-bitcoin,代码行数:10,代码来源:patricia.py


示例9: _foreach

    def _foreach(obj, eng):
        my_list_to_process = []
        step = str(eng.getCurrTaskId())
        try:
            if "_Iterators" not in eng.extra_data:
                eng.extra_data["_Iterators"] = {}
        except KeyError:
            eng.extra_data["_Iterators"] = {}

        if step not in eng.extra_data["_Iterators"]:
            eng.extra_data["_Iterators"][step] = {}
            if cache_data:
                if callable(get_list_function):
                    eng.extra_data["_Iterators"][step]["cache"] = get_list_function(obj, eng)
                elif isinstance(get_list_function, list):
                    eng.extra_data["_Iterators"][step]["cache"] = get_list_function
                else:
                    eng.extra_data["_Iterators"][step]["cache"] = []

                my_list_to_process = eng.extra_data["_Iterators"][step]["cache"]
            if order == "ASC":
                eng.extra_data["_Iterators"][step].update({"value": 0})
            elif order == "DSC":
                eng.extra_data["_Iterators"][step].update({"value": len(my_list_to_process) - 1})
            eng.extra_data["_Iterators"][step]["previous_data"] = obj.data

        if callable(get_list_function):
            if cache_data:
                my_list_to_process = eng.extra_data["_Iterators"][step]["cache"]
            else:
                my_list_to_process = get_list_function(obj, eng)
        elif isinstance(get_list_function, list):
            my_list_to_process = get_list_function
        else:
            my_list_to_process = []

        if order == "ASC" and eng.extra_data["_Iterators"][step]["value"] < len(my_list_to_process):
            obj.data = my_list_to_process[eng.extra_data["_Iterators"][step]["value"]]
            if savename is not None:
                obj.extra_data[savename] = obj.data
            eng.extra_data["_Iterators"][step]["value"] += 1
        elif order == "DSC" and eng.extra_data["_Iterators"][step]["value"] > -1:
            obj.data = my_list_to_process[eng.extra_data["_Iterators"][step]["value"]]
            if savename is not None:
                obj.extra_data[savename] = obj.data
            eng.extra_data["_Iterators"][step]["value"] -= 1
        else:
            obj.data = eng.extra_data["_Iterators"][step]["previous_data"]
            del eng.extra_data["_Iterators"][step]
            coordonatex = len(eng.getCurrTaskId()) - 1
            coordonatey = eng.getCurrTaskId()[coordonatex]
            new_vector = eng.getCurrTaskId()
            new_vector[coordonatex] = coordonatey + 2
            eng.setPosition(eng.getCurrObjId(), new_vector)
开发者ID:SCOAP3,项目名称:invenio,代码行数:54,代码来源:logic_tasks.py


示例10: _get_files_list

    def _get_files_list(obj, eng):
        if callable(parameter):
            unknown = parameter
            while callable(unknown):
                unknown = unknown(obj, eng)

        else:
            unknown = parameter
        result = glob.glob1(path, unknown)
        for i in range(0, len(result)):
            result[i] = path + os.sep + result[i]
        return result
开发者ID:dset0x,项目名称:invenio,代码行数:12,代码来源:marcxml_tasks.py


示例11: add_listener

    def add_listener(self, rule, view_func, **options):
        """Adds a listener to the listeners container; verifies that
        `rule` and `view_func` are callable.

        :raises TypeError: if rule is not callable.
        :raises TypeError: if view_func is not callable
        """
        if not six.callable(rule):
            raise TypeError('rule should be callable')
        if not six.callable(view_func):
            raise TypeError('view_func should be callable')
        self.listeners.append(Listener(rule, view_func, options))
开发者ID:dhruvbaldawa,项目名称:gendo,代码行数:12,代码来源:bot.py


示例12: test_namespace_dereferencing

    def test_namespace_dereferencing(self):
        service = self.object.nested
        assert service is self.object.nested
        assert six.callable(service)
        assert hasattr(service, 'method')
        assert six.callable(service.method)

        service = self.object.nested.deeper
        assert service is self.object.nested.deeper
        assert six.callable(service)
        assert hasattr(service, 'method')
        assert six.callable(service.method)
开发者ID:arhoyling,项目名称:cuckoos,代码行数:12,代码来源:nest_test.py


示例13: register

    def register(self, event_type, callback,
                 args=None, kwargs=None, details_filter=None,
                 weak=False):
        """Register a callback to be called when event of a given type occurs.

        Callback will be called with provided ``args`` and ``kwargs`` and
        when event type occurs (or on any event if ``event_type`` equals to
        :attr:`.ANY`). It will also get additional keyword argument,
        ``details``, that will hold event details provided to the
        :meth:`.notify` method (if a details filter callback is provided then
        the target callback will *only* be triggered if the details filter
        callback returns a truthy value).

        :param event_type: event type to get triggered on
        :param callback: function callback to be registered.
        :param args: non-keyworded arguments
        :type args: list
        :param kwargs: key-value pair arguments
        :type kwargs: dictionary
        :param weak: if the callback retained should be referenced via
                     a weak reference or a strong reference (defaults to
                     holding a strong reference)
        :type weak: bool

        :returns: the listener that was registered
        :rtype: :py:class:`~.Listener`
        """
        if not six.callable(callback):
            raise ValueError("Event callback must be callable")
        if details_filter is not None:
            if not six.callable(details_filter):
                raise ValueError("Details filter must be callable")
        if not self.can_be_registered(event_type):
            raise ValueError("Disallowed event type '%s' can not have a"
                             " callback registered" % event_type)
        if kwargs:
            for k in self.RESERVED_KEYS:
                if k in kwargs:
                    raise KeyError("Reserved key '%s' not allowed in "
                                   "kwargs" % k)
        with self._lock:
            if self.is_registered(event_type, callback,
                                  details_filter=details_filter):
                raise ValueError("Event callback already registered with"
                                 " equivalent details filter")
            listener = Listener(_make_ref(callback, weak=weak),
                                args=args, kwargs=kwargs,
                                details_filter=details_filter,
                                weak=weak)
            listeners = self._topics.setdefault(event_type, [])
            listeners.append(listener)
            return listener
开发者ID:harlowja,项目名称:notifier,代码行数:52,代码来源:_notifier.py


示例14: _update_last_update

 def _update_last_update(obj, eng):
     if "_should_last_run_be_update" in obj.extra_data:
         if obj.extra_data["_should_last_run_be_update"]:
             repository_list_to_process = repository_list
             if not isinstance(repository_list_to_process, list):
                 if callable(repository_list_to_process):
                     while callable(repository_list_to_process):
                         repository_list_to_process = repository_list_to_process(
                             obj, eng)
                 else:
                     repository_list_to_process = [
                         repository_list_to_process]
             for repository in repository_list_to_process:
                 update_lastrun(repository["id"])
开发者ID:SCOAP3,项目名称:invenio,代码行数:14,代码来源:marcxml_tasks.py


示例15: valid_int

def valid_int(x, cast=None):
    '''Ensure that an input value is integer-typed.
    This is primarily useful for ensuring integrable-valued
    array indices.

    Parameters
    ----------
    x : number
        A scalar value to be cast to int

    cast : function [optional]
        A function to modify `x` before casting.
        Default: `np.floor`

    Returns
    -------
    x_int : int
        `x_int = int(cast(x))`

    Raises
    ------
    TypeError
        If `cast` is provided and is not callable.
    '''

    if cast is None:
        cast = np.floor

    if not six.callable(cast):
        raise TypeError('cast parameter must be callable.')

    return int(cast(x))
开发者ID:ScartleRoy,项目名称:librosa,代码行数:32,代码来源:utils.py


示例16: url_encode

def url_encode(obj, charset="utf8", encode_keys=False):
    items = []
    if isinstance(obj, dict):
        for k, v in list(obj.items()):
            items.append((k, v))
    else:
        items = list(items)

    tmp = []
    for k, v in items:
        if encode_keys:
            k = encode(k, charset)

        if not isinstance(v, (tuple, list)):
            v = [v]

        for v1 in v:
            if v1 is None:
                v1 = ''
            elif six.callable(v1):
                v1 = encode(v1(), charset)
            else:
                v1 = encode(v1, charset)
            tmp.append('%s=%s' % (quote(k), quote_plus(v1)))
    return '&'.join(tmp)
开发者ID:adamchainz,项目名称:gaffer,代码行数:25,代码来源:util.py


示例17: __getattr__

    def __getattr__(self, name):
        attr = getattr(self.obj, name)

        if not six.callable(attr):
            return attr

        return functools.partial(self.proxy_callable, name)
开发者ID:APSL,项目名称:fig,代码行数:7,代码来源:verbose_proxy.py


示例18: _func

      def _func(request, *args, **kwargs):
        user = getattr(request, 'user', None)
        is_authenticated = getattr(user, 'is_authenticated', lambda: False)
        if ((user is not None
              and six.callable(is_authenticated) and not is_authenticated())
            or user is None):
          user = None
          try:
            creds = args[:len(authentication_arguments)]
            if len(creds) == 0:
                raise IndexError
            # Django's authenticate() method takes arguments as dict
            user = _authenticate(username=creds[0], password=creds[1], *creds[2:])
            if user is not None:
              args = args[len(authentication_arguments):]
          except IndexError:
              auth_kwargs = {}
              try:
                for auth_kwarg in authentication_arguments:
                  auth_kwargs[auth_kwarg] = kwargs[auth_kwarg]
              except KeyError:
                raise InvalidParamsError(
                  'Authenticated methods require at least '
                  '[%s] or {%s} arguments', authentication_arguments)

              user = _authenticate(**auth_kwargs)
              if user is not None:
                for auth_kwarg in authentication_arguments:
                  kwargs.pop(auth_kwarg)
          if user is None:
            raise InvalidCredentialsError
          request.user = user
        return func(request, *args, **kwargs)
开发者ID:mutax,项目名称:django-json-rpc,代码行数:33,代码来源:__init__.py


示例19: merge_graphs

def merge_graphs(graph, *graphs, **kwargs):
    """Merges a bunch of graphs into a new graph.

    If no additional graphs are provided the first graph is
    returned unmodified otherwise the merged graph is returned.
    """
    tmp_graph = graph
    allow_overlaps = kwargs.get('allow_overlaps', False)
    overlap_detector = kwargs.get('overlap_detector')
    if overlap_detector is not None and not six.callable(overlap_detector):
        raise ValueError("Overlap detection callback expected to be callable")
    elif overlap_detector is None:
        overlap_detector = (lambda to_graph, from_graph:
                            len(to_graph.subgraph(from_graph.nodes_iter())))
    for g in graphs:
        # This should ensure that the nodes to be merged do not already exist
        # in the graph that is to be merged into. This could be problematic if
        # there are duplicates.
        if not allow_overlaps:
            # Attempt to induce a subgraph using the to be merged graphs nodes
            # and see if any graph results.
            overlaps = overlap_detector(graph, g)
            if overlaps:
                raise ValueError("Can not merge graph %s into %s since there "
                                 "are %s overlapping nodes (and we do not "
                                 "support merging nodes)" % (g, graph,
                                                             overlaps))
        graph = nx.algorithms.compose(graph, g)
    # Keep the first graphs name.
    if graphs:
        graph.name = tmp_graph.name
    return graph
开发者ID:Dynavisor,项目名称:taskflow,代码行数:32,代码来源:graph.py


示例20: handle_key

    def handle_key(self, key, check_parent=True):
        '''Handle a key press in this window.'''
        
        # First try the first responder if this window has one, but don't allow
        # it to check with its parent (False second parameter) so we don't recurse
        # and get a stack overflow
        for first_responder in reversed(self.first_responders):
            if first_responder.handle_key(key, False):
                return True       

        # Check our key map to see if we have any actions. Actions don't take
        # any arguments, they must be callable
        if key in self.key_actions:
            key_action = self.key_actions[key]
            key_action['callback']()
            return True
        # Check if there is a wildcard key for any key
        if -1 in self.key_actions:
            key_action = self.key_actions[-1]
            key_action['callback']()
            return True
        # Check if the window delegate wants to handle this key press
        if self.delegate:      
            if six.callable(getattr(self.delegate, "handle_key", None)):
                if self.delegate.handle_key(self, key):
                    return True
            if self.delegate(self, key):
                return True
        # Check if we have a parent window and if so, let the parent 
        # window handle the key press
        if check_parent and self.parent:
            return self.parent.handle_key(key, True)
        else:
            return False # Key not handled
开发者ID:32bitmicro,项目名称:riscv-lldb,代码行数:34,代码来源:lldbcurses.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python six.create_bound_method函数代码示例发布时间:2022-05-27
下一篇:
Python six.byte2int函数代码示例发布时间: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