0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】ラッパー関数を使って処理結果をおしゃれにprint()する

Posted at

こういうやつ

image.png

result.pyとして保存する。

from typing import Callable

from display import AnsiStyle


def print_result(name: str) -> Callable:
    """指定した関数の実行状態を表示するデコレーター。

    実行中のステータスと、関数の戻り値に応じた成功/失敗メッセージを表示する。

    Args:
        name (str): 関数の説明や識別用の名前。

    Returns:
        Callable: ラップされた関数を返すデコレーター。

    """
    def _print_result(func: Callable) -> Callable:
        """
        指定した関数の実行前後にステータスを表示する。

        Args:
            func (Callable): デコレートする関数。

        Returns:
            Callable: ラップされた関数。
        """
        def wrapper(*args: any, **kwargs: any) -> None:
            """関数の実行状態を表示し、結果に応じたメッセージを出力する。"""
            print(f"[    ] {name}", end="\r")

            result = func(*args, **kwargs)
            colorize_result = AnsiStyle.format("OK" if result else "NG", "GREEN" if result else "RED")

            print(f"[ {colorize_result} ] {name}")

        return wrapper
    return _print_result

つかいかた

import time

import result


@result.print_result(name="成功する関数")
def a() -> bool:
    time.sleep(3)
    return True


@result.print_result(name="失敗する関数")
def b() -> bool:
    time.sleep(3)
    return False


a()
b()


結果

image.png

image.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?