Re-assigning a name to itself

Question:

Notice these lines in multiprocessing package of standard libraries:

dict = dict
list = list

What’s the point of rebinding some names already available on __builtins__ into the module scope? What is it trying to achieve? I searched for an explanation in the git blame, but this commit was large and there was no relevant comment.

Asked By: wim

||

Answers:

This code occurs in multiprocessing.dummy, a “fake” version of multiprocessing that implements the functionality with threads. If you look down a few lines, you’ll see

def Manager():
    return sys.modules[__name__]

multiprocessing.dummy implements Manager as a function that just returns the multiprocessing.dummy module itself, so the multiprocessing.dummy module object has to provide the API of a multiprocessing Manager object. The lines

dict = dict
list = list

copy the bindings for the dict and list names from the builtins namespace into the module’s namespace, so you can do

m = multiprocessing.dummy.Manager()
d = m.dict()

as if you had a real multiprocessing.Manager().

Answered By: user2357112
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.