Can I combine two decorators into a single one in Python?

前端 未结 6 488
刺人心
刺人心 2020-11-29 02:08

Is there a way to combine two decorators into one new decorator in python?

I realize I can just apply multiple decorators to a function, but I was curious as to whet

6条回答
  •  有刺的猬
    2020-11-29 02:35

    If you don't want to repeat yourself too much in a test suite, you could do like this::

    def apply_patches(func):
        @functools.wraps(func)
        @mock.patch('foo.settings.USE_FAKE_CONNECTION', False)
        @mock.patch('foo.settings.DATABASE_URI', 'li://foo')
        @mock.patch('foo.connection.api.Session.post', autospec=True)
        def _(*args, **kwargs):
            return func(*args, **kwargs)
    
        return _
    

    now you can use that in your test suite instead of a crazy amount of decorators above each function::

    def ChuckNorrisCase(unittest.TestCase):
        @apply_patches
        def test_chuck_pwns_none(self):
            self.assertTrue(None)
    

提交回复
热议问题