【问题标题】:Using decorators of optional dependency使用可选依赖的装饰器
【发布时间】:2021-10-14 21:52:02
【问题描述】:

假设我有以下代码:

try:
    import bar
except ImportError:
    bar = None

@bar.SomeProvidedDecorator
def foo():
    pass

其中 bar 是一个可选依赖项。如果没有导入 bar,上面的代码将失败。 有没有推荐的方法来处理这个问题?

我想出了:

try:
    import bar
except ImportError:
    bar = None

def foo():
    pass

if bar is not None:
    foo = bar.SomeProvidedDecorator(foo)

但我想知道是否有更好的方法来处理这个问题(即有没有办法保留装饰器的语法)?

【问题讨论】:

    标签: python python-import python-decorators


    【解决方案1】:

    bar不可用的情况下提供身份装饰器:

    try:
        import bar
    except ImportError:
        class bar:
            SomeProvidedDecorator = lambda f: f
    

    【讨论】:

    • 如果模块bar中有很多装饰器,你可以在你的后备类中定义__getattr__,例如def __getattr(self, name)__: return lambda f: f
    猜你喜欢
    • 2013-11-22
    • 1970-01-01
    • 2021-01-05
    • 2013-04-08
    • 2018-08-07
    • 2023-04-06
    • 2018-02-01
    • 1970-01-01
    • 2016-02-08
    相关资源
    最近更新 更多