0

I would like to get the full listing of enums from the header file using cffi. But I see a strange behaviour: by observing the object, I'm forcing the change in the underlying __dict__:

>>> from cffi import FFI
>>> ffi = FFI()
>>> ffi.cdef('typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy;')
>>> c = ffi.dlopen('c')

# the dictionary is empty
>>> print c.__dict__
{}

>>> dir(c)

# the dictionary is populated
>>> print c.__dict__
{'SEARCH': 2, 'RANDOM': 0, 'IMMEDIATE': 1}

I'm guessing that __dict__ is not populated until first getattr() on the class is called, but the real question is: what does dir() do that populates __dict__? Calling hasattr() seems to do the same thing.

4

1 回答 1

1

从技术上讲,您观察到的原因是dir()试图获取对象__members__上的一些特殊属性lib。cffi 中的代码在计算属性时会延迟添加属性。如果没有找到作为函数的名称,它将继续安装所有枚举声明并尝试返回其中一个,如果这是我们尝试读取的名称。这就是为什么尝试读取一个不存在的名称总是会在lib.__dict__. (此逻辑仅适用于由 返回的库ffi.dlopen(),不适用于 API 模式。)

理想情况下,您不应该依赖任何这些,但在这种情况下,您必须:这确实是一个错误。请注意,您可以简单地阅读dir(lib)两次:第二次,它将包含枚举值...(修复了 19cae8d1a5f6 中的错误:至少dir(lib)应该始终在 cffi 1.4 中工作——并且不再列出所有特殊的 Python 方法名称。 )

于 2015-12-08T09:47:38.023 回答