def _new_func_from_source(source, func):
    """
    Create new function defined in source but maintain context from func

    @param func: The function whose global + local context we will use
    @param source: Python source code containing def statement
    """
    src_str = ''.join(source)
    frames = inspect.getouterframes(inspect.currentframe())
    calling_frame = frames[2][0]

    context = {}
    # My initial instict was: exec src_str in func.func_globals.items(), calling_frame.f_locals
    # however this seems to break the function closure so caveat here is that we create a new
    # function with the locals merged into the globals.
    #
    # Possible consequences I can think of:
    #   - If a global exists that already has the same name as the local, it will be overwritten in
    #     in the context of this function. This shouldnt matter though as the global should have already
    #     been hidden by the new name?
    #
    # This functionality should be considered experimental as no idea what other consequences there
    # could be.
    #
    # relevant: http://stackoverflow.com/questions/2749655/why-are-closures-broken-within-exec
    globals = six.get_function_globals(func)
    locals = calling_frame.f_locals
    combined = globals.copy()
    combined.update(locals)
    Logger.debug(src_str % 'New src_str:\n %s')
    six.exec_(src_str, combined, context)
    new_func = context[func.__name__]
    return new_func
dataset/ETHPy150Open django-silk/silk/silk/profiling/dynamic.py/_new_func_from_source/swapped operands of `%`