Ignore all real exceptions (descendants of Exception). Handy for cleaning data such as user input:

brand_id = silent(int)(request.GET['brand_id'])
ids = keep(silent(int), request.GET.getlist('id'))

And in data import/transform:

choices = {1: 'a', 2: ' b', 4: ' c '}
get_caption = compose(silent(string.strip), choices)
map(get_caption, [0, 1, 2, 3, 4])
# -> [None, 'a', 'b', None, 'c']


avoid silencing non-primitive functions, use ignore() instead and even then be careful not to swallow exceptions unintentionally.

@ignore(errors, default=None)

Same as silent(), but able to specify errors to catch and default to return in case of error caught. errors can either be exception class or tuple of them.

raiser(exception_or_class, *args, **kwargs)

Constructs function that raises given exception with given arguments on any invocation.

@retry(tries, errors=Exception)

Transforms generator or other iterator returning function into list returning one.

Handy to prevent quirky iterator-returning properties:

def path_up(self):
    node = self
    while node:
        yield node
        node = node.parent

Also makes list constructing functions beautifully yielding.


Wraps common python idiom “collect then join” into a decorator. Transforms generator or alike into function, returning string of joined results. Automatically converts all elements to separator type for convenience.

Goes well with generators with some ad-hoc logic within:

@joining(', ')
def car_desc(self):
    yield self.year_made
    if self.engine_volume: yield '%s cc' % self.engine_volume
    if self.transmission:  yield self.get_transmission_display()
    if self.gear:          yield self.get_gear_display()
    # ...

Use unicode separator to get unicode result:

@joining(u', ')
def car_desc(self):
    yield self.year_made
    # ...

See also str_join().

Previous topic


Next topic

String utils

This Page