functools.wraps の紹介
メニューを表示するにはスワイプしてください
独自のデコレーターを作成する際、元の関数の名前、ドックストリング、モジュールなどの重要な情報が失われることがよくあります。これは、デコレーターが元の関数を新しいラッパー関数で置き換えるために発生します。この問題を解決するには、Python標準ライブラリの functools.wraps デコレーターを使用します。
functools.wraps をラッパー関数に適用することで、元の関数のメタデータを保持できます。これにより、
- 関数の
__name__属性が元のまま保持される; - 関数の
__doc__文字列がそのまま維持される; __module__属性やその他のメタデータも保存される。
メタデータの保持は、デバッグ、ドキュメント生成、関数のイントロスペクションに依存するツールにとって重要です。functools.wraps を使わない場合、スタックトレースやヘルプユーティリティが誤った情報を表示し、コードの保守やデバッグが難しくなります。
1234567891011121314151617181920212223from functools import wraps # Define a decorator that will wrap another function def my_decorator(func): # Use @wraps to preserve metadata from the original function @wraps(func) def wrapper(*args, **kwargs): # This code runs before the original function print("Running the decorated function...") return func(*args, **kwargs) # Call the original function return wrapper # Return the wrapper as the new decorated function # Apply the decorator to a function def say_hello(): """Prints a hello message.""" print("Hello!") say_hello = my_decorator(say_hello) say_hello() # Print out the preserved metadata print(f"Function name: {say_hello.__name__}") # Name is preserved print(f"Docstring: {say_hello.__doc__}") # Docstring is preserved
functools.wraps を使用して、デコレーター作成時に元の関数のメタデータを保持する方法を確認できます。ラッパーに functools.wraps を適用することで、関数名やドックストリングなどの属性がデコレーション後も失われないようにできます。
すべて明確でしたか?
フィードバックありがとうございます!
セクション 4. 章 7
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 4. 章 7