重新定义函数的 Pythonic 方式? (Flake8 F811错误)

Pythonic way to redefine function? (Flake8 F811 error)

我正在尝试在 python 中编写一个下载器包装器模块,它可能会使用 pycurl、selenium 或 good-ol' 请求来下载 URL,按照 [=12] =]

# 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