how to create a new method with signature of another

2024/4/14 4:12:31

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.


Consider using boltons.wraps - here's an excerpt from the documentation:

boltons.funcutils.wraps(func, injected=None, **kw)

Modeled after the built-in functools.wraps(), this function is used tomake your decorator’s wrapper functions reflect the wrappedfunction’s:

Name Documentation Module Signature

The built-in functools.wraps() copies the first three, but does notcopy the signature. This version of wraps can copy the innerfunction’s signature exactly, allowing seamless usage andintrospection. Usage is identical to the built-in version:

>>> from boltons.funcutils import wraps
>>> def print_return(func):
...     @wraps(func)
...     def wrapper(*args, **kwargs):
...         ret = func(*args, **kwargs)
...         print(ret)
...         return ret
...     return wrapper
>>> @print_return
... def example():
...     '''docstring'''
...     return 'example return value'
>>> val = example()
example return value
>>> example.__name__
>>> example.__doc__

In addition, the boltons version of wraps supports modifying the outersignature based on the inner signature. By passing a list of injectedargument names, those arguments will be removed from the outerwrapper’s signature, allowing your decorator to provide arguments thataren’t passed in.

Parameters: func (function) – The callable whose attributes are tobe copied.

injected (list) – An optional list of argument names which should notappear in the new wrapper’s signature.

update_dict (bool) – Whether to copy other, non-standard attributes offunc over to the wrapper. Defaults to True.

inject_to_varkw (bool) – Ignore missing arguments when a **kwargs-typecatch-all is present. Defaults to True.

For more in-depth wrapping of functions, see the FunctionBuilder type,on which wraps was built.

Related Q&A

Converting a full column of integer into string with thousands separated using comma in pandas

Say I have population data stored in a column of a dataframe using pandas in python with Country names as row indices. How do I convert the whole column of numbers into string thousands separator using…

Nested WHILE loops in Python

I am a beginner with Python and trying few programs. I have something like the following WHILE loop construct in Python (not exact). IDLE 2.6.4 >>> a=0 >>> b=0 >>> whil…

Fastest way to drop rows / get subset with difference from large DataFrame in Pandas

Question Im looking for the fastest way to drop a set of rows which indices Ive got or get the subset of the difference of these indices (which results in the same dataset) from a large Pandas DataFram…

Python inheritance: when and why __init__

Im a Python newbie, trying to understand the philosophy/logic behind the inheritance methods. Questions ultimately regards why and when one has to use the __init__ method in a subclass. Example:It seem…

TypeError: A Future or coroutine is required

I try make auto-reconnecting ssh client on asyncssh. (SshConnectManager must stay in background and make ssh sessions when need)class SshConnectManager(object): def __init__(self, host, username, passw…

Python socket closed before all data have been consumed by remote

I am writing a Python module which is communicating with a go program through unix sockets. The client (the python module) write data to the socket and the server consume them.# Simplified version of t…

Python child process silently crashes when issuing an HTTP request

Im running into an issue when combining multiprocessing, requests (or urllib2) and nltk. Here is a very simple code:>>> from multiprocessing import Process >>> import requests >>…

Shared variable in concurrent.futures.ProcessPoolExecutor() python

I want to use parallel to update global variable using module concurrent.futures in pythonIt turned out that using ThreadPoolExecutor can update my global variable but the CPU did not use all their pot…

MongoEngine - Another user is already authenticated to this database. You must logout first

Can anyone please explain why I am getting error Another user is already authenticated to this database. You must logout first when connecting to MongoDB using Flask MongoEngine?from mongoengine.conne…

How to bucketize a group of columns in pyspark?

I am trying to bucketize columns that contain the word "road" in a 5k dataset. And create a new dataframe. I am not sure how to do that, here is what I have tried far : from…