如何使用 Python 裝飾器保留函數簽名?

Barbara Streisand
發布: 2024-10-17 17:00:03
原創
870 人瀏覽過

How to Preserve Function Signatures with Python Decorators?

Preserving Function Signatures with Decorators

Decorators are a powerful tool in Python, but they can also introduce problems with decorated function signatures. To preserve the original function's signature, consider the following approaches:

Approach 1: decorator module

Install the decorator module (pip install decorator) and adapt your decorator to use its @decorator.decorator syntax:

<code class="python">import decorator

@decorator.decorator
def args_as_ints(f, *args, **kwargs):
    args = [int(x) for x in args]
    kwargs = dict((k, int(v)) for k, v in kwargs.items())
    return f(*args, **kwargs)</code>
登入後複製

Approach 2: functools.wraps() (Python 3.4+)

Python 3.4 introduced functools.wraps(), which preserves function signatures:

<code class="python">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</code>
登入後複製

Both approaches effectively preserve the function signature after decoration. Additionally, functools.wraps() can be used for compatibility with older Python versions.

以上是如何使用 Python 裝飾器保留函數簽名?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!