Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/8850921/what-is-the-effect-of-list-list-in-python-modules

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...