gpt4 book ai didi

python - 如何全局覆盖/重载python函数(os.path.walk)?

转载 作者:太空宇宙 更新时间:2023-11-04 01:19:10 25 4
gpt4 key购买 nike

scandir.walk() is a better alternative to os.walk() .

我想用 scandir.walk() 替换 os.walk() 的所有实例。然而,我也想确保所有 future 的开发者都将使用 scandir.walk()。

这将很难执行,所以我想知道是否可以覆盖默认的 os.walk() 功能。

最佳答案

python 3.5+

os.walk现在是 scandir.walk。引用 PEP 471 :

As part of this proposal, os.walk() will also be modified to use scandir() rather than listdir() and os.path.isdir().

now implemented using os.scandir(), which speeds it up by 3-5 times on POSIX systems and by 7-20 times on Windows systems. [...] The implementation of this proposal was written by Ben Hoyt (initial > version) and Tim Golden (who helped a lot with the C extension > module). It lives on GitHub at benhoyt/scandir.

较旧的 Python

只需修补它:

>>> import scandir
>>> import os
>>> os.walk
<function walk at 0x7f3c02afc8c0>
>>> scandir.walk
<function walk at 0x7f3c00fe28c0>
>>> os.walk = scandir.walk
>>> os.walk is scandir.walk
True
>>> os.walk('/')
<generator object walk at 0x7f3c02b53500>

因为

The API for scandir.walk() is exactly the same as os.walk()

(来自GitHub page)

关于python - 如何全局覆盖/重载python函数(os.path.walk)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22386516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com