[英]In Python 3.x how do I create a simple proxy function for another function that is a pure pass through?
In Python 3.x, I want to create a proxy function _proxy for a specific known function proxiedFunc and guarantee that all arguments passed are "forwarded" exactly as if they were passed directly to the proxiedFunc .在 Python 3.x 中,我想为特定的已知函数proxiedFunc创建一个代理函数_proxy并保证传递的所有参数都完全“转发”,就像它们直接传递给proxiedFunc 一样。
# Pseudo-Python code
def _proxy(???generic_parameters???):
return proxiedFunc(???arguments???)
What I mean by "pure pass through" -> The implementation of the _proxy method should not be affected by (non-)compatible changes to the proxiedMethod , assuming the name of the function doesn't change (SOLID principles).我所说的“纯传递”是什么意思 -> _proxy方法的实现不应受到对proxiedMethod的(非)兼容更改的影响,假设函数名称没有更改(SOLID 原则)。 Obviously, callers of _proxy would need to be modified if proxiedMethod is changed incompatibly (ie I'm not intending for _proxy to be an adapter, but that would be a possibility).
显然,_proxy的呼叫者需要,如果proxiedMethod是不兼容的改变进行修改(即我不打算对_proxy是一个适配器,但是这将是一个可能性)。
The generic way of taking "anything" in a function definition is using *args, **kwargs
. 在函数定义中采用“任何”的通用方式是使用
*args, **kwargs
。
The same syntax is used for passing those args when calling another function. 调用另一个函数时,使用相同的语法来传递这些args。
def _proxy(*args, **kwargs):
return proxiedFunc(*args, **kwargs)
The single *
(eg *args
) captures the positional arguments, and the double (eg **kwargs
) captures the keyword arguments. 单
*
(例如*args
)捕获位置参数,而双(例如**kwargs
)捕获关键字参数。
args
and kwargs
are the names you give to those argument-containers. args
和kwargs
是您为这些参数容器指定的名称。 By convention, the name of the "any-positional-args" argument is args
or a
(its type is tuple
), and the name of the "any-keyword-args" argument is kwargs
or kw
(its type is dict
). 按照约定,“ any-positional-args”参数的名称为
args
或a
(其类型为tuple
),“ any-keyword-args”参数的名称为kwargs
或kw
(其类型为dict
)。
I, too, wanted to find a way to do that, so I wrote a function for that.我也想找到一种方法来做到这一点,所以我为此编写了一个函数。 I posted it to github: https://github.com/make-itrain/function-proxy
我把它贴到了github: https : //github.com/make-itrain/function-proxy
Basically, what it does is:基本上,它的作用是:
def a(p1, p2, p3=3, *args, p4=228, p18=11, **kwargs):
# any function, doesn't matter
pass
def b(p4, p2, *args):
# some overlapping arguments
# it too doesn't matter, what's inside here
print(p4, p2, args)
args, kwargs = proxy_function(b, a, {"args": ("replaced args",)}, 322, "some_random_arg", 1337,
"arguments", ('anything',), 1, abc=338, cbd="here too?")
b(*args, **kwargs)
Prints 228 some_random_arg ('replaced args',)
.打印
228 some_random_arg ('replaced args',)
。 Cool, isn't it?很酷,不是吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.