def tree_item_iterator(items, ancestors=False):
 structure = {}
 opts = None
 first_item_level = 0
 for (previous, current, next_) in previous_current_next(items):
  if (opts is None):
   opts = current._mptt_meta
  current_level = getattr(current, opts.level_attr)
  if previous:
   structure[u'new_level'] = (getattr(previous, opts.level_attr) < current_level)
   if ancestors:
    if structure[u'closed_levels']:
     structure[u'ancestors'] = structure[u'ancestors'][:(- len(structure[u'closed_levels']))]
    if structure[u'new_level']:
     structure[u'ancestors'].append(text_type(previous))
  else:
   structure[u'new_level'] = True
   if ancestors:
    structure[u'ancestors'] = []
   first_item_level = current_level
  if next_:
   structure[u'closed_levels'] = list(range(current_level, getattr(next_, opts.level_attr), (-1)))
  else:
   structure[u'closed_levels'] = list(range(current_level, (first_item_level - 1), (-1)))
  (yield (current, copy.deepcopy(structure)))

def tree_item_iterator ( items , ancestors = False ) : structure = { } opts = None first_item_level = 0 for ( previous , current , next_ ) in previous_current_next ( items ) : if ( opts is None ) : opts = current . _mptt_meta current_level = getattr ( current , opts . level_attr ) if previous : structure [ u'new_level' ] = ( getattr ( previous , opts . level_attr ) < current_level ) if ancestors : if structure [ u'closed_levels' ] : structure [ u'ancestors' ] = structure [ u'ancestors' ] [ : ( - len ( structure [ u'closed_levels' ] ) ) ] if structure [ u'new_level' ] : structure [ u'ancestors' ] . append ( text_type ( previous ) ) else : structure [ u'new_level' ] = True if ancestors : structure [ u'ancestors' ] = [ ] first_item_level = current_level if next_ : structure [ u'closed_levels' ] = list ( range ( current_level , getattr ( next_ , opts . level_attr ) , ( - 1 ) ) ) else : structure [ u'closed_levels' ] = list ( range ( current_level , ( first_item_level - 1 ) , ( - 1 ) ) ) ( yield ( current , copy . deepcopy ( structure ) ) )
given a list of tree items .