Python six.callable() Examples

The following are 30 code examples for showing how to use six.callable(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module six , or try the search function .

Example 1
Project: lambda-packs   Author: ryfeus   File: device_setter.py    License: MIT License 6 votes vote down vote up
def __init__(self, ps_tasks, ps_device, worker_device, merge_devices, ps_ops,
               ps_strategy):
    """Create a new `_ReplicaDeviceChooser`.

    Args:
      ps_tasks: Number of tasks in the `ps` job.
      ps_device: String.  Name of the `ps` job.
      worker_device: String.  Name of the `worker` job.
      merge_devices: Boolean. Set to True to allow merging of device specs.
      ps_ops: List of strings representing `Operation` types that need to be
        placed on `ps` devices.
      ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by
        `ps_ops`), that takes the `Operation` and returns the ps task index to
        use.
    """
    self._ps_tasks = ps_tasks
    self._ps_device = ps_device
    self._worker_device = worker_device
    self._merge_devices = merge_devices
    self._ps_ops = ps_ops
    self._ps_strategy = ps_strategy 
Example 2
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: device_setter.py    License: MIT License 6 votes vote down vote up
def __init__(self, ps_tasks, ps_device, worker_device, merge_devices, ps_ops,
               ps_strategy):
    """Create a new `_ReplicaDeviceChooser`.

    Args:
      ps_tasks: Number of tasks in the `ps` job.
      ps_device: String.  Name of the `ps` job.
      worker_device: String.  Name of the `worker` job.
      merge_devices: Boolean. Set to True to allow merging of device specs.
      ps_ops: List of strings representing `Operation` types that need to be
        placed on `ps` devices.
      ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by
        `ps_ops`), that takes the `Operation` and returns the ps task index to
        use.
    """
    self._ps_tasks = ps_tasks
    self._ps_device = ps_device
    self._worker_device = worker_device
    self._merge_devices = merge_devices
    self._ps_ops = ps_ops
    self._ps_strategy = ps_strategy 
Example 3
Project: related   Author: genomoncology   File: converters.py    License: MIT License 6 votes vote down vote up
def to_sequence_field(cls):
    """
    Returns a callable instance that will convert a value to a Sequence.

    :param cls: Valid class type of the items in the Sequence.
    :return: instance of the SequenceConverter.
    """
    class SequenceConverter(object):

        def __init__(self, cls):
            self._cls = cls

        @property
        def cls(self):
            return resolve_class(self._cls)

        def __call__(self, values):
            values = values or []
            args = [to_model(self.cls, value) for value in values]
            return TypedSequence(cls=self.cls, args=args)

    return SequenceConverter(cls) 
Example 4
Project: related   Author: genomoncology   File: converters.py    License: MIT License 6 votes vote down vote up
def to_set_field(cls):
    """
    Returns a callable instance that will convert a value to a Sequence.

    :param cls: Valid class type of the items in the Sequence.
    :return: instance of the SequenceConverter.
    """
    class SetConverter(object):

        def __init__(self, cls):
            self._cls = cls

        @property
        def cls(self):
            return resolve_class(self._cls)

        def __call__(self, values):
            values = values or set()
            args = {to_model(self.cls, value) for value in values}
            return TypedSet(cls=self.cls, args=args)

    return SetConverter(cls) 
Example 5
Project: related   Author: genomoncology   File: converters.py    License: MIT License 6 votes vote down vote up
def to_date_field(formatter):
    """
    Returns a callable instance that will convert a string to a Date.

    :param formatter: String that represents data format for parsing.
    :return: instance of the DateConverter.
    """
    class DateConverter(object):

        def __init__(self, formatter):
            self.formatter = formatter

        def __call__(self, value):
            if isinstance(value, string_types):
                value = datetime.strptime(value, self.formatter).date()

            if isinstance(value, datetime):
                value = value.date()

            return value

    return DateConverter(formatter) 
Example 6
Project: related   Author: genomoncology   File: converters.py    License: MIT License 6 votes vote down vote up
def to_time_field(formatter):
    """
    Returns a callable instance that will convert a string to a Time.

    :param formatter: String that represents data format for parsing.
    :return: instance of the TimeConverter.
    """
    class TimeConverter(object):

        def __init__(self, formatter):
            self.formatter = formatter

        def __call__(self, value):
            if isinstance(value, string_types):
                value = datetime.strptime(value, self.formatter).time()

            return value

    return TimeConverter(formatter) 
Example 7
Project: neural-network-animation   Author: miloharper   File: axis.py    License: MIT License 6 votes vote down vote up
def contains(self, mouseevent):
        """Test whether the mouse event occured in the x axis.
        """
        if six.callable(self._contains):
            return self._contains(self, mouseevent)

        x, y = mouseevent.x, mouseevent.y
        try:
            trans = self.axes.transAxes.inverted()
            xaxes, yaxes = trans.transform_point((x, y))
        except ValueError:
            return False, {}
        l, b = self.axes.transAxes.transform_point((0, 0))
        r, t = self.axes.transAxes.transform_point((1, 1))
        inaxis = xaxes >= 0 and xaxes <= 1 and (
                   (y < b and y > b - self.pickradius) or
                   (y > t and y < t + self.pickradius))
        return inaxis, {} 
Example 8
Project: neural-network-animation   Author: miloharper   File: axis.py    License: MIT License 6 votes vote down vote up
def contains(self, mouseevent):
        """Test whether the mouse event occurred in the y axis.

        Returns *True* | *False*
        """
        if six.callable(self._contains):
            return self._contains(self, mouseevent)

        x, y = mouseevent.x, mouseevent.y
        try:
            trans = self.axes.transAxes.inverted()
            xaxes, yaxes = trans.transform_point((x, y))
        except ValueError:
            return False, {}
        l, b = self.axes.transAxes.transform_point((0, 0))
        r, t = self.axes.transAxes.transform_point((1, 1))
        inaxis = yaxes >= 0 and yaxes <= 1 and (
                   (x < l and x > l - self.pickradius) or
                   (x > r and x < r + self.pickradius))
        return inaxis, {} 
Example 9
Project: neural-network-animation   Author: miloharper   File: __init__.py    License: MIT License 6 votes vote down vote up
def wrap(self, fmt, func, level='helpful', always=True):
        """
        return a callable function that wraps func and reports it
        output through the verbose handler if current verbosity level
        is higher than level

        if always is True, the report will occur on every function
        call; otherwise only on the first time the function is called
        """
        assert six.callable(func)
        def wrapper(*args, **kwargs):
            ret = func(*args, **kwargs)

            if (always or not wrapper._spoke):
                spoke = self.report(fmt%ret, level)
                if not wrapper._spoke: wrapper._spoke = spoke
            return ret
        wrapper._spoke = False
        wrapper.__doc__ = func.__doc__
        return wrapper 
Example 10
Project: neural-network-animation   Author: miloharper   File: patches.py    License: MIT License 6 votes vote down vote up
def contains(self, mouseevent, radius=None):
        """Test whether the mouse event occurred in the patch.

        Returns T/F, {}
        """
        # This is a general version of contains that should work on any
        # patch with a path.  However, patches that have a faster
        # algebraic solution to hit-testing should override this
        # method.
        if six.callable(self._contains):
            return self._contains(self, mouseevent)
        if radius is None:
            radius = self.get_linewidth()
        inside = self.get_path().contains_point(
            (mouseevent.x, mouseevent.y), self.get_transform(), radius)
        return inside, {} 
Example 11
Project: neural-network-animation   Author: miloharper   File: table.py    License: MIT License 6 votes vote down vote up
def contains(self, mouseevent):
        """Test whether the mouse event occurred in the table.

        Returns T/F, {}
        """
        if six.callable(self._contains):
            return self._contains(self, mouseevent)

        # TODO: Return index of the cell containing the cursor so that the user
        # doesn't have to bind to each one individually.
        if self._cachedRenderer is not None:
            boxes = [self._cells[pos].get_window_extent(self._cachedRenderer)
                 for pos in six.iterkeys(self._cells)
                 if pos[0] >= 0 and pos[1] >= 0]
            bbox = Bbox.union(boxes)
            return bbox.contains(mouseevent.x, mouseevent.y), {}
        else:
            return False, {} 
Example 12
Project: neural-network-animation   Author: miloharper   File: image.py    License: MIT License 6 votes vote down vote up
def contains(self, mouseevent):
        """
        Test whether the mouse event occured within the image.
        """
        if six.callable(self._contains):
            return self._contains(self, mouseevent)
        # TODO: make sure this is consistent with patch and patch
        # collection on nonlinear transformed coordinates.
        # TODO: consider returning image coordinates (shouldn't
        # be too difficult given that the image is rectilinear
        x, y = mouseevent.xdata, mouseevent.ydata
        xmin, xmax, ymin, ymax = self.get_extent()
        if xmin > xmax:
            xmin, xmax = xmax, xmin
        if ymin > ymax:
            ymin, ymax = ymax, ymin
        #print x, y, xmin, xmax, ymin, ymax
        if x is not None and y is not None:
            inside = ((x >= xmin) and (x <= xmax) and
                      (y >= ymin) and (y <= ymax))
        else:
            inside = False

        return inside, {} 
Example 13
Project: neural-network-animation   Author: miloharper   File: cbook.py    License: MIT License 6 votes vote down vote up
def __call__(self, *args, **kwargs):
        '''
        Proxy for a call to the weak referenced object. Take
        arbitrary params to pass to the callable.

        Raises `ReferenceError`: When the weak reference refers to
        a dead object
        '''
        if self.inst is not None and self.inst() is None:
            raise ReferenceError
        elif self.inst is not None:
            # build a new instance method with a strong reference to the
            # instance

            mtd = types.MethodType(self.func, self.inst())

        else:
            # not a bound method, just return the func
            mtd = self.func
        # invoke the callable and return the result
        return mtd(*args, **kwargs) 
Example 14
Project: neural-network-animation   Author: miloharper   File: artist.py    License: MIT License 6 votes vote down vote up
def update(self, props):
        """
        Update the properties of this :class:`Artist` from the
        dictionary *prop*.
        """
        store = self.eventson
        self.eventson = False
        changed = False

        for k, v in six.iteritems(props):
            func = getattr(self, 'set_' + k, None)
            if func is None or not six.callable(func):
                raise AttributeError('Unknown property %s' % k)
            func(v)
            changed = True
        self.eventson = store
        if changed:
            self.pchanged() 
Example 15
Project: neural-network-animation   Author: miloharper   File: artist.py    License: MIT License 6 votes vote down vote up
def get_aliases(self):
        """
        Get a dict mapping *fullname* -> *alias* for each *alias* in
        the :class:`~matplotlib.artist.ArtistInspector`.

        e.g., for lines::

          {'markerfacecolor': 'mfc',
           'linewidth'      : 'lw',
          }

        """
        names = [name for name in dir(self.o) if
                 (name.startswith('set_') or name.startswith('get_'))
                 and six.callable(getattr(self.o, name))]
        aliases = {}
        for name in names:
            func = getattr(self.o, name)
            if not self.is_alias(func):
                continue
            docstring = func.__doc__
            fullname = docstring[10:]
            aliases.setdefault(fullname[4:], {})[name[4:]] = None
        return aliases 
Example 16
Project: neural-network-animation   Author: miloharper   File: artist.py    License: MIT License 6 votes vote down vote up
def _get_setters_and_targets(self):
        """
        Get the attribute strings and a full path to where the setter
        is defined for all setters in an object.
        """

        setters = []
        for name in dir(self.o):
            if not name.startswith('set_'):
                continue
            o = getattr(self.o, name)
            if not six.callable(o):
                continue
            if len(inspect.getargspec(o)[0]) < 2:
                continue
            func = o
            if self.is_alias(func):
                continue
            source_class = self.o.__module__ + "." + self.o.__name__
            for cls in self.o.mro():
                if name in cls.__dict__:
                    source_class = cls.__module__ + "." + cls.__name__
                    break
            setters.append((name[4:], source_class + "." + name))
        return setters 
Example 17
Project: neural-network-animation   Author: miloharper   File: artist.py    License: MIT License 6 votes vote down vote up
def properties(self):
        """
        return a dictionary mapping property name -> value
        """
        o = self.oorig
        getters = [name for name in dir(o)
                   if name.startswith('get_')
                   and six.callable(getattr(o, name))]
        #print getters
        getters.sort()
        d = dict()
        for name in getters:
            func = getattr(o, name)
            if self.is_alias(func):
                continue

            try:
                val = func()
            except:
                continue
            else:
                d[name[4:]] = val

        return d 
Example 18
Project: neural-network-animation   Author: miloharper   File: dates.py    License: MIT License 6 votes vote down vote up
def __call__(self, x, pos=None):
        locator_unit_scale = float(self._locator._get_unit())
        fmt = self.defaultfmt

        # Pick the first scale which is greater than the locator unit.
        for possible_scale in sorted(self.scaled):
            if possible_scale >= locator_unit_scale:
                fmt = self.scaled[possible_scale]
                break

        if isinstance(fmt, six.string_types):
            self._formatter = DateFormatter(fmt, self._tz)
            result = self._formatter(x, pos)
        elif six.callable(fmt):
            result = fmt(x, pos)
        else:
            raise TypeError('Unexpected type passed to {!r}.'.formatter(self))

        return result 
Example 19
Project: neural-network-animation   Author: miloharper   File: patheffects.py    License: MIT License 6 votes vote down vote up
def _update_gc(self, gc, new_gc_dict):
        """
        Update the given GraphicsCollection with the given
        dictionary of properties. The keys in the dictionary are used to
        identify the appropriate set_ method on the gc.

        """
        new_gc_dict = new_gc_dict.copy()

        dashes = new_gc_dict.pop("dashes", None)
        if dashes:
            gc.set_dashes(**dashes)

        for k, v in six.iteritems(new_gc_dict):
            set_method = getattr(gc, 'set_' + k, None)
            if set_method is None or not six.callable(set_method):
                raise AttributeError('Unknown property {}'.format(k))
            set_method(v)
        return gc 
Example 20
Project: yaql   Author: openstack   File: system.py    License: Apache License 2.0 6 votes vote down vote up
def call(callable_, *args, **kwargs):
    """:yaql:call

    Evaluates function with specified args and kwargs and returns the
    result.
    This function is used to transform expressions like '$foo(args, kwargs)'
    to '#call($foo, args, kwargs)'.
    Note that to use this functionality 'delegate' mode has to be enabled.

    :signature: call(callable, args, kwargs)
    :arg callable: callable function
    :argType callable: python type
    :arg args: sequence of items to be used for calling
    :argType args: sequence
    :arg kwargs: dictionary with kwargs to be used for calling
    :argType kwargs: mapping
    :returnType: any (callable return type)
    """
    return callable_(*args, **kwargs) 
Example 21
Project: yaql   Author: openstack   File: system.py    License: Apache License 2.0 6 votes vote down vote up
def call_func(context, engine, name, args, kwargs, receiver=utils.NO_VALUE):
    """:yaql:call

    Evaluates function name with specified args and kwargs and returns the
    result.

    :signature: call(name, args, kwargs)
    :arg name: name of callable
    :argType name: string
    :arg args: sequence of items to be used for calling
    :argType args: sequence
    :arg kwargs: dictionary with kwargs to be used for calling
    :argType kwargs: mapping
    :returnType: any (callable return type)

    .. code::

        yaql> call(let, [1, 2], {a => 3, b => 4}) -> $1 + $a + $2 + $b
        10
    """
    return context(name, engine, receiver)(
        *args, **utils.filter_parameters_dict(kwargs)) 
Example 22
Project: deep_image_model   Author: tobegit3hub   File: device_setter.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, ps_tasks, ps_device, worker_device, merge_devices, ps_ops,
               ps_strategy):
    """Create a new `_ReplicaDeviceChooser`.

    Args:
      ps_tasks: Number of tasks in the `ps` job.
      ps_device: String.  Name of the `ps` job.
      worker_device: String.  Name of the `worker` job.
      merge_devices: Boolean. Set to True to allow merging of device specs.
      ps_ops: List of strings representing `Operation` types that need to be
        placed on `ps` devices.
      ps_strategy: A callable invoked for every ps `Operation` (i.e. matched by
        `ps_ops`), that takes the `Operation` and returns the ps task index to
        use.
    """
    self._ps_tasks = ps_tasks
    self._ps_device = ps_device
    self._worker_device = worker_device
    self._merge_devices = merge_devices
    self._ps_ops = ps_ops
    self._ps_strategy = ps_strategy 
Example 23
Project: nefertari   Author: ramses-tech   File: data.py    License: Apache License 2.0 6 votes vote down vote up
def obj2dict(obj, classkey=None):
    if isinstance(obj, dict):
        for k in obj.keys():
            obj[k] = obj2dict(obj[k], classkey)
        return obj
    elif issequence(obj):
        return [obj2dict(v, classkey) for v in obj]
    elif hasattr(obj, "__dict__"):
        data = dictset([
            (key, obj2dict(value, classkey))
            for key, value in obj.__dict__.items()
            if not six.callable(value) and not key.startswith('_')
        ])
        if classkey is not None and hasattr(obj, "__class__"):
            data[classkey] = obj.__class__.__name__
        return data
    else:
        return obj 
Example 24
Project: deepmatcher   Author: anhaidgroup   File: _utils.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_module(cls, op, required=False, op_kwarg=None, **kwargs):
    if op is None and not required or isinstance(op, cls):
        return op
    elif required:
        return cls(**kwargs)
    elif isinstance(op, six.string_types):
        if op_kwarg is not None:
            kwargs[op_kwarg] = op
            return cls(**kwargs)
        else:
            return cls(op, **kwargs)
    elif six.callable(op) and not isinstance(op, torch.nn.Module):
        return dm.modules.LazyModuleFn(op)
    else:
        raise ValueError(
            str(cls) + ' arg must be a valid string, a ' + str(cls) + ' object, or a '
            'callable.') 
Example 25
Project: insights-core   Author: RedHatInsights   File: dr.py    License: Apache License 2.0 6 votes vote down vote up
def set_enabled(component, enabled=True):
    """
    Enable a component for evaluation. If set to False, the component is
    skipped, and all components that require it will not execute. If component
    is a fully qualified name string of a callable object instead of the
    callable object itself, the component's module is loaded as a side effect
    of calling this function.

    Args:
        component (str or callable): fully qualified name of the component or
            the component object itself.
        enabled (bool): whether the component is enabled for evaluation.

    Returns:
        None
    """
    ENABLED[get_component(component) or component] = enabled 
Example 26
Project: automaton   Author: openstack   File: machines.py    License: Apache License 2.0 5 votes vote down vote up
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() 
Example 27
Project: automaton   Author: openstack   File: machines.py    License: Apache License 2.0 5 votes vote down vote up
def add_reaction(self, state, event, reaction, *args, **kwargs):
        """Adds a reaction that may get triggered by the given event & state.

        Reaction callbacks may (depending on how the state machine is ran) be
        used after an event is processed (and a transition occurs) to cause the
        machine to react to the newly arrived at stable state.

        These callbacks are expected to accept three default positional
        parameters (although more can be passed in via *args and **kwargs,
        these will automatically get provided to the callback when it is
        activated *ontop* of the three default). The three default parameters
        are the last stable state, the new stable state and the event that
        caused the transition to this new stable state to be arrived at.

        The expected result of a callback is expected to be a new event that
        the callback wants the state machine to react to. This new event
        may (depending on how the state machine is ran) get processed (and
        this process typically repeats) until the state machine reaches a
        terminal state.
        """
        if self.frozen:
            raise excp.FrozenMachine()
        if state not in self._states:
            raise excp.NotFound("Can not add a reaction to event '%s' for an"
                                " undefined state '%s'" % (event, state))
        if not six.callable(reaction):
            raise ValueError("Reaction callback must be callable")
        if event not in self._states[state]['reactions']:
            self._states[state]['reactions'][event] = (reaction, args, kwargs)
        else:
            raise excp.Duplicate("State '%s' reaction to event '%s'"
                                 " already defined" % (state, event)) 
Example 28
Project: a10-neutron-lbaas   Author: a10networks   File: resources.py    License: Apache License 2.0 5 votes vote down vote up
def apply_template(template, *args, **kw):
    """Applies every callable in any Mapping or Iterable"""
    if six.callable(template):
        return template(*args, **kw)
    if isinstance(template, six.string_types):
        return template
    if isinstance(template, collections.Mapping):
        return template.__class__((k, apply_template(v, *args, **kw)) for k, v in template.items())
    if isinstance(template, collections.Iterable):
        return template.__class__(apply_template(v, *args, **kw) for v in template)
    return template 
Example 29
Project: zero   Author: bzhangGo   File: parallel.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def local_device_setter(num_devices=1,
                        ps_device_type='cpu',
                        worker_device='/cpu:0',
                        ps_ops=None,
                        ps_strategy=None):
    if ps_ops is None:
        ps_ops = ['Variable', 'VariableV2', 'VarHandleOp']

    if ps_strategy is None:
        ps_strategy = device_setter._RoundRobinStrategy(num_devices)
    if not six.callable(ps_strategy):
        raise TypeError("ps_strategy must be callable")

    def _local_device_chooser(op):
        current_device = pydev.DeviceSpec.from_string(op.device or "")

        node_def = op if isinstance(op, node_def_pb2.NodeDef) else op.node_def
        if node_def.op in ps_ops:
            ps_device_spec = pydev.DeviceSpec.from_string(
                '/{}:{}'.format(ps_device_type, ps_strategy(op)))

            ps_device_spec.merge_from(current_device)
            return ps_device_spec.to_string()
        else:
            worker_device_spec = pydev.DeviceSpec.from_string(worker_device or "")
            worker_device_spec.merge_from(current_device)
            return worker_device_spec.to_string()

    return _local_device_chooser 
Example 30
Project: related   Author: genomoncology   File: converters.py    License: MIT License 5 votes vote down vote up
def to_child_field(cls):
    """
    Returns an callable instance that will convert a value to a Child object.

    :param cls: Valid class type of the Child.
    :return: instance of ChildConverter.
    """

    class ChildConverter(object):

        def __init__(self, cls):
            self._cls = cls

        @property
        def cls(self):
            return resolve_class(self._cls)

        def __call__(self, value):
            try:
                # Issue #33: if value is the class and callable, then invoke
                if value == self._cls and callable(value):
                    value = value()

                return to_model(self.cls, value)
            except ValueError as e:
                error_msg = CHILD_ERROR_MSG.format(value, self.cls, str(e))
                raise ValueError(error_msg)

    return ChildConverter(cls)