【问题标题】:Python 3.3 PEP 418 example gives 'namespace' object is not iterable errorPython 3.3 PEP 418 示例给出“命名空间”对象不可迭代错误
【发布时间】:2012-07-10 17:08:56
【问题描述】:

Python 3.3 的测试版已经发布,非常棒。

新改版的time 模块具有get_clock_info 方法来获取有关平台的许多逻辑时钟的信息。 PEP 418 描述了新的时间模块。

当我尝试运行 PEP 418 clock_resolution.py 中引用的示例程序之一时,我在下面的第 54 行得到 TypeError: 'namespace' object is not iterable

46 clocks = ['clock', 'perf_counter', 'process_time']
47 if hasattr(time, 'monotonic'):
48     clocks.append('monotonic')
49 clocks.append('time')
50 for name in clocks:
51     func = getattr(time, name)
52     test_clock("%s()" % name, func)
53     info = time.get_clock_info(name)
54     if 'precision' in info:
55         print("- announced precision: %s" % format_duration(info['precision']))
56     print("- implementation: %s" % info['implementation'])
57     print("- resolution: %s" % format_duration(info['resolution']))

第 53 行的“信息”包含:

>>> info
namespace(adjustable=True, implementation='gettimeofday()', monotonic=False, resolution=1e-06) 

那么如何迭代一个命名空间对象呢?

【问题讨论】:

  • 您应该在 Python 错误跟踪器上打开一个关于此的问题:bugs.python.org
  • @NedDeily:哪个有错误? Python 3.3 还是 PEP 418 中的示例代码?在我看来,您应该能够迭代命名空间对象,但我没有看到这个记录..
  • 我认为要记录的问题是 PEP 中的示例程序由于功能实现的变化而不再工作。

标签: python namespaces python-3.x python-3.3


【解决方案1】:

你不想迭代对象;您只想测试是否存在属性。两种方式:

# "easier to get forgiveness than permission" approach
try:
    print(info.precision)
except AttributeError:
    pass

# "look before you leap" approach
if hasattr(info, "precision"):
    print(info.precision)

in 测试用于检查某些内容是否在字典、列表、元组或其他序列中。在一般情况下,in 将尝试迭代某些内容以查找值(dictset 是例外;Python 为提高效率对它们进行了特殊处理)。但是info 是一个不支持迭代的类的实例。

如果你愿意,你可以这样做:

# alternate "look before you leap"
if "precision" in info.__dict__:
    print(info.precision)

属性实际上存储在名为.__dict__dict 实例成员变量中。

编辑:@DSM 写了一条评论,显示了上述的替代方案。内置函数vars()会返回.__dict__成员变量,所以这相当于上面的:

# nicer alternate "look before you leap"
if "precision" in vars(info):
    print(info.precision)

【讨论】:

  • 啊,打败我。我还要提一下,使用 info = vars(time.get_clock_info(name)) 可以通过将 info 变成字典而不是命名空间来使当前代码正常工作。
  • @DSM,谢谢。我知道引用x.__dict__,但我不知道vars(x)。我会将其添加到答案中。
  • 澄清一下:Python 没有特殊情况下的 dict 和 set - 任何实现 __contains__ 的类在检查 in 时都会使用它。你也可以在自己的课堂上做到这一点。只有__contains__没有实现,Python才会诉诸迭代(也可以直接支持,或者回退到__getitem__)。
猜你喜欢
  • 2021-07-03
  • 2017-06-12
  • 2013-07-02
  • 2017-06-22
  • 2014-10-09
  • 2017-06-29
  • 1970-01-01
  • 2017-03-22
  • 1970-01-01
相关资源
最近更新 更多