def replacingGlobals(function, **newGlobals):
    """
    Create a copy of the given function with the given globals substituted.

    The globals must already exist in the function's existing global scope.

    @param function: any function object.
    @type function: L{types.FunctionType}

    @param newGlobals: each keyword argument should be a global to set in the
        new function's returned scope.
    @type newGlobals: L{dict}

    @return: a new function, like C{function}, but with new global scope.
    """
    try:
        codeObject = function.func_code
        funcGlobals = function.func_globals
    except AttributeError:
        codeObject = function.__code__
        funcGlobals = function.__globals__
    for key in newGlobals:
        if key not in funcGlobals:
            raise TypeError(
                "Name bound by replacingGlobals but not present in module: {}"
                .format(key)
            )
    mergedGlobals = {}
    mergedGlobals.update(funcGlobals)
    mergedGlobals.update(newGlobals)
    newFunction = FunctionType(codeObject, mergedGlobals)
    mergedGlobals[function.__name__] = newFunction
    return newFunction

    Create a copy of the given function with the given globals substituted.

    The globals must already exist in the function's existing global scope.

    @param function: any function object.
    @type function: L{types.FunctionType}

    @param newGlobals: each keyword argument should be a global to set in the
        new function's returned scope.
    @type newGlobals: L{dict}

    @return: a new function, like C{function}, but with new global scope.
    
stackoverflow/venv/lib/python3.6/site-packages/twisted/internet/test/test_endpoints.py