【问题标题】:python use different decorator parameters dependent on a variable valuepython根据变量值使用不同的装饰器参数
【发布时间】:2021-10-25 06:32:31
【问题描述】:

下面是示例代码:

    @deviceCountAtLeast(1)
if NO_DOUBLE:
    @dtypes(torch.float)
else:
    @dtypes(torch.float, torch.double)
    def test_requires_grad_factory(self, devices, dtype):
        fns = [torch.ones_like, torch.testing.randn_like]
        x = torch.randn(2, 3, dtype=dtype, device=devices[0])

        for fn in fns:
            for requires_grad in [True, False]:
                output = fn(x, dtype=dtype, device=devices[0], requires_grad=requires_grad)
                self.assertEqual(requires_grad, output.requires_grad)
                self.assertIs(dtype, output.dtype)
                self.assertEqual(devices[0], str(x.device))

如您所见,我想根据NO_DOUBLE 值选择@dtypes() 装饰器的参数列表。

我目前的解决方法就像使用另一个函数来返回不同的装饰器:

def no_double(cond, dec1, dec2):
    return dec1 if cond else dec2

@no_double(NO_DOUBLE, dtypes(torch.float), dtypes(torch.float, torch.double))
def test_requires_grad_factory(self, devices, dtype):

【问题讨论】:

    标签: python python-decorators


    【解决方案1】:

    从 Python3.9 开始你可以使用任何表达式作为装饰器,参见PEP 614

    当使用的装饰器是三元表达式的结果时,类似下面的方法应该可以工作

    @(dtypes(torch.float) if NO_DOUBLE else dtypes(torch.float, torch.double))
    def test_requires_grad_factory(self, devices, dtype):
        ...
    

    【讨论】:

    • 太棒了,好奇我是不是只用python3.6.9,这样行吗?
    • 这可能无法使用 Python3.6,您必须自己手动装饰函数 - 在函数定义之后类似于 if NO_DOUBLE: test_requires_grad_factory = dtypes(torch.float)(test_requires_grad_factory); else: test_requires_grad_factory = dtypes(torch.float, torch.double)(test_requires_grad_factory)
    猜你喜欢
    • 2023-04-04
    • 2013-09-18
    • 2012-11-24
    • 1970-01-01
    • 2021-05-24
    • 2012-08-18
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多