What is the effect of "list=list" in Python modules?


I’ve seen following code in the python standard library /usr/lib/python2.7/multiprocessing/dummy/__init__.py:

list = list
dict = dict

What does this idiom mean? My best guess is: “let’s check if dict and list exist”.
Is it just legacy code from the ancient times without list and dict in the __builtins__?

And I have another mad guess: optimization of lookup speed moving list from global scope to module scope. Is it sane assumption regarding the idiom? I see, that the assumption is wrong if I apply it to multiprocessing.

Asked By: darkk



Exports. You then can do:

from multiprocessing.dummy import list

… which happens to be the regular list.

Without that line, there would be no list in the package multiprocessing.dummy.

This is sensible to have a uniform API across packages. Say all packages are supposed to offer a list class. Package a chooses to provide a custom implementation, package b however wants to use the list from __builtins__.

from powerfulinternals import PowerfulList as list
from simple.simpleinternals import Something as whoo

list = list
from simpleinternals import Something as whoo

  import powerful as api
  import simple as api

mylist = api.list()
woot = api.whoo()

There more reason to do such things. For example to make it explicit what you are using.

list = list

can also be seen as a statement “if you want to change the type of lists I’m using, change it here.”

In this particular case, it is the former. The list and dict are exposed as:

manager = multiprocessing.dummy.Manager()
l = manager.list()
d = manager.dict()

And the definition of Manager is:

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

i.e. Manager.list = list.

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.