Python-dir()中的副本是一个错误吗? - python

在以下序列中,使用numpy dir(np)返回重复的条目。这是一个错误吗? dir()是否允许/预期返回重复项?

Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> len(dir(np))
620
>>> np.testing
<module 'numpy.testing' from 'C:\\Python\\Python38\\lib\\site-packages\\numpy\\testing\\__init__.py'>
>>> len(dir(np))
621
>>> [i for i in dir(np) if i == "testing"]
['testing', 'testing']
>>> np.__version__
'1.18.1'
>>>

参考方案

这看起来是一个(相对无害的)错误,该错误是由插入的优化numpy触发的,以避免急切地导入testing子包的开销,同时仍提供testingTester作为根numpy包的属性。

优化使用模块级别的__getattr__(仅在Python 3.7+上可用,因此在3.6和更早版本中不使用)仅在显式访问它们时将它们导入(此时testing成为numpy的真实属性,作为子模块)并将软件包作为其属性自动附加到其父对象上),但为了继续假装它们被急切地导入,它还定义了一个模块级__dir__来假装它们已经存在:

def __dir__():
    return list(globals().keys()) + ['Tester', 'testing']

此处的缺陷在于,如果导入了numpy.testing(通过__getattr__钩显式或隐式地),那么它已经出现在globals()中,因此将['Tester', 'testing']添加到list中会向'testing'的结果中添加dir的第二个副本。

他们可以通过重复数据删除(在转换为list之前,或者因为 dir is already documented to perform the conversion automatically而仅省略转换)来解决此问题,而不是例如在之后进行串联:

def __dir__():
    return globals().keys() | {'Tester', 'testing'}

但这不是一个严重的错误;因为dir产生的结果翻倍而导致代码中断,但一开始可能很脆弱且有故障。

此优化的完整说明在源注释中:

    # Importing Tester requires importing all of UnitTest which is not a
    # cheap import Since it is mainly used in test suits, we lazy import it
    # here to save on the order of 10 ms of import time for most users
    #
    # The previous way Tester was imported also had a side effect of adding
    # the full `numpy.testing` namespace
    #
    # module level getattr is only supported in 3.7 onwards
    # https://www.python.org/dev/peps/pep-0562/

在3.6及更早版本上,将跳过定义__getattr____dir__的代码路径,它所做的就是:

    # We don't actually use this ourselves anymore, but I'm not 100% sure that
    # no-one else in the world is using it (though I hope not)
    from .testing import Tester

这意味着testingTester是一开始的“真实”属性,并且不会出现该错误。

Python 3运算符>>打印到文件 - python

我有以下Python代码编写项目的依赖文件。它可以在Python 2.x上正常工作,但是在使用Python 3进行测试时会报告错误。depend = None if not nmake: depend = open(".depend", "a") dependmak = open(".depend.mak&#…

Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python:对于长时间运行的进程,通过还是休眠? - python

我正在编写一个队列处理应用程序,该应用程序使用线程等待和响应要发送到该应用程序的队列消息。对于应用程序的主要部分,只需要保持活动状态即可。对于像这样的代码示例:而True: 通过要么而True: time.sleep(1)哪一个对系统的影响最小?除了保持python应用运行外,什么都不做的首选方式是什么? 参考方案 我可以想象time.sleep()会减少系…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…