brennivin.itertoolsext module

Like the itertools module but contains even more stuff! Also puts itertools namespace into this module so you can safely just use brennivin.itertoolsext instead of itertools.

Most useful are the sequence functions based off the LINQ extension methods in C#.

Contains the Bundle and FrozenDict utility types.

Contains functions for walking trees depth and breadth first. While a depth-first recursive function is easy to write and you should feel free to write your own instead of using treeyield_depthfirst(), a breadth-first is much more difficult and you should consider using treeyield_breadthfirst().

Also contains functions for getting/setting attrs and keys of compound objects and dicts, such as set_compound_attr() and get_compound_item().

Members

class brennivin.itertoolsext.Bundle(seq=None, **kwargs)

Allowed .notation access of dict keys.

Note that any keys that would otherwise hide a dict attribute will be ignored.

>>> Bundle({'spam': 'eggs'}).spam
'eggs'
class brennivin.itertoolsext.FrozenDict

An immutable version of a dict.

Raises:TypeError for any unsupported (mutable) operations.
brennivin.itertoolsext.all(seq, predicate=<type 'bool'>)

Returns True if all items in seq return True for predicate(item).

brennivin.itertoolsext.any(seq, predicate=<type 'bool'>)

Returns True if any item in seq returns True for predicate(item).

brennivin.itertoolsext.bucket(seq, keyprojection=lambda x: x, valueprojection=lambda x: x)

Buckets items in seq according to their keyprojection. Returns a dict where the keys are all unique values from keyprojections, and the values are lists containing the valueprojection of all items in that bucket.

>>> seq = ('a', 1), ('b', 2), ('a', 3)
>>> bucket(seq, lambda x: x[0], lambda x: x[1])
{'a': [1, 3], 'b': [2]}
brennivin.itertoolsext.count(seq, predicate=None)

Return the number of items in seq. If predicate is specified, return the number of items in seq that predicate is true for.

brennivin.itertoolsext.datespan(startdate, enddate, delta=datetime.timedelta(1))

Yield datetimes while walking from startdate to enddate. If startdate is later than endddate, will count backwards starting at startdate.

Note that startdate is inclusive (will always be the first yield), enddate is exclusive (it or later will never be yielded).

Parameters:
  • startdate – The first date to yield.
  • enddate – The date to stop yielding at.
  • delta – The size of the step.
>>> dt = _datetime.datetime
>>> len(list(datespan(dt(2010, 2, 20), dt(2010, 4, 21))))
60
>>> len(list(datespan(dt(2010, 2, 20), dt(2010, 4, 21),
...                   _datetime.timedelta(days=2))))
30
>>> len(list(datespan(dt(2010, 4, 21), dt(2010, 2, 20))))
60
brennivin.itertoolsext.del_compound_item(collection, *indices)

Delete element in collection that indices point to.

brennivin.itertoolsext.dict_add(alpha, beta, adder_function=None)

Adds any keys and valued from the second given dictionary to the first one using the given adder function. Any keys in the beta dict not present in alpha will be added there as they are in beta. If alpha and beta share keys, the adder function is applied to their values. If no adder function is supplied a simple numerical addition is used.

An adder function should take in two parameters, the value from alpha and the value from beta in those cases where they share keys, and should return the desired value after addition.

Example:

>>> summary = {'done': 38, 'errors': 0}
>>> current = {'done': 4, 'warnings': 3}
>>> dict_add(summary, current)
>>> print summary
{'errors': 0, 'done': 42, 'warnings': 3}
Parameters:
  • alpha (dict) – The dict to add stuff to
  • beta (dict) – The dict supplying stuff
brennivin.itertoolsext.first(seq, predicate=None)

Return the first item in seq. If predicate is specified, return the first item in seq that predicate returns True for. Raises StopIteration if no item is found.

brennivin.itertoolsext.first_or_default(seq, predicate=None, default=None)

Return the first item in seq. If predicate is specified, return the first item in seq that predicate returns True for. Returns default if sequence is empty or no item matches criteria.

brennivin.itertoolsext.flatmap(function, sequence)

Return a generator that yields the equivalent of: chain(map(function, sequence)).

Parameters:
  • function – Function that takes an item in sequence and returns a sequence.
  • sequence – Any iterable object.
brennivin.itertoolsext.get_compound_attr(obj, *namesandindices)

Like getattr, but takes a sequence of names and indices to get compound attr from obj.

get_compound_attr(x, ['y', 0, 'z'] is equivalent to x.y[0].z.

brennivin.itertoolsext.get_compound_item(collection, *indices)

Return the value of the element in collection that the indicies point to.

E.g.:

>>> get_compound_item(['a', {'b': 'value'}], 1, 'b')
'value'
brennivin.itertoolsext.groupby2(seq, keyfunc)

Groups a sequence by a key selector. Yields 2-item tuples of (key, list of items that share key).

Parameters:
  • seq – Sequence of items. Items should be collections or other complex items. Ie, it doesn’t make sense to group a list of integers, and such a sequence will give unpredictable results.
  • keyfunc – Callable that takes an item in seq and returns the key for grouping.

This is a more intuitive version of itertools.groupby (which is used internally) since it will sort the data for you, and has a more sensible return signature.

>>> seq = ('a', 1), ('a', 2), ('b', 3)
>>> dict(groupby2(seq, lambda pair: pair[0]))
{'a': [('a', 1), ('a', 2)], 'b': [('b', 3)]}
brennivin.itertoolsext.groups_of_n(seq, n)

Return list of groups. A group is seq split at size n.

>>> groups_of_n([1,2,3,4,5,6], 3)
[[1, 2, 3], [4, 5, 6]]
brennivin.itertoolsext.last(seq, predicate=None)

Return the last item in seq. If predicate is specified, return last item in seq that predicate returns True for.

Raises StopIteration:
 If seq is empty or no item matches predicate criteria.
brennivin.itertoolsext.last_or_default(seq, predicate=None, default=None)

Return the last item in seq. If predicate is specified, return the last item in seq that predicate returns true for. Return default if seq is empty or no item matches predicate criteria.

brennivin.itertoolsext.set_compound_attr(obj, value, *namesandindices)

Like setattr, but takes a sequence of names and indices to set compound attr on obj.

set_compound_attr(x, ['y', 0, 'z'], v) is equivalent to x.y[0].z = v.

brennivin.itertoolsext.set_compound_item(collection, value, *indices)

Mutates element of collection that the indicies point to, setting it to value.

E.g.:

>>> coll = ['a', {'b': None}]
>>> set_compound_item(coll, 'value', 1, 'b')
>>> print coll
['a', {'b': 'value'}]
brennivin.itertoolsext.shuffle(col, maxattempts=5)

Return a new shuffled collection and ensure it is shuffled. A regular random.shuffle could return the same as the input for small sequences.

Asserts after more than maxattempts at shuffle have been made.

brennivin.itertoolsext.single(seq)

Returns the only item in seq. If seq is empty or has more than one item, raise StopIteration.

brennivin.itertoolsext.skip(sequence, number)

Returns a generator that skips number of items in sequence. Similar to sequence[number:].

brennivin.itertoolsext.take(seq, number, predicate=None)

Returns a list with len <= number from items in seq.

brennivin.itertoolsext.treeyield_breadthfirst(node, getchildren, getchild=None, yieldnode=False)

Yields a tree in breadth first order.

Parameters:
  • node – The node to start at.
  • getchildren – A function to return the children of ‘node’.
  • getchild – If provided, getChildren should return an int (the index of the child in ‘node’). This function will be called with (node, index).
  • yieldnode – If True, yield ‘node’ argument.
brennivin.itertoolsext.treeyield_depthfirst(node, getchildren, getchild=None, yieldnode=False)

Yields a tree in depth first order.

Parameters:
  • node – The node to start at.
  • getchildren – A function to return the children of ‘node’.
  • getchild – If provided, getChildren should return an int (the index of the child in ‘node’). This function will be called with (node, index).
  • yieldnode – If True, yield ‘node’ argument.
brennivin.itertoolsext.unique(seq, transform=lambda x: x)

Returns an iterator of unique elements in seq. If transform is provided, will apply the method to items in seq as the keys for uniqueness.