【问题标题】:Idiomatic way to inject parameters with python decorators使用 python 装饰器注入参数的惯用方法
【发布时间】:2016-03-26 10:04:29
【问题描述】:

所以,这是一个两部分的问题 -

  1. 在使用装饰器时,python 中是否有一种惯用的方式将参数注入函数签名?

例如:

def _mydecorator(func):
  def wrapped(someval, *args, **kwargs):
    do_something(someval)
    return func(*args, **kwargs)
  return wrapped

@_mydecorator
def foo(thisval, thatval=None):
  do_stuff()

原因是在使用 SaltStack 的运行器模块时,您可以在模块中定义函数,并且可以通过“salt-run”命令调用这些函数。如果上面的例子是一个 Salt runner 模块调用'bar',那么我可以运行:

salt-run bar.foo aval bval

salt-run 导入模块并使用您在命令行中提供的参数调用函数。模块中以 _ 开头或在类中的任何函数都将被忽略,并且无法通过 salt-run 运行。

所以,我想定义一个类似超时装饰器的东西来控制函数可以运行多长时间。

我意识到我可以这样做:

@timeout(30)
def foo():
  ...

但我想让这个值可配置,这样我就可以运行类似的东西:

salt-run bar.foo 30 aval bval
salt-run bar.foo 60 aval bval

上面的装饰器可以工作,但感觉就像一个 hack,因为它正在改变函数的签名并且用户不知道,除非他们查看装饰器。

我有另一种情况,我想在 Salt runner 中的函数执行之前制作一个装饰器来处理“预检查”。但是,预检查需要来自它正在装饰的功能的一条信息。这是一个例子:

def _precheck(func):
  def wrapper(*args, **kwargs):
    ok = False
    if len(args) > 0:
      ok = run_prechecks(args[0])
    else:
      ok = run_prechecks(kwargs['record_id'])
    if ok:
      func(*args, **kwargs)
  return wrapper

@_precheck
def foo(record_id, this_val):
  do_stuff()

这似乎也很老套,因为它要求被修饰的函数,a) 有一个名为“record_id”的参数,并且 b) 它是第一个参数。

现在,因为我正在编写所有这些函数,所以这并不是什么大问题,但似乎有更好的方法可以做到这一点(比如不使用装饰器来尝试解决这个问题)

【问题讨论】:

  • 我不知道您使用的是哪个 Python 版本(我猜是 Salt doc 示例中的 2.x),但如果您可以使用 Python 3,您的装饰器可以注入一个关键字-唯一具有默认值的参数,您可以在调用它时选择覆盖它。

标签: python decorator


【解决方案1】:

动态定义装饰器参数的方法不是使用语法糖 (@)。像这样: func = dec(dec_arguments)(func_name)(func_arguments)

import json
import sys

foo = lambda record_id, thatval=None: do_stuff(record_id, thatval)
def do_stuff(*args, **kwargs):
    # python3
    print(*args, json.dumps(kwargs))

def _mydecorator(timeout):
    print('Timeout: %s' % timeout)
    def decorator(func):
        def wrapped(*args, **kwargs):
            return func(*args, **kwargs)
        return wrapped
    return decorator


if __name__ == '__main__':
    _dec_default = 30
    l_argv = len(sys.argv)
    if  l_argv == 1:
        # no args sent
        sys.exit('Arguments missing')
    elif l_argv == 2:
        # assuming record_id is a required argument
        _dec_arg = _dec_default
        _args = 1
    else:
        # three or more args: filename 1 2 [...]
        # consider using optional keyword argument `timeout`
        # otherwise in combination with another optional argument it's a recipe for disaster
        # if only two arguments will be given - with current logic it will be tested for `timeoutedness`
        try:
            _dec_arg = int(sys.argv[1])
            _args = 2
        except (ValueError, IndexError):
            _dec_arg = _dec_default
            _args = 1
    foo = _mydecorator(_dec_arg)(foo)(*sys.argv[_args:])

【讨论】:

    【解决方案2】:

    据我所知,在 python 3.7 中没有惯用的方法来做到这一点。事实上,@functools.wraps 仅在您不修改签名时才有效(请参阅what does functools.wraps do ?)

    但是有一种与@functools.wraps 相同的方法(公开完整签名,保留__dict__ 和文档字符串):@makefun.wraps。有了这个@wraps 的直接替换,您可以edit the exposed signature。

    from makefun import wraps
    
    def _mydecorator(func):
      @wraps(func, prepend_args="someval")
      def wrapped(someval, *args, **kwargs):
        print("wrapper executes with %r" % someval)
        return func(*args, **kwargs)
      return wrapped
    
    @_mydecorator
    def foo(thisval, thatval=None):
      """A foo function"""
      print("foo executes with thisval=%r thatval=%r" % (thisval, thatval))
    
    # let's check the signature
    help(foo)
    
    # let's test it
    foo(5, 1)
    

    产量:

    Help on function foo in module __main__:
    
    foo(someval, thisval, thatval=None)
        A foo function
    
    wrapper executes with 5
    foo executes with thisval=1 thatval=None
    

    您可以看到公开的签名包含前置参数。

    相同的机制适用于附加和删除参数,以及更深入地编辑签名。详情见makefun documentation(我是作者;))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      • 2011-09-01
      • 1970-01-01
      • 2011-08-02
      • 2019-11-16
      • 2011-03-04
      • 1970-01-01
      相关资源
      最近更新 更多