def fast_iter(context, func, d=2, **kwargs):
    """
    Applies ``func`` to all xml elements of depth 1 of the xml parser ``context``. `
    ``**kwargs`` are passed to ``func``.

    Modified version of a modified version of Liza Daly's fast_iter
    Inspired by
    https://stackoverflow.com/questions/4695826/efficient-way-to-iterate-through-xml-elements

    Parameters
    ----------
    context: XMLparser
        A parser obtained from etree.iterparse
    func: function
        How to process the elements
    d: int, optional
        Depth to process elements.
    """
    depth = 0
    for event, elem in context:
        if event == 'start':
            depth += 1
        if event == 'end':
            depth -= 1
            if depth < d:
                func(elem, **kwargs)
                elem.clear()
                for ancestor in elem.xpath('ancestor-or-self::*'):
                    while ancestor.getprevious() is not None:
                        del ancestor.getparent()[0]
    del context
