在 Python 中实现 `__dir__`:是否需要 return 列表并且列表是否需要排序?

Implementing `__dir__` in Python: Does it need to return a list and does the list need to be sorted?

我有一个 class 实现了 __dir__ 方法。但是,我并不完全确定 dir API.

的一些细节

A: __dir__ returns 真的需要一个列表吗?我的实现是使用 set 来避免两次列出属性,我需要在返回之前将其转换为列表吗?从 documentation 我猜它必须是一个列表:

If the object has a method named dir(), this method will be called and must return the list of attributes.

但是,在某些时候不返回列表会中断功能吗?


B:结果需要排序吗?这里的文档有点模棱两可:

The resulting list is sorted alphabetically.

这是否意味着调用内置 dir 会自动对 __dir__ 返回的数据进行排序,或者是否意味着 dir 期望来自 __dir__ 的排序数据?

编辑:顺便说一句,我的问题包括 Python 2(2.6 和 2.7)和 3(3.3、3.4)。

Python3下you can return any sequence,包含一组,不用排序

Python2 下不存在相应的文档,所以我不确定您在那里需要做什么。

在Python2中,必须是list。否则,当您 运行 相应实例上的 dir() 函数时,您会得到一个 TypeError

class Dirry(object):
    def __dir__(self):
        return set('andy pandy mandy sandy'.split())

d = Dirry()
dir(d)

产量:

      5 d = Dirry()
----> 6 dir(d)

TypeError: __dir__() must return a list, not set

如果以列表形式返回,则不需要排序。 dir() 函数将为您排序:

class DirryList(object):
    def __dir__(self):
        return 'andy pandy mandy sandy'.split()

d = DirryList()
dir(d)

产量:

['andy', 'mandy', 'pandy', 'sandy']

即使 __dir__ 未按排序顺序给出。

根据Python2.7.3,答案是:

答:对,必须是列表:

>>> class F:
...     def __dir__(self):
...             return set(['1'])
... 
>>> dir(F())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __dir__() must return a list, not set

B:没有,dir会排序的。

>>> class G:
...     def __dir__(self):
...             return ['c','b','a']
... 
>>> dir(G())
['a', 'b', 'c']