classification
Title: profiling-compatible functools.wraps
Type: enhancement Stage:
Components: Library (Lib) Versions: Python 3.11
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: Anthony Sottile, rhettinger
Priority: normal Keywords:

Created on 2021-06-20 20:40 by Anthony Sottile, last changed 2021-06-20 22:57 by pablogsal.

Messages (1)
msg396199 - (view) Author: Anthony Sottile (Anthony Sottile) * Date: 2021-06-20 20:40
this is a small proposal to add a new function to the functools module which provides better profiling-compatible `@functools.wraps(...)`

the rationale comes from https://github.com/Yelp/named_decorator (which is dead / abandoned)

the tl;dr from there is any time a decorator is involved in a profile it becomes very difficult to trace because everything becomes tangled around common decorators (because function names are used from the code object)

here is the proposal and an initial implementation:


def wraps_with_name(func, decorator, **kwargs):
    def wraps_with_name_decorator(wrapped):
        new_name = f'{func.__name__}@{decorator.__name__}'
        new_code = wrapped.__code__.replace(co_name=new_name)
        # would be nice if `types.FunctionType` had a `.replace(...)` too!
        new_wrapped = types.FunctionType(
            new_code,
            wrapped.__globals__,
            new_name,
            wrapped.__defaults__,
            wrapped.__closure__,
        )
        return functools.wraps(func, **kwargs)(new_wrapped)
    return better_wraps_decorator

the usage would be similar to `functools.wraps`, here is an example:

```python
def my_decorator(func):
    @functools.wraps_with_name(func, my_decorator)
    def my_decorator_inner(*args, **kwargs):
        return func(*args, **kwargs)
    return my_decorator
```
History
Date User Action Args
2021-06-20 22:57:55pablogsalsetnosy: + rhettinger
2021-06-20 20:40:39Anthony Sottilecreate