python - Pythonic 重新定义函数的方法?(Flake8 F811 错误)
问题描述
我正在尝试在 python 中编写一个下载器包装模块,该模块可能使用 pycurl、selenium 或 good-ol' 请求来下载 URL,如下所示
# import pycurl inside a try-except block, logging errors
# also import selenium stuff inside a try-except block logging errors
# then
def pycurl_downloader(*args, **kwargs):
raise NotImplementedError
if 'pycurl' in sys.modules:
def pycurl_downloader(url, char_encoding=None):
# actual implementation, now we are certain pycurl is there
# similar for selenium
那么当一个站点不使用愚蠢的 DOM 修改 JavaScript 时,我可以只使用 pycurl(或者如果找不到,则优雅地回退到请求),否则使用各种 selenium 驱动程序(如果驱动程序失败,再次使用优雅的回退)。
但是 flake8 在上面的代码中抱怨 F811 重新定义错误(稍后也重新定义了 pycurl_downloader 和 selenium_downloader)。
我可以尝试使用一些 _not_implemented_function 虚拟对象并将名称 pycurl_downloader 分配给它,然后编写 _real_pycurl_downloader 函数并重新分配:
pycurl_downloader = _not_implemented_func
if 'pycurl' in sys.modules:
def _real_pycurl_downloader(...):
# blah
pycurl_downloader = _real_pycurl_downloader
但这感觉不对。有没有人有更好的主意?
解决方案
使用if
-else
只定义一次函数应该关闭 flake8:
if 'pycurl' in sys.modules:
def pycurl_downloader(url, char_encoding=None):
# actual implementation, now we are certain pycurl is there
...
else:
def pycurl_downloader(*args, **kwargs):
raise NotImplementedError
推荐阅读
- java - 安卓。谷歌地图API实现标记点击
- api - 富文本的最佳实践。休息。后端
- flutter - 使用 LineMetrics 获取文本高度的颤振问题
- conv-neural-network - 图像的位深度会影响卷积神经网络吗?
- qt - QtQuick QML如何在悬停时突出显示ListView中的项目?
- flask - EventSource 每 3 秒不断断开连接并重试连接
- javascript - 流添加永远不会被 agora.io 触发
- c# - 如何在 asp.net mvc 中获取子模式集合时包含基本模型属性
- regex - 匹配任何不是 az 或 AZ 或 & 后跟数字的内容
- linux - 替代“树”命令或减少树输出文件大小的方法?