0
0

Pythonデコレータのネストを減らすデコレータ

Posted at

概要

デコレータ自身に引数を持つ場合の書き方がややこしいので、ネストを減らすデコレータを作ってみました

デコレータのデコレータが無い場合の実行例

import functools

def sample_decorator(print_key: str):
    def _sample_decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            print(f"function start, name: {func.__name__}")
            print(f"print value: {kwargs[print_key]}")
            result = func(*args, **kwargs)
            print("function end")
            return result

        return wrapper

    return _sample_decorator


@sample_decorator(print_key="file_name")
def sample_function(file_name):
    print("this is sample_function")


sample_function(file_name="hogehuga")
# function start, name: sample_function
# print value: hogehuga
# this is sample_function
# function end

ネストを減らすデコレータ

import functools

def decorate_args(func):
    def _decorate_args(*args, **kwargs):
        @functools.wraps(func)
        def wrapper(f):
            return func(f, *args, **kwargs)

        return wrapper

    return _decorate_args

実行例

@decorate_args
def sample_decorator(func, print_key: str):
    def wrapper(*args, **kwargs):
        print(f"function start, name: {func.__name__}")
        print(f"print value: {kwargs[print_key]}")
        result = func(*args, **kwargs)
        print("function end")
        return result

    return wrapper


@sample_decorator(print_key="file_name")
def sample_function(file_name):
    print("this is sample_function")


sample_function(file_name="hogehuga")
# function start, name: sample_function
# print value: hogehuga
# this is sample_function
# function end

まとめ

デコレータのネストを減らすデコレータを使うと、入れ子が減ることを確認できます。
ついでに、デコレートされる側のデコレータには、@functools.wraps(func)を書かなくてよくなりますね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0