How to create a wrapper that preserves the signature of the function to wrap

Especially in function decorators, you often create and return a function that wraps the modifying function you receive as an argument, but sometimes you want the signature of the wrapping function to be the same as the wrapped function. Starting with Python 3.4, this implementation is possible using a decorator called wraps provided by the standard library functools.

In the example below, the funny_function modified with the decorator ʻargs_as_ints (ie the wrappermodified withfunctools.wraps) has the same signature as the modified function funny_function, but all Convert the argument to ʻint and do the same calculation for the original function.

python


# Source: https://stackoverflow.com/questions/147816/preserving-signatures-of-decorated-functions

import functools

def args_as_ints(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        args = [int(x) for x in args]
        kwargs = dict((k, int(v)) for k, v in kwargs.items())
        return func(*args, **kwargs)
    return wrapper

@args_as_ints
def funny_function(x, y, z=3):
    """Computes x*y + 2*z"""
    return x*y + 2*z

After being qualified, the funny_function has a member called __wrapped__, which holds the original function.

Use the standard library inspect to find out the signature of a function. You can use the signature function provided by inspect to retrieve the function's signature as aSignature object. The following code ensures that the funny_function signature is the same before and after qualification.

python


>>> from inspect import signature
>>> str(signature(funny_function))
'(x, y, z=3)'
>>> signature(funny_function) == signature(funny_function.__wrapped__)
True

Recommended Posts

How to create a wrapper that preserves the signature of the function to wrap
Create a function to get the contents of the database in Go
How to create a function object from a string
Various methods to numerically create the inverse function of a certain function Introduction
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
How to make a Raspberry Pi that speaks the tweets of the specified user
Create a function to visualize / evaluate the clustering result
How to solve the recursive function that solved abc115-D
# Function that returns the character code of a string
How to hit the document of Magic Function (Line Magic)
Various methods to numerically create the inverse function of a certain function Part 1 Polynomial regression
How to create a property of relations that can be prefetch_related by specific conditions
[Ubuntu] How to delete the entire contents of a directory
I made a function to check the model of DCGAN
How to run the Export function of GCP Datastore automatically
How to find the scaling factor of a biorthogonal wavelet
How to connect the contents of a list into a string
[Linux] [C / C ++] How to get the return address value of a function and the function name of the caller
How to use the zip function
How to create a Conda package
How to make a recursive function
How to create a virtual bridge
How to create a Dockerfile (basic)
How to create a config file
Overview of how to create a server socket and how to establish a client socket
How to determine the existence of a selenium element in Python
[Introduction to Python] How to split a character string with the split function
[Go] Create a CLI command to change the extension of the image
How to check the memory size of a dictionary in Python
A function that measures the processing time of a method in python
How to find the memory address of a Pandas dataframe value
[Python3] Define a decorator to measure the execution time of a function
How to create a large amount of test data in MySQL? ??
[python] A note that started to understand the behavior of matplotlib.pyplot
[NNabla] How to remove the middle tier of a pre-built network
[Python] A simple function to find the center coordinates of a circle
[Python] A program that rotates the contents of the list to the left
How to create a clone from Github
How to create a git clone folder
How to check the version of Django
How to create a repository from media
How to divide and process a data frame using the groupby function
[Python] Explains how to use the range function with a concrete example
[Python] A program that calculates the number of socks to be paired
[Introduction to Python] How to sort the contents of a list efficiently with list sort
A memorandum of how to write pandas that I tend to forget personally
[NNabla] How to add a quantization layer to the middle layer of a trained model
How to put a line number at the beginning of a CSV file
[Introduction to Python] How to write a character string with the format function
[Development environment] How to create a data set close to the production DB
How to play a video while watching the number of frames (Mac)
Python: I want to measure the processing time of a function neatly
[Python] Note: A self-made function that finds the area of the normal distribution
I made a function to see the movement of a two-dimensional array (Python)
Create a bot that posts the number of people positive for the new coronavirus in Tokyo to Slack
How to pass the execution result of a shell command in a list in Python
A simple example of how to use ArgumentParser
How to find the area of the Voronoi diagram
How to mention a user group in slack notification, how to check the id of the user group
How to create a Python virtual environment (venv)
The story of IPv6 address that I want to keep at a minimum