[英]__import__ missing from Python __builtins__ (when in Django Shell)
I hope this isn't too dumb of a question :-( but why isn't __import__
included in inspect.getmembers(__builtins__)
? 我希望这不是一个愚蠢的问题:-(但是为什么
__import__
不包含在inspect.getmembers(__builtins__)
?
Here's what I get when I try to print the builtins: 这是我尝试打印内置文件时得到的信息:
>>> sorted([name for (name,obj) in inspect.getmembers(__builtins__)])
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
Update: 更新:
Actually I was in the Django 1.6 shell when I ran that. 实际上,运行该程序时我在Django 1.6 Shell中。 (Python 2.7).
(Python 2.7)。
Running it in Python 2.7 alone does include __import__
. 仅在Python 2.7中运行它确实包含
__import__
。 What could be going on? 可能会发生什么?
From the docs: 从文档:
27.3.
27.3。
__builtin__
— Built-in objects__builtin__
—内置对象CPython implementation detail: Most modules have the name
__builtins__
(note the's'
) made available as part of their globals.CPython实现细节:大多数模块的名称
__builtins__
(请注意's'
)作为其全局变量的一部分可用。 The value of__builtins__
is normally either this module or the value of this modules's [sic]__dict__
attribute.__builtins__
的值通常是此模块或此模块的[sic]__dict__
属性的值。 Since this is an implementation detail, it may not be used by alternate implementations of Python.由于这是一个实现细节,因此Python的其他实现可能不会使用它。
In your case, it looks like the __builtins__
you are looking at is the dictionary not the module ( __builtin__.__dict__
rather than __builtin__
). 在您的情况下,看起来您正在查看的
__builtins__
是字典而不是模块( __builtin__.__dict__
而不是__builtin__
)。 So inspect.getmembers
is returning the attributes of the dict class rather than the keys. 因此,
inspect.getmembers
返回的是dict类的属性,而不是键。 Instead you might want something like the following: 相反,您可能需要类似以下内容:
if isinstance(__builtins__, dict):
names = sorted(__builtins__)
else:
names = sorted(name for name, obj in inspect.getmembers(__builtins__))
Or alternatively: 或者:
import __builtin__
names = sorted(name for name, obj in inspect.getmembers(__builtin__))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.