Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 303
darkk Avatar asked Jan 13 '12 12:01

darkk


1 Answers

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__.

powerful/__init__.py:
from powerfulinternals import PowerfulList as list
from simple.simpleinternals import Something as whoo

simple/__init__.py:
list = list
from simpleinternals import Something as whoo

application.py:
try:
  import powerful as api
else:
  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.

like image 100
Has QUIT--Anony-Mousse Avatar answered Nov 11 '22 10:11

Has QUIT--Anony-Mousse