How can I copy the signature of a method from one class, and create a "proxy method" with same signature in another ?.
I am writing a RPC library in python. The server supports remote calls to a server-side class (C). When the client connects to the server, it should create a proxy class for C with same signatures. When the program calls proxy instance, it should call the function with same arguments at the server.
You don't have to copy the function signature. Instead, accept arbitrary positional and keyword arguments and pass those on:
Here the
*args
and**kw
syntax in theproxy_function
signature are given a tuple and dictionary, respectively, of arguments passed into the function:Similarly, the
*args
and**kw
syntax in theoriginal_function()
call takes a sequence or a mapping, respectively, to apply their contents as separate arguments to the function being called:Combined, the two serve as an arbitrary-argument-pass-through for proxy functions.
Creating a full facade on the other hand is a little more involved:
This produces a whole new function object with the same argument names, and handles defaults by referencing the original proxied function defaults rather than copy them to the facade; this ensures that even mutable defaults continue to work.
The facade builder handles bound methods too; in that case
self
is removed from the call before passing on, to ensure that the target method is not getting an extraself
argument (which would be the wrong type anyway).Handling unbound methods is out of scope here; provide your own
_proxy
function in that case that can instantiate the proxied class and pass on arguments without theself
or provide a new value forself
; you cannot pass inself
unaltered.Demo:
Consider using boltons.wraps - here's an excerpt from the documentation: