Search code examples
pythonsetuptoolspkg-resources

Why would you execute code in a local scope just to update the global scope?


In pkg_resources module you have this weird function:

@_call_aside
def _initialize_master_working_set():
    # A bunch of ugly code, and then finally:
    globals().update(locals())

The _call_aside is a decorator defined like this, it calls the function once at definition time (why to do this with a decorator rather than simply calling the function explicitly, I can't tell):

def _call_aside(f, *args, **kwargs):
    f(*args, **kwargs)
    return f

The function _initialize_master_working_set is not called anywhere else and the underscore on the name suggests it's not intended for public re-use. The docstring further warns against calling that:

This function ... is intended to be invoked once at the initialization of this module. Invocation by other packages is unsupported

I don't get it. Isn't this just an obfuscated way of executing "A bunch of ugly code" at the module scope? How is this pattern any different than executing code directly at the global scope?


Solution

  • Git blame turns up a commit message with a link to an issue that motivated this function's introduction. Someone wanted a way to rerun this initialization, so they extracted it into a function that can be called repeatedly.

    This function was not intended to behave any differently from the old version, where its code was at module level. While there are cases where a function with globals().update(locals()) at the end would behave differently from running the code in the global scope directly (for example, if something else rebinds the same global names in the middle of the function, the function will stomp over those changes at the end), that was not the motivation for introducing this function. They just wanted to be able to rerun it on demand.