Python function decorator

I decided to leave it on Qiita as a summary of research and teaching materials for review. I think that there are many unfriendly descriptions because it is for my own organization. In that case, please use it as a collection of links to the reference URL list.

Origin

Originally, there is a decorator pattern in the design pattern, and it seems that Python decorators also come from it.

Decorator pattern

Dynamically add new features and behaviors to existing objects

Source: Decorator Pattern https://en.wikipedia.org/wiki/Decorator_%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3

We will proceed with understanding based on this definition. Roughly speaking, you can add pre-processing and post-processing to the processing you want to execute, or replace the response itself.

Strictly speaking, the Decorator pattern and Decorator are different, or the latter seems to be the former element, but I don't dig deeper there. Reference: python-3 patterns, idioms and test https://python-3-patterns-idioms-test.readthedocs.io/en/latest/PythonDecorators.html

First object

Functions are first-class citizens in Python. Python functions are objects, and you can use them for their arguments and return values. The decorator can execute the function it receives as an argument as part of the decorator's own processing.

Operation check

I was playing with the following things.

decorater.py


#Define a decorator
def decorator(func):
    #The name does not have to be deco. It can be dedede.
    def _deco(*args, **kwargs):
        #The name of the function can be anything. You can also use decodeco.
        print('japan')
        func()
        print('america')
    return _decorator

# @Attach to associate the decorator with the function
#If the decorator is dedede@Dedede
@decorator
def hello_world():
    print('china')
# japan
# china
# america

@decorator
def hello_earth():
    print('england')
# japan
# england
# america

@decorator
def hello_tokyo():
    print('tokyo')
# japan
# tokyo
# america

Each function is passed as an argument to the decorator function and is executed inside the decorator. The function with @decorator at the beginning becomes the argument of the decorator as func. The name of the decorator can be anything. Give it an appropriate name for your purpose. In the above example, we were able to insert the print process between japan and america.

Implementation example

Since the operation was confirmed, it is implemented. We have implemented a common API in API Gateway + Lambda. As a matter of fact, it is designed and implemented by someone other than me, so I will briefly describe some of the elements. Performs request parameter pre-processing and log processing for lambda processing.

implementation.py


    def implementation(func):
        def _deco(*args, **kwargs):
            # *args can receive lambda events.*args is a variadic argument.

            print("lambda start")
            print(args[0])
            #It is easy to use if you create and call the processing for the log separately. Since it is temporary here, print()

            params = json.loads(event.get("body"))
            if event.get('pathParameters'):
                params.update(event.get('pathParameters'))
            # get,post Combine each process into one params.

            if not params.get("id"):
                return error_response()
            #If the parameter does not have an ID, you can perform processing such as returning an error.

            response = func(params, id)
            #Get the execution result of individual processing
            print("lamdba end")
            return response
            #If you set a return value at the bottom of the nest, it will be replaced with the new return value.
            #You can spit out the log before returning the response of the original process.
        return _deco

lambda_function.py


@implementation
def handler(params, id):
    """
Some processing
    """
   return success_response()

When executing the original process, you can add functions such as preparing the log as a common process, organizing the parameters, checking the elements, and replacing the response with the one at the time of error.

Decorator with arguments to associate with individual processing

For example, when performing validation, the required value changes depending on the individual processing. Therefore, in order to be able to pass the schema for validation defined in the individual process as an argument, use a decorator with an argument.

implementation_with_params


def implementation_with_params(schema):
    def _deco(func):
        def _decodeco(*args, **kwargs):
            params = *args[0].get("body")
            error = validator(schema, params)
            #Pass some validator to the defined function.
            if error:
                return error_response()
            response = func(params)
            return response
        return _decodeco
    return _deco

lambda_function.py


#List of keys for validation
SCHEMA = ["id","user_name", "password", "address", "tel"]

@implementation_with_params(schema=SCHEMA)
def handler(params)
    """
Some processing
    """
    return success_response()

In fact, we are validating with Cerberous.

Other uses

The response content change, request parameter pre-processing and log processing, and validation processing are also described, but other uses are also possible. -Record the start and end of processing and measure performance ・ Authentication processing ・ Session management

Reference URL

Official documentation https://docs.python.org/ja/3/reference/compound_stmts.html#function About Python decorators https://qiita.com/mtb_beta/items/d257519b018b8cd0cc2e 12 Steps to Understanding Python Decorators https://qiita.com/rdtr/items/d3bc1a8d4b7eb375c368 Reintroduction to Python Decorators ~ Learn Decorators by Type ~ https://qiita.com/macinjoke/items/1be6cf0f1f238b5ba01b How to make a decorator with arguments https://qiita.com/utgwkk/items/d7c6af97b81df9483f9e Rediscover Python-Decorators and their usage patterns- https://slideship.com/users/@rhoboro/presentations/2017/12/YagWLokYuWX5Er78UdLbWX/?p=23 Decorator pattern https://ja.wikipedia.org/wiki/Decorator%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3 Design Pattern #Decorator https://qiita.com/nirperm/items/398cb970826fa972a94f python-3 patterns,idioms and test https://python-3-patterns-idioms-test.readthedocs.io/en/latest/PythonDecorators.html Design pattern in Python ~ Py design ~ Decorator pattern https://pydp.info/GoF_dp/structure/09_Decorator/

Digression

Javascript and Typescript also have decorators.

How to use JavaScript decorators https://qiita.com/kerupani129/items/2b3f2cba195c0705b2e5 About TypeScript Decorator – Official Document Japanese Translation https://mae.chab.in/archives/59845 Write clean and easy-to-read JavaScript Get ahead of the basics of decorators https://www.webprofessional.jp/javascript-decorators-what-they-are/

Recommended Posts

Python function decorator
python function ①
[Python] function
python function ②
Python higher-order function (decorator) sample
Note: Python Decorator
python enumerate function
Python> function> Closure
[Python] Generator function
Python> function> Inner function
Create a Python function decorator with Class
About function arguments (python)
Function execution time (Python)
python decorator to retry
Python function argument summary
Python print function (sequel)
Python: About function arguments
Python decorator operation memo
I tried Python> decorator
Create a function in Python
Decorator 1
Python
Use callback function in Python
[python] Value of function object (?)
ntile (decile) function in python
[Python] Etymology of python function names
About python beginner's memorandum function
About the enumerate function (python)
python url setting include function
Python #function 2 for super beginners
Decorator 2
Draw implicit function in python
Immediate function in python (lie)
Decorator
Decorator
Decorator 1
Decorator 2
Decorator
Decorator
Note: Python Decorator
Decorator to retry
Python function decorator
[Python] What is a zip function?
Call a Python function from p5.js.
[python] Callback function (pass function as argument)
Implement R's power.prop.test function in python
Function argument type definition in python
Included notation in Python function arguments
[Introduction to Udemy Python 3 + Application] 57. Decorator
Write AWS Lambda function in Python
[Python] What is @? (About the decorator)
Measure function execution time in Python
[Python] Make the function a lambda function
Python #len function for super beginners
Function synthesis and application in Python
Create a Python general-purpose decorator framework
Basic Python operation 2nd: Function (argument)
How to use python zip function
[Python] Difference between function and method
[Python] Function arguments * (star) and ** (double star)
[OpenCV; Python] Summary of findcontours function
[Python3] Define a decorator to measure the execution time of a function
kafka python
Python3> Functions> Function Renaming Mechanism> f = fib
Python basics ⑤
python + lottery 6
Python Summary