Signal and Callable objects are among the core building blocks of Kaa and are used extensively throughout the framework.
Callable objects encapsulate a callable (such as a function or method) and, optionally, any number of arguments and keyword arguments. Callable objects are in turn invokable like any other native callable, and upon invocation will call the underlying (wrapped) function or method, passing it all arguments passed during invocation combined with all arguments passed to the constructor.
One very common use-case of Callable objects is any time a callback function is required, such as with signals (described later). They can be used to construct partial functions:
>>> square = kaa.Callable(pow, 2)
>>> print square(5)
25
(Of course this example is a bit contrived, because you could use lambda to achieve the same result with less overhead. But it helps to start simple.)
By default, all arguments passed upon invocation of the Callable are passed to the wrapped callable first, followed by arguments passed upon construction. So the above example translates to pow(5, 2). It is possible to reverse this behaviour by setting the init_args_first property to True:
>>> square.init_args_first = True
>>> square(5) # Of course, now this isn't a square
32
Keyword arguments work in a similar way. Keyword arguments given to the constructor as well as those passed upon invocation are passed to the wrapped callable. When init_args_first is False (default), keyword arguments passed on invocation take precedence (overwrite) same-named keyword arguments passed on the constructor. When True, keyword arguments from the constructor take precedence over those passed upon invocation.
Here’s an example that more clearly demonstrates the rules of precedence:
>>> def func(*args, **kwargs):
... print 'Callable:', args, kwargs
...
>>> cb = kaa.Callable(func, 1, 2, foo=42, bar='kaa')
>>> cb()
Callable: (1, 2) {'foo': 42, 'bar': 'kaa'}
>>> cb('hello world', foo='overrides', another='kwarg')
Callable: ('hello world', 1, 2) {'foo': 'overrides', 'bar': 'kaa', 'another': 'kwarg'}
>>> cb.init_args_first = True
>>> cb('hello world', foo="doesn't override", another='kwarg')
Callable: (1, 2, 'hello world') {'foo': 42, 'bar': 'kaa', 'another': 'kwarg'}
Because Callable objects hold references to the function, or to the class instance in the case of a method, and any arguments passed at construction time, those objects remain alive as long as the Callable is referenced. This is not always what’s wanted, and in those cases the WeakCallable variant can be used.
With WeakCallable, only weak references are held to the callable and constructor arguments. When any of the wrapped objects are destroyed, the WeakCallable ceases to be valid. One common use-case for WeakCallable is to avoid cyclical references. For example, an object may hold an IOMonitor on some file descriptor, and have a method invoked when there’s activity. Consider this code fragment:
class MyClass(object):
def __init__(self, fd):
self._monitor = kaa.IOMonitor(self._handle_read)
self._monitor.register(fd)
In this example, a reference cycle is created: the MyClass instance holds a reference to the IOMonitor, which holds a reference to the _handle_read method of the MyClass instance (which implicitly holds a reference to the MyClass instance itself).
You might be thinking this isn’t a problem: after all, Python has a garbage collector that will detect and break orphaned cyclic references. However, because the file descriptor fd is registered (with the notifier), Kaa keeps an internal reference to the IOMonitor. Therefore, even if all user-visible references to the MyClass instance are gone, neither that object nor the IOMonitor ever get deleted (at least so long as the fd is open). And furthermore, MyClass._handle_read() will continue to be invoked upon activity of the fd.
If you want the IOMonitor to automatically become unregistered when the callback (or specifically the instance the method belongs to) is destroyed, you can use a WeakCallable:
self._monitor = kaa.IOMonitor(kaa.WeakCallable(self._handle_read))
In this example, when the notifier would normally invoke the callback (when there is activity on the registered file descriptor), it will find the weak callable is in fact dead and automatically unregister the monitor. With this, the instance of MyClass is allowed to be destroyed (at least insofar as Kaa would not hold any internal references to it).
Now, the previous example is a bit clumsy because it requires the callback to be invoked (or attempted to be) before the monitor is automatically unregistered. It would be cleaner if the monitor was registered immediately when the MyClass instance is destroyed. For this, the weak variant of IOMonitor called WeakIOMonitor can be used:
self._monitor = kaa.WeakIOMonitor(self._handle_read)
Weak variants of these notifier-aware classes exist throughout Kaa: WeakIOMonitor, WeakTimer, WeakOneShotTimer, WeakEventHandler.
Wraps an existing callable, binding to it any given args and kwargs.
When the Callable object is invoked, the arguments passed on invocation are combined with the arguments specified at construction time and the underlying callable is invoked with those arguments.
Parameters: |
|
---|
kaa.Callable
__call__() | Invoke the callable. |
---|
ignore_caller_args | read/write | If True, any arguments passed when invoking the Callable object are not passed to the underlying callable. |
---|---|---|
init_args_first | read/write | If True, any arguments passed upon invocation of the Callable object take precedence over those arguments passed at object initialization time. e.g. func(constructor_args..., invocation_args...) |
Invoke the callable.
The arguments passed here take precedence over constructor arguments if the init_args_first property is False (default). The wrapped callable’s return value is returned.
If True, any arguments passed when invoking the Callable object are not passed to the underlying callable.
Default value is False, so all arguments are passed to the callable.
If True, any arguments passed upon invocation of the Callable object take precedence over those arguments passed at object initialization time. e.g. func(constructor_args..., invocation_args...)
Default value is False, so invocation arguments take precedence over init arguments. e.g. func(invocation_args..., constructor_args...)
“A takes precedence over B” means that non-keyword arguments are passed in order of A + B, and keyword arguments from A override same-named keyword arguments from B.
Weak variant of the Callable class. Only weak references are held for non-intrinsic types (i.e. any user-defined object).
If the callable is a method, only a weak reference is kept to the instance to which that method belongs, and only weak references are kept to any of the arguments and keyword arguments.
This also works recursively, so if there are nested data structures, for example kwarg=[1, [2, [3, my_object]]], only a weak reference is held for my_object.
kaa.Callable
└─ kaa.WeakCallable
weakref_destroyed_cb | read/write | A callback that’s invoked when any of the weak references held (either for the callable or any of the arguments passed on the constructor) become dead. |
---|
A callback that’s invoked when any of the weak references held (either for the callable or any of the arguments passed on the constructor) become dead.
When this happens, the Callable is invalid and any attempt to invoke it will raise a kaa.CallableError.
The callback is passed the weakref object (which is probably dead). If the callback requires additional arguments, they can be encapsulated in a kaa.Callable object.
In Kaa, signals don’t refer to Unix signals, but rather are similar to gtk+ signals in that they are hooks to allow you to connect callbacks to be triggered when certain events occur. A signal may have any number of callbacks connected to it, and when it is emitted, all the callbacks are invoked. For example, kaa.IOChannel has a signal called read which is emitted when a chunk of data has been read from the IO channel.
Classes that offer signals have a signals attribute, which is a dictionary (or in fact a kaa.Signals object, which behaves like a dictionary), whose keys are the names of the signal supported by that object, and the corresponding values are kaa.Signal objects. For example:
def handle_data_chunk(data, userdata):
print 'Read:', data
iochannel.signals['read'].connect(handle_data_chunk, 'This is user data')
The connect() method accepts a callable and arbitrary non-keyword and keyword arguments, which are passed to the callback. This method, and the whole connect_* family of methods in general, constructs a Callable object implicitly (and in fact return that newly constructed Callable). So the above example is equivalent to:
iochannel.signals['read'].connect(kaa.Callable(handle_data_chunk, 'this is user data'))
Obviously the earlier form is more convenient. Similarly, connect_weak() does the same thing, except it creates a WeakCallable from the callback and arguments.
It is possible to detect when a Signal changes by assigning a callback to the Signal object’s changed_cb property (or by passing it on the constructor):
>>> def signal_changed(signal, action):
... if action == kaa.Signal.CONNECTED:
... print 'New callback added, signal now has %d' % len(signal)
... else:
... print 'Callback removed, signal now has %d' % len(signal)
...
>>> sig = kaa.Signal(changed_cb=signal_changed)
>>> callback = sig.connect(lambda: None)
New callback added, signal now has 1
>>> sig.disconnect(callback)
Callback added, signal now has 0
One example of where this is used is with IOChannel’s read signal. If there are no callbacks connected to the read signal then we don’t want to consume any data from the channel. So, when a callback is connected, the IOChannel must register itself with the notifier and handle read events in order to consume data, passing it to all the callbacks connected to the read signal. When all callbacks have been disconnected, the IOChannel must unregister itself, so that no data is consumed when it has no listeners.
Signal objects also behave like containers, in that they can be iterated over (where each element is the Callable object), counted (via len()), and tested for membership (myfunc in signal).
A Signal knows how to be coerced into an InProgress object via kaa.inprogress(), and can therefore be yielded from a coroutine:
@kaa.coroutine()
def stop_process(self):
self.write('quit\n')
# Let's assume the 'terminated' signal gets emitted when the process
# exits, which is handled elsewhere.
yield kaa.inprogress(self.signals['terminated'])
# Once we get here, the 'terminated' signal was emitted.
# [...]
Here, the stop_process() coroutine is finished when the terminated signal is emitted. For more information on coroutines, see the section on asynchronous programming in Kaa.
A collection of many Signal objects is represented by a Signals object, which behaves like a dictionary. There are several additional methods with Signals object, such as any() and all().
Create a Signal object to which callbacks can be connected and later invoked in sequence when the Signal is emitted.
Parameters: | changed_cb (callable) – corresponds to the changed_cb property. |
---|
kaa.Signal
connect() | Connects the callback with the (optional) given arguments to be invoked when the signal is emitted. |
---|---|
connect_first() | Variant of connect() in which the given callback is inserted to the front of the callback list. |
connect_first_once() | Variant of connect_once() in which the given callback is inserted to the front of the callback list. |
connect_once() | Variant of connect() where the callback is automatically disconnected after one signal emission. |
connect_weak() | Weak variant of connect() where only weak references are held to the callback and arguments. |
connect_weak_first() | Weak variant of connect_first(). |
connect_weak_first_once() | Weak variant of connect_weak_first_once(). |
connect_weak_once() | Weak variant of connect_once(). |
count() | Returns the number of callbacks connected to the signal. |
disconnect() | Disconnects the given callback from the signal so that future emissions will not invoke that callback any longer. |
disconnect_all() | Disconnects all callbacks from the signal. |
emit() | Emits the signal, passing the given arguments callback connected to the signal. |
emit_deferred() | Queues the emission until after the next callback is connected. |
emit_when_handled() | Emits the signal if there are callbacks connected, or defers it until the first callback is connected. |
callbacks | read-only | Tuple containing the callbacks connected to this signal. |
---|---|---|
changed_cb | read/write | Callable to be invoked whenever a callback is connected to or disconnected from the Signal. |
Connects the callback with the (optional) given arguments to be invoked when the signal is emitted.
Parameters: |
|
---|---|
Returns: | a new Callable object encapsulating the supplied callable and arguments. |
Variant of connect() in which the given callback is inserted to the front of the callback list.
Variant of connect_once() in which the given callback is inserted to the front of the callback list.
Variant of connect() where the callback is automatically disconnected after one signal emission.
Weak variant of connect() where only weak references are held to the callback and arguments.
Returns: | a new WeakCallable object encapsulating the supplied callable and arguments. |
---|
Weak variant of connect_first().
Weak variant of connect_weak_first_once().
Weak variant of connect_once().
Returns the number of callbacks connected to the signal.
Equivalent to len(signal).
Disconnects the given callback from the signal so that future emissions will not invoke that callback any longer.
If neither args nor kwargs are specified, all instances of the given callback (regardless of what arguments they were originally connected with) will be disconnected.
Parameters: | callback – either the callback originally connected, or the Callable object returned by connect(). |
---|---|
Returns: | True if any callbacks were disconnected, and False if none were found. |
Disconnects all callbacks from the signal.
Emits the signal, passing the given arguments callback connected to the signal.
Returns: | False if any of the callbacks returned False, and True otherwise. |
---|
Queues the emission until after the next callback is connected.
This allows a signal to be ‘primed’ by its creator, and the handler that subsequently connects to it will be called with the given arguments.
Emits the signal if there are callbacks connected, or defers it until the first callback is connected.
Tuple containing the callbacks connected to this signal.
Because this value is a tuple, it cannot be manipulated directly. Use connect() and disconnect() instead.
A collection of one or more Signal objects, which behaves like a dictionary (with key order preserved).
__builtin__.dict
└─ kaa.Signals
add() | Creates a new Signals object by merging all signals defined in self and the signals specified in the arguments. |
---|---|
all() | Returns an InProgressAll object with all signals in self. |
any() | Returns an InProgressAny object with all signals in self. |
keys() | List of signal names (strings). |
subset() | Returns a new Signals object by taking a subset of the supplied signal names. |
values() | List of Signal objects. |
Creates a new Signals object by merging all signals defined in self and the signals specified in the arguments.
The same types of arguments accepted by the initializer are allowed here.
Returns an InProgressAll object with all signals in self.
Returns an InProgressAny object with all signals in self.
List of signal names (strings).
Returns a new Signals object by taking a subset of the supplied signal names.
The keys of the new Signals object are ordered as specified in the names parameter.
>>> yield signals.subset('pass', 'fail').any()
List of Signal objects.