kiwi Package

kiwi Package

Kiwi is a library designed to make developing graphical applications as easy as possible. It offers both a framework and a set of enhanced widgets, and is based on Python and GTK+. Kiwi borrows concepts from MVC, Java Swing and Microsoft MFC, but implements a set of unique classes that take advantage of the flexibility and simplicity of Python to make real-world application creation much easier.

Kiwi includes a Framework and a set of enhanced widgets

class kiwi.__init__.ValueUnset[source]

To differentiate from places where None is a valid default. Used mainly in the Kiwi Proxy

__version__ Module

accessor Module

The accessor module offers two important front-end functions: kgetattr and ksetattr. These functions allow retrieving attribute values from objects much in the same way as getattr/setattr allow, but with two important differences:

  • They follow a dot hierarchy to retrieve or modify any value reachable from the object.
  • They cache the method used to access a certain attribute and reuse it the next time the value is retrieved.
class kiwi.accessor.CacheControl(key)[source]

Bases: object

cacheable
disable()[source]
invalidate()[source]
key
exception kiwi.accessor.DefaultValue[source]

Bases: exceptions.Exception

This can be raised in kgetattr accessors to indicate that the default value should be used

kiwi.accessor.clear_attr_cache()[source]

Clears the kgetattr cache. It must be called repeatedly to avoid memory leaks in Python 2.0 and earlier.

kiwi.accessor.enable_attr_cache()[source]

Enables the use of the kgetattr cache when using Python versions that do not support weakrefs (1.5.x and earlier). Be warned, using the cache in these versions causes leaked references to accessor methods and models!

kiwi.accessor.get_default_getter(model, attr_name, cache)[source]

Obtains from model a callable through which attr_name can be retrieved. This callable is an accessor named get_foo, where foo is the value of attr_name, or getattr(model, foo) if the accessor does not exist. If the callable exists, it is returned; if getattr() is to be used a tuple in the format (model, attr_name) is returned.

kiwi.accessor.get_default_setter(model, attr_name, cache)[source]

Obtains from model a callable through which attr_name can be set. This callable is an accessor named set_foo, where foo is the value of attr_name, or setattr(model, foo, value) if the accessor does not exist. If the callable exists, it is returned; if setattr() is to be used a tuple in the format (model, attr_name) is returned.

kiwi.accessor.kgetattr(model, attr_name, default=<class kiwi.accessor._AttrUnset at 0x8ef171c>, flat=0, ref=<type 'weakref'>, TupleType=<type 'tuple'>, MethodType=<type 'instancemethod'>, split=<function split at 0x40859d4c>, kgetattr_guard=<function kgetattr_guard at 0x8f2348c>, getattr=<built-in function getattr>, dummycache=<kiwi.accessor.CacheControl object at 0x8f7bb6c>, LAMBDA_ACCESS=0, METHOD_ACCESS=1, TUPLE_ACCESS=2, NWR_METHOD_ACCESS=3, NWR_TUPLE_ACCESS=4, FAST_METHOD_ACCESS=5, FAST_TUPLE_ACCESS=6)[source]

Returns the value associated with the attribute in model named by attr_name. If default is provided and model does not have an attribute called attr_name, the default value is returned. If flat=1 is specified, no dot path parsing will be done.

kiwi.accessor.kgetattr_guard(wref)[source]
kiwi.accessor.ksetattr(model, attr_name, value, flat=0, ref=<type 'weakref'>, TupleType=<type 'tuple'>, MethodType=<type 'instancemethod'>, ksetattr_guard=<function ksetattr_guard at 0x8f2356c>, getattr=<built-in function getattr>, dummycache=<kiwi.accessor.CacheControl object at 0x8f7bb8c>, LAMBDA_ACCESS=0, METHOD_ACCESS=1, TUPLE_ACCESS=2, NWR_METHOD_ACCESS=3, NWR_TUPLE_ACCESS=4, FAST_METHOD_ACCESS=5, FAST_TUPLE_ACCESS=6)[source]

Set the value associated with the attribute in model named by attr_name. If flat=1 is specified, no dot path parsing will be done.

kiwi.accessor.ksetattr_guard(wref)[source]

argcheck Module

Argument checking decorator and support

class kiwi.argcheck.CustomType[source]

Bases: type

classmethod value_check(mcs, name, value)[source]
class kiwi.argcheck.argcheck(*types)[source]

Bases: object

Decorator to check type and value of arguments.

Usage:

>>> @argcheck(types...)
... def function(args..)

or

>>> class Class:
...     @argcheck(types..)
...     def method(self, args)

You can customize the checks by subclassing your type from CustomType, there are two builtin types: number which is a float/int combined check and a percent which verifis that the value is a percentage

classmethod disable()[source]

Disable argcheck globally

classmethod enable()[source]

Enable argcheck globally

extra_check(names, types, args, kwargs)[source]
class kiwi.argcheck.number[source]

Bases: kiwi.argcheck.CustomType

Custom type that verifies that the type is a number (eg float or int)

type = (<type 'int'>, <type 'float'>, <type 'long'>, <class 'decimal.Decimal'>)
class kiwi.argcheck.percent[source]

Bases: kiwi.argcheck.CustomType

Custom type that verifies that the value is a percentage

type = (<type 'int'>, <type 'float'>, <type 'long'>, <class 'decimal.Decimal'>)
classmethod value_check(mcs, name, value)[source]

component Module

exception kiwi.component.AlreadyImplementedError[source]

Bases: exceptions.Exception

Called when a utility already exists.

kiwi.component.get_utility(iface, default=<class kiwi.ValueUnset at 0x8f7d3ec>)[source]

Get the utility for the named interface. If the utility is not available (has not been set) a {NotImplementedError} is raised unless default is set.

Parameters:
  • iface – an interface
  • default – optional, if set return if a utility is not found
Returns:

the utility

kiwi.component.provide_utility(iface, utility, replace=False)[source]

Set the utility for the named interface. If the utility is already set, an {AlreadyImplementedError} is raised.

Parameters:
  • iface – interface to set the utility for.
  • utility – utility providing the interface.
kiwi.component.remove_utility(iface)[source]

Remove the utility provided for an interface If the utility is not available (has not been set) {NotImplementedError} is raised.

Parameters:iface – the interface
Returns:the removed utility

controllers Module

class kiwi.controllers.BaseController(view=None, keyactions=None)[source]

A generic controller that can be attached to any View

BaseController defines one public variable:

  • view: corresponds to a the associated View instance, which holds the UI implementation itself (widgets, layout, etc.)
get_parent()[source]

parent: the correspondent parent for the controller

get_view()[source]

view: the correspondent view for the controller

on_key_press(widget, event)[source]

The keypress handler, which dispatches keypresses to the functions mapped to in self.keyactions

set_keyactions(keyactions)[source]

Sets the keyactions mapping. See the constructor documentation for a description of it.

set_parent(parent)[source]

parent: the correspondent parent for the controller

set_view(view)[source]

view: the correspondent view for the controller

update_keyactions(new_actions)[source]

XXX

view = None

currency Module

Currency and datatype converter

class kiwi.currency.currency[source]

Bases: decimal.Decimal

A datatype representing currency, used together with the list and the framework

format(symbol=True, precision=None)[source]
kiwi.currency.format_price(value, symbol=True, precision=None)[source]

Formats a price according to the current locales monetary settings

Parameters:
  • value – number
  • symbol – whether to include the currency symbol

datatypes Module

Data type converters with locale and currency support.

Provides routines for converting data to and from strings. Simple example:

>>> from kiwi.datatypes import converter
>>> converter.from_string(int, '1,234')
'1234'
>>> converter.from_string(float, '1,234')
'1234.0'
>>> converter.to_string(currency, currency('10.5'))
'$10.50'
exception kiwi.datatypes.ValidationError[source]

Bases: exceptions.Exception

kiwi.datatypes.lformat(format, value)[source]

Like locale.format but with grouping enabled

kiwi.datatypes.format_price(value, symbol=True, precision=None)

Formats a price according to the current locales monetary settings

Parameters:
  • value – number
  • symbol – whether to include the currency symbol

decorators Module

Function and method decorators used in kiwi

class kiwi.decorators.deprecated(new, log=None)[source]

Bases: object

I am a decorator which prints a deprecation warning each time you call the decorated (and deprecated) function

class kiwi.decorators.signal_block(*signals)[source]

Bases: object

A decorator to be used on kiwi.ui.views.SlaveView methods. It takes a list of arguments which is the name of the widget and the signal name separated by a dot.

For instance:

>>> class MyView(SlaveView):
...     @signal_block('money.changed')
...     def update_money(self):
...         self.money.set_value(10)
...     def on_money__changed(self):
...         pass

When calling update_money() the value of the spinbutton called money will be updated, but on_money__changed will not be called.

desktopparser Module

class kiwi.desktopparser.DesktopParser(defaults=None)[source]

Bases: ConfigParser.ConfigParser

A DesktopParser for GNOME/KDE .desktop files. The API is similar to GKeyFile from glib.

Example:

>>> parser = DesktopParser()
>>> parser.read('/usr/share/applications/gnome-terminal.desktop')
>>> parser.get_locale('Desktop Entry', 'Comment', 'pt')
get_boolean_list(section, option)[source]

Get a boolean list.

Parameters:
  • section – section name
  • option – an option
get_integer_list(section, option)[source]

Get a list of integers as string.

Parameters:
  • section – section name
  • option – an option
get_locale(section, option, locale)[source]

Get locale.

Parameters:
  • section – section name
  • option – an option
  • locale – a locale
get_string_list(section, option)[source]

Get a list as string.

Parameters:
  • section – section name
  • option – an option
get_string_list_locale(section, option, locale)[source]

Get list locale as an string.

Parameters:
  • section – section name
  • option – an option
  • locale – a locale
optionxform(optionstr)[source]
set_boolean_list(section, option, values)[source]

Set an list wiht boolena values.

Parameters:
  • section – section name
  • option – an option
  • values – list of boolean values
set_integer_list(section, option, values)[source]

Set a list with integer values.

Parameters:
  • section – section name
  • option – an option
  • values – list of integer values
set_list_separator(separator)[source]

Sets the character which is used to separate values in lists. Typically ‘;’ or ‘,’ are used as separators. The default list separator is ‘;’.

Parameters:separator – the separator
set_locale(section, option, locale, value)[source]

Set locale.

Parameters:
  • section – section name
  • option – an option
  • locale – a locale
  • value – value to set
set_string_list(section, option, values)[source]

Set a list of string values.

Parameters:
  • section – section name
  • option – an option
  • values – list of string values
set_string_list_locale(section, option, locale, values)[source]

Set string list with locale values.

Parameters:
  • section – section name
  • option – an option
  • locale – a locale
  • values – list of string values

dist Module

Distutils extensions and utilities

class kiwi.dist.KiwiClean(dist)[source]

Bases: distutils.command.clean.clean

run()[source]
class kiwi.dist.KiwiInstallData(dist)[source]

Bases: distutils.command.install_data.install_data

run()[source]
class kiwi.dist.KiwiInstallLib(dist)[source]

Bases: distutils.command.install_lib.install_lib

generate_template()[source]
get_outputs()[source]
global_resources = {}
install()[source]
resources = {}
kiwi.dist.TemplateInstallLib

alias of KiwiInstallLib

kiwi.dist.compile_po_files(domain, dirname='locale')[source]

Compiles po files to mo files. Note. this function depends on gettext utilities being installed

Parameters:
  • domain – gettext domain
  • dirname – base directory
Returns:

a list of po files

kiwi.dist.get_site_packages_dir(*dirs)[source]

Gets the relative path of the site-packages directory

This is mainly useful for setup.py usage:

>>> setup(...
          data_files=[(get_site_packages_dir('foo'),
                       files..)])

where files is a list of files to be installed in a directory called foo created in your site-packages directory

Parameters:dirs – directory names to be appended
kiwi.dist.listfiles(*dirs)[source]

Lists all files in directories and optionally uses basic shell matching, example:

>>> listfiles('data', 'glade', '*.glade')
['data/glade/Foo.glade', 'data/glade/Bar.glade', ...]
Parameters:dirs – directory parts
kiwi.dist.listpackages(root, exclude=None)[source]

Recursivly list all packages in directory root Optionally exclude can be specified which is a string like foo/bar.

Parameters:
  • root – directory
  • exclude – optional packages to be skipped
kiwi.dist.setup(**kwargs)[source]

A drop in replacement for distutils.core.setup which integrates nicely with kiwi.environ :attribute resources: :attribute global_resources: :attribute templates: List of templates to install

enums Module

class kiwi.enums.Alignment[source]

Bases: kiwi.python.enum

LEFT = <Alignment value LEFT>
RIGHT = <Alignment value RIGHT>
names = {'RIGHT': <Alignment value RIGHT>, 'LEFT': <Alignment value LEFT>}
values = {0: <Alignment value LEFT>, 1: <Alignment value RIGHT>}
class kiwi.enums.ComboColumn[source]

Bases: kiwi.python.enum

DATA = <ComboColumn value DATA>
LABEL = <ComboColumn value LABEL>
names = {'DATA': <ComboColumn value DATA>, 'LABEL': <ComboColumn value LABEL>}
values = {0: <ComboColumn value LABEL>, 1: <ComboColumn value DATA>}
class kiwi.enums.ComboMode[source]

Bases: kiwi.python.enum

DATA = <ComboMode value DATA>
STRING = <ComboMode value STRING>
UNKNOWN = <ComboMode value UNKNOWN>
names = {'UNKNOWN': <ComboMode value UNKNOWN>, 'DATA': <ComboMode value DATA>, 'STRING': <ComboMode value STRING>}
values = {0: <ComboMode value UNKNOWN>, 1: <ComboMode value STRING>, 2: <ComboMode value DATA>}
class kiwi.enums.Direction[source]

Bases: kiwi.python.enum

LEFT = <Direction value LEFT>
RIGHT = <Direction value RIGHT>
names = {'RIGHT': <Direction value RIGHT>, 'LEFT': <Direction value LEFT>}
values = {1: <Direction value LEFT>, -1: <Direction value RIGHT>}
class kiwi.enums.ListType[source]

Bases: kiwi.python.enum

  • NORMAL: Add, Remove, Edit
  • REMOVEOLY: Remove
  • UNADDABLE: Remove, Edit
  • UNEDITABLE: Add, Remove
  • UNREMOVABLE: Add, Edit
  • READONLY: No buttons
NORMAL = <ListType value NORMAL>
READONLY = <ListType value READONLY>
REMOVEONLY = <ListType value REMOVEONLY>
UNADDABLE = <ListType value UNADDABLE>
UNEDITABLE = <ListType value UNEDITABLE>
UNREMOVABLE = <ListType value UNREMOVABLE>
names = {'UNREMOVABLE': <ListType value UNREMOVABLE>, 'UNADDABLE': <ListType value UNADDABLE>, 'NORMAL': <ListType value NORMAL>, 'READONLY': <ListType value READONLY>, 'UNEDITABLE': <ListType value UNEDITABLE>, 'REMOVEONLY': <ListType value REMOVEONLY>}
values = {0: <ListType value NORMAL>, 1: <ListType value READONLY>, 2: <ListType value REMOVEONLY>, 3: <ListType value UNREMOVABLE>, 4: <ListType value UNADDABLE>, 5: <ListType value UNEDITABLE>}
class kiwi.enums.SearchFilterPosition[source]

Bases: kiwi.python.enum

An enum used to indicate where a search filter should be added to a SearchContainer:

- TOP: top left corner
- BOTTOM: bottom
BOTTOM = <SearchFilterPosition value BOTTOM>
TOP = <SearchFilterPosition value TOP>
names = {'TOP': <SearchFilterPosition value TOP>, 'BOTTOM': <SearchFilterPosition value BOTTOM>}
values = {0: <SearchFilterPosition value TOP>, 1: <SearchFilterPosition value BOTTOM>}

environ Module

Environment helpers: path mangling and resource management

class kiwi.environ.Application(name, root='..', path='main', dirname=None)[source]

Bases: kiwi.environ.Library

Application extends a Library. It’s meant to be used by applications

Libraries are usually instantiated in __init__.py in the topmost package in your library, an example usage is kiwi itself which does:

>>> from kiwi.environ import Application
>>> app = Application('gnomovision')
>>> if app.uninstalled:
>>>     app.add_global_resource('glade', 'glade')
>>>     app.add_global_resource('pixmap', 'pixmaps')

If you want to do translations, you also need to do the following:

>>> app.enable_translation()
@see: Library for more information on how to integrate it with
the standard distutils configuration.
enable_translation(domain=None, localedir=None)[source]

Enables translation for a application See Library.enable_translation.

run()[source]
class kiwi.environ.Library(name, root='..', dirname=None)[source]

Bases: kiwi.environ.Environment

A Library is a local environment object, it’s a subclass of the Environment class. It’s used by libraries and applications (through the Application class)

It provides a way to manage local resources, which should only be seen in the current context.

Libraries are usually instantiated in __init__.py in the topmost package in your library, an example usage is kiwi itself which does:

>>> from kiwi.environ import Library
>>> lib = Library('kiwi')
>>> if lib.uninstalled:
>>>     lib.add_global_resource('glade', 'glade')
>>>     lib.add_global_resource('pixmap', 'pixmaps')

which is combined with the following class in setup.py:

>>> from kiwi.dist import InstallLib
>>> class InstallLib(TemplateInstallLib):
>>>    name = 'kiwi'
>>>    global_resources = dict(glade='$datadir/glade',
>>>                            pixmap='$datadir/pixmaps')
>>>
>>> setup(...,
>>>       data_files=[('share/kiwi/glade',
>>>                   listfiles('glade', '*.glade')),
>>>                   ('share/kiwi/pixmaps',
>>>                   listfiles('pixmaps', '*.png')),
>>>       cmdclass=dict(install_lib=InstallLib))

It may seems like a bit of work, but this is everything that’s needed for kiwi to figure out how to load resources when installed and when running in an uninstalled mode, eg directly from the source tree. To locate a pixmap called kiwi.png the following is enough:

>>> from kiwi.environ import environ
>>> environ.find_resource('pixmap', 'kiwi.png')
'/usr/share/kiwi/pixmaps/kiwi.png' # installed mode

Which will lookup the resource kiwi.png in the domain pixmap, which points to $datadir/pixmaps (eg $prefix/share/kiwi/pixmaps) when running in installed mode and from $builddir/pixmaps otherwise.

add_global_resource(resource, path)[source]

Convenience method to add a global resource. This is the same as calling kiwi.environ.environ.add_resource

add_global_resources(**kwargs)[source]
enable_translation(domain=None, localedir=None)[source]

Enables translation for a library

Parameters:
  • domain – optional, if not specified name sent to constructor will be used
  • localedir – directory to get locales from when running in uninstalled mode. If not specified a directory called ‘locale’ in the root will be used.
get_revision()[source]
set_application_domain(domain)[source]

Sets the default application domain :param domain: the domain

kiwi.environ.require_gazpacho()[source]
kiwi.environ.is_gazpacho_required()[source]

interfaces Module

Interface specifications and utilities

log Module

Extension to the logging module

This module defines a couple of extensions to the logging module included in the python standard distribution.

It creates an additional logging handler that print log records on the standard output. This handler is only showing records which has a level set to logging.WARNING or higher by default. The messages printed by this handler can be modified by using the environment variable called KIWI_LOG.

The syntax for the string which KIWI_LOG points to is the following:

domain ':' level [, domain ':', level]

domain can contain wildcards such as * and ? level is an integer 1-5 which defines the minimal level:

  • B{5}: DEBUG
  • B{4}: INFO
  • B{3}: WARNING
  • B{2}: ERROR
  • B{1}: CRITICAL

Examples:

KIWI_LOG="stoq*:5"

will print all the messages in a domain starting with stoq with DEBUG or higher:

KIWI_LOG="kiwi*:4,stoq.*:5"

will print all the messages with INFO or higher in all domains starting with kiwi, and all the messages in the stoq.* domains which are DEBUG or higher

Inspiration for the syntax is taken from the U{debugging facilities<http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer/html/gstreamer-GstInfo.html#id2857358>} of the U{GStreamer<http://www.gstreamer.net>} multimedia framework.

exception kiwi.log.LogError[source]

Bases: exceptions.Exception

class kiwi.log.Logger[source]

Bases: object

class kiwi.log.ReversedGlobalFilter[source]

Bases: logging.Filter

It’s like a reversed filter, the default behavior is to not show the message, you need to add custom filters for all the records you wish to see

add_filter(f, level=10)[source]
filter(record)[source]
kiwi.log.set_log_file(filename, mask=None)[source]

Set the filename used for logging.

Parameters:
  • filename
  • mask – optional
kiwi.log.set_log_level(name, level)[source]

Set the log level.

Parameters:
  • name – logging category
  • level – level
kiwi.log.update_logger()[source]

model Module

Holds the models part of the Kiwi Framework

class kiwi.model.Model[source]

The Model is a mixin to be used by domain classes when attached to Proxies. It also provides autonotification of changes to the attached proxies. Note that if using setters, a specific call to notify_proxies() may be necessary; see the doc for __setattr__.

block_proxy(proxy)[source]

Temporarily block a proxy from receiving any notification. See unblock_proxy()

disable_autonotify()[source]

disable automatic notification to proxies based on __setattr__. All changes to the model must be followed by a call to notify_proxies() to allow the proxies to notice the change.

ensure_init()[source]

Sets up the variables so the Model’s getattr hook and proxy notification work properly.

flush_proxies()[source]

Removes all proxies attached to Model

notify_proxies(attr)[source]

Notify proxies that an attribute value has changed.

register_proxy_for_attribute(attr, proxy)[source]

Attach a proxy to an attribute. The proxy will be notified of changes to that particular attribute (my means of Proxy.notify()).

unblock_proxy(proxy)[source]

Re-enable notifications to a proxy

unregister_proxy(proxy)[source]

Deattach a proxy completely from the model

unregister_proxy_for_attribute(attr, proxy)[source]

Detach a proxy from an attribute.

class kiwi.model.PickledModel[source]

Bases: kiwi.model.Model

PickledModel is a model that is able to save itself into a pickle using save(). This has all the limitations of a pickle: its instance variables must be picklable, or pickle.dump() will raise exceptions. You can prefix variables with an underscore to make them non-persistent (and you can restore them accordingly by overriding __setstate__, but don’t forget to call PickledModel.__setstate__)

save(filename=None)[source]

Saves the instance to a pickle filename. If no filename argument is provided, will try to use the internal _filename attribute that is set using set_filename() :param filename: optional filename to pass in

set_filename(filename)[source]

Sets the name of the file which will be used to pickle the model

classmethod unpickle(filename=None)[source]

Loads an instance from a pickle file; if it fails for some reason, create a new instance.

  • filename: the file from which the pickle should be loaded. If file is not provided, the name of the class suffixed by ”.pickle” is used (i.e. “FooClass.pickle” for the class FooClass).

If the pickle file is damaged, it will be saved with the extension ”.err”; if a file with that name also exists, it will use ”.err.1” and so on. This is to avoid the damaged file being clobbered by an instance calling save() unsuspectingly.

python Module

Generic python addons

class kiwi.python.ClassInittableMetaType(name, bases, namespace)[source]

Bases: type

class kiwi.python.ClassInittableObject[source]

Bases: object

I am an object which will call a classmethod called __class_init__ when I am created. Subclasses of me will also have __class_init__ called.

Note that __class_init__ is called when the class is created, eg when the file is imported at the first time. It’s called after the class is created, but before it is put in the namespace of the module where it is defined.

tasklet Module

Pseudo-thread (coroutines) framework

Introduction

This module adds infrastructure for managing tasklets. In this context, a X{tasklet} is defined as a routine that explicitly gives back control to the main program a certain points in the code, while waiting for certain events. Other terms that may be used to describe tasklets include I{coroutines}, or I{cooperative threads}.

The main advantages of tasklets are:

  • Eliminates the danger of unexpected race conditions or deadlocks that happen with preemptive (regular) threads;
  • Reduces the number of callbacks in your code, that sometimes are so many that you end up with I{spaghetti code}.

The fundamental block used to create tasklets is Python’s generators. Generators are objects that are defined as functions, and when called produce iterators that return values defined by the body of the function, specifically C{yield} statements.

The neat thing about generators are not the iterators themselves but the fact that a function’s state is completely frozen and restored between one call to the iterator’s C{next()} and the following one. This allows the function to return control to a program’s main loop while waiting for an event, such as IO on a socket, thus allowing other code to run in the mean time. When the specified event occurs, the function regains control and continues executing as if nothing had happened.

Structure of a tasklet

At the outset, a tasklet is simply a python U{generator function<http://www.python.org/peps/pep-0255.html>}, i.e. a function or method containing one or more C{yield} statements. Tasklets add a couple more requirements to regular generator functions:

  1. The values contained in C{yield} statements cannot be arbitrary (see below);
  2. After each C{yield} that indicates events, the function kiwi.tasklet.get_event must be called to retrieve the event that just occurred.

Syntax for yield in tasklets

Inside tasklet functions, C{yield} statements are used to suspend execution of the tasklet while waiting for certain events. Valid C{yield} values are:

  • A single Message object, with a correctly set I{dest} parameter. With this form, a message is sent to the indicated tasklet. When C{yield} returns, no event is generated, so the tasklet should B{not} call get_event.

  • One, or a sequence of:

    • WaitCondition, meaning to wait for that specific condition
    • Tasklet, with the same meaning as L{WaitForTasklet}C{(tasklet)}
    • generator, with the same meaning as :class:`WaitForTasklet`C{(Tasklet(gen))}

    In this case, the tasklet is suspended until either one of the indicated events occurs. The tasklet must call get_event in this case.

Launching a tasklet

To start a tasklet, the Tasklet constructor must be used::

from kiwi import tasklet

def my_task(x):
[...]

tasklet.Tasklet(my_task(x=0))

Alternatively, kiwi.tasklet.run can be used to the same effect::
from kiwi import tasklet tasklet.run(my_task(x=0))
Yet another approach is to use the @tasklet.task decorator::

from kiwi import tasklet

@tasklet.task def my_task(x):

[...] raise StopIteration(“return value”)

yield my_task(x=0) retval = tasklet.get_event().retval

Examples

This example demonstrates basic tasklet structure and timeout events::

import gobject from kiwi import tasklet

mainloop = gobject.MainLoop()

def simple_counter(numbers):

timeout = tasklet.WaitForTimeout(1000) for x in xrange(numbers):

print x yield timeout tasklet.get_event()

mainloop.quit()

tasklet.run(simple_counter(10)) mainloop.run()

This example extends the previous one and demonstrates message passing:

import gobject
from kiwi import tasklet

mainloop = gobject.MainLoop()

@tasklet.task
def printer():
    msgwait = tasklet.WaitForMessages(accept=("quit", "print"))
    while True:
        yield msgwait
        msg = tasklet.get_event()
        if msg.name == "quit":
            return
        assert msg.name == 'print'
        print ">>> ", msg.value

@tasklet.task
def simple_counter(numbers, task):
    timeout = tasklet.WaitForTimeout(1000)
    for x in xrange(numbers):
        yield tasklet.Message('print', dest=task, value=x)
        yield timeout
        tasklet.get_event()
    yield tasklet.Message('quit', dest=task)
    mainloop.quit()

task = printer()
simple_counter(10, task)
mainloop.run()
class kiwi.tasklet.Message(name, dest=None, value=None, sender=None)[source]

Bases: object

A message that can be received by or sent to a tasklet.

ACCEPT = 0
DEFER = 1
DISCARD = 2
class kiwi.tasklet.Tasklet(gen=None, start=True)[source]

Bases: object

An object that launches and manages a tasklet.

Variables:
  • state – current execution state of the tasklet, one of the STATE_* contants.
  • return_value – the value returned by the task function, or None.
  • STATE_RUNNING – the tasklet function is currently executing code
  • STATE_SUSPENDED – the tasklet function is currently waiting for an event
  • STATE_MSGSEND – the tasklet function is currently sending a message
  • STATE_ZOMBIE – the tasklet function has ended
STATE_MSGSEND = 2
STATE_RUNNING = 0
STATE_SUSPENDED = 1
STATE_ZOMBIE = 3
add_join_callback(callback, *extra_args)[source]

Add a callable to be invoked when the tasklet finishes. Return a connection handle that can be used in remove_join_callback()

The callback will be called like this::
callback(tasklet, retval, *extra_args)

where tasklet is the tasklet that finished, and retval its return value (or None).

When a join callback is invoked, it is automatically removed, so calling remove_join_callback afterwards produces a KeyError exception.

get_message_actions()[source]

Dictionary mapping message names to actions (‘accept’ or ‘discard’ or ‘defer’). Should normally not be accessed directly by the programmer.

message_actions

Dictionary mapping message names to actions (‘accept’ or ‘discard’ or ‘defer’). Should normally not be accessed directly by the programmer.

remove_join_callback(handle)[source]

Remove a join callback previously added with add_join_callback

run()[source]

Method that executes the task.

Should be overridden in a subclass if no generator is passed into the constructor.

@note: do NOT call this method directly; it is meant to be called by the tasklet framework.

send_message(message)[source]

Send a message to be received by the tasklet as an event.

@note: Don’t call this from another tasklet, only from the main loop! To send a message from another tasklet, yield a Message with a correctly set ‘dest’ parameter.

start()[source]

Starts the execution of the task, for use with tasklets created with start=False

wait_condition_fired(triggered_cond)[source]

Method that should be called when a wait condition fires

class kiwi.tasklet.WaitCondition[source]

Bases: object

Base class for all wait-able condition objects.

WaitConditions are used in a yield statement inside tasklets body for specifying what event(s) it should wait for in order to receive control once more.

arm(tasklet)[source]

Prepare the wait condition to receive events.

When a wait condition receives the event it is waiting for, it should call the method L{wait_condition_fired<Tasklet.wait_condition_fired>} of the tasklet with the wait condition as argument. The method returns True or False; if it returns True, it means the WaitCondition object must “rearm” itself (continue to monitor events), otherwise it should disarm.

Parameters:tasklet – the tasklet instance the wait condition is to be associated with.
@note: this method normally should not be called directly
by the programmer.
disarm()[source]

Stop the wait condition from receiving events.

@note: this method normally should not be called by the programmer.

class kiwi.tasklet.WaitForCall(return_value=None)[source]

Bases: kiwi.tasklet.WaitCondition

An object that waits until it is called.

This example demonstrates how a tasklet waits for a callback::

import gobject from kiwi import tasklet

mainloop = gobject.MainLoop()

def my_task():
callback = tasklet.WaitForCall() gobject.timeout_add(1000, callback) yield callback mainloop.quit()

tasklet.run(my_task()) mainloop.run()

Variables:return_value – value to return when called
arm(tasklet)[source]

Overrides WaitCondition.arm

disarm()[source]

Overrides WaitCondition.disarm

class kiwi.tasklet.WaitForIO(filedes, condition=1, priority=0)[source]

Bases: kiwi.tasklet.WaitCondition

An object that waits for IO conditions on sockets or file descriptors.

arm(tasklet)[source]

Overrides WaitCondition.arm

disarm()[source]

Overrides WaitCondition.disarm

class kiwi.tasklet.WaitForIdle(priority=200)[source]

Bases: kiwi.tasklet.WaitCondition

An object that waits for the main loop to become idle

arm(tasklet)[source]

See WaitCondition.arm

disarm()[source]

See WaitCondition.disarm

class kiwi.tasklet.WaitForMessages(accept=None, defer=None, discard=None)[source]

Bases: kiwi.tasklet.WaitCondition

An object that waits for messages to arrive

arm(tasklet)[source]

Overrides WaitCondition.arm

disarm()[source]

Overrides WaitCondition.disarm

class kiwi.tasklet.WaitForProcess(pid)[source]

Bases: kiwi.tasklet.WaitCondition

An object that waits for a process to end

arm(tasklet)[source]

See WaitCondition.arm

disarm()[source]

See WaitCondition.disarm

class kiwi.tasklet.WaitForSignal(obj, signal)[source]

Bases: kiwi.tasklet.WaitCondition

An object that waits for a signal emission

arm(tasklet)[source]

See WaitCondition.arm

disarm()[source]

See WaitCondition.disarm

class kiwi.tasklet.WaitForTasklet(tasklet)[source]

Bases: kiwi.tasklet.WaitCondition

An object that waits for a tasklet to complete

arm(tasklet)[source]

See WaitCondition.arm

disarm()[source]

See WaitCondition.disarm

class kiwi.tasklet.WaitForTimeout(timeout, priority=0)[source]

Bases: kiwi.tasklet.WaitCondition

An object that waits for a specified ammount of time (a timeout)

arm(tasklet)[source]

See WaitCondition.arm

disarm()[source]

See WaitCondition.disarm

restart()[source]

Restart the timeout. Makes time counting start again from zero.

kiwi.tasklet.get_event()[source]

Return the last event that caused the current tasklet to regain control.

@note: this function should be called exactly once after each yield that includes a wait condition.

kiwi.tasklet.run(gen)[source]

Start running a generator as a Tasklet.

Parameters:gen – generator object that implements the tasklet body.
Returns:a new Tasklet instance, already running.

@note: this is strictly equivalent to calling C{Tasklet(gen)}.

class kiwi.tasklet.task(func)[source]

Bases: object

A decorator that modifies a tasklet function to avoid the need to call C{tasklet.run(func())} or C{tasklet.Tasklet(func())}.

utils Module

GObject utilities and addons

kiwi.utils.gsignal(name, *args, **kwargs)[source]

Add a GObject signal to the current object. It current supports the following types:

  • str, int, float, long, object, enum
Parameters:
  • name (string) – name of the signal
  • args – types for signal parameters, if the first one is a string ‘override’, the signal will be overridden and must therefor exists in the parent GObject.
@note: flags: A combination of;
  • gobject.SIGNAL_RUN_FIRST
  • gobject.SIGNAL_RUN_LAST
  • gobject.SIGNAL_RUN_CLEANUP
  • gobject.SIGNAL_NO_RECURSE
  • gobject.SIGNAL_DETAILED
  • gobject.SIGNAL_ACTION
  • gobject.SIGNAL_NO_HOOKS

@note: retval: return value in signal callback

kiwi.utils.list_properties(gtype, parent=True)[source]

Return a list of all properties for GType gtype, excluding properties in parent classes

kiwi.utils.quote(msg)[source]

Similar to urllib.quote but for glibs GMarkup :param msg: string to quote :returns: quoted string

kiwi.utils.type_register(gtype)[source]

Register the type, but only if it’s not already registered :param gtype: the class to register