def build_plugin_tree(plugins):
 cache = dict(((p.pk, p) for p in plugins))
 by_parent_id = attrgetter('parent_id')
 nonroots = sorted(filter(by_parent_id, cache.values()), key=attrgetter('parent_id', 'position'))
 families = ((cache[parent_id], tuple(children)) for (parent_id, children) in groupby(nonroots, by_parent_id))
 for (parent, children) in families:
  parent.child_plugin_instances = children
 return sorted(filterfalse(by_parent_id, cache.values()), key=attrgetter('position'))

def build_plugin_tree ( plugins ) : cache = dict ( ( ( p . pk , p ) for p in plugins ) ) by_parent_id = attrgetter ( 'parent_id' ) nonroots = sorted ( filter ( by_parent_id , cache . values ( ) ) , key = attrgetter ( 'parent_id' , 'position' ) ) families = ( ( cache [ parent_id ] , tuple ( children ) ) for ( parent_id , children ) in groupby ( nonroots , by_parent_id ) ) for ( parent , children ) in families : parent . child_plugin_instances = children return sorted ( filterfalse ( by_parent_id , cache . values ( ) ) , key = attrgetter ( 'position' ) )
accepts an iterable of plugins and assigns tuples .