Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Where is the __builtin__ module in Python3? Why was it renamed?

I was curious about the __builtin__ module and how it's used, but I can't find it in Python3! Why was it moved?

Python 2.7

>>> import __builtin__
>>>

Python 3.2

>>> import __builtin__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named __builtin__
>>>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The __builtin__ module was renamed to builtins in Python3.

This change solves 2 sources of confusion for the average Python developer.

  • Is it '__builtins__' or '__builtin__' that is in the global namespace? Darn s!
  • Is __builtin__ a special method name or a module? I can't tell.

This confusion mainly arises because of the violation of pep8 convention. Also, the lack of pluralization on the module hinders communication as well. Both of these are greatly illustrated by the lengths Guido must go to explain the following from http://mail.python.org/pipermail/python-ideas/2009-March/003821.html:

[CPython] looks at the globals, which contain a special magic entry __builtins__ (with an 's') which is the dict where built-in functions are looked up. When this dict is the same object as the default built-in dict (which is __builtin__.__dict__ where __builtin__ -- without 's' -- is the module defining the built-in functions) it gives you supervisor privileges;…

For example,

Python2.7

>>> import __builtin__
>>> vars(globals()['__builtins__']) is vars(__builtin__)
True
>>> 

Python3.2

>>> import builtins
>>> vars(globals()['__builtins__']) is vars(builtins)
True
>>>

Related resources:

Other name changes - http://docs.pythonsprints.com/python3_porting/py-porting.html#name-changes

For a succinct explanation of how __builtins__ is used in name resolution - __builtin__ module in Python


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...