日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
帶參數(shù)的全類型Python裝飾器

這篇短文中顯示的代碼取自我的小型開源項目按合同設(shè)計,它提供了一個類型化的裝飾器。裝飾器是一個非常有用的概念,你肯定會在網(wǎng)上找到很多關(guān)于它們的介紹。簡單說,它們允許在每次調(diào)用裝飾函數(shù)時(之前和之后)執(zhí)行代碼。通過這種方式,你可以修改函數(shù)參數(shù)或返回值、測量執(zhí)行時間、添加日志記錄、執(zhí)行執(zhí)行時類型檢查等等。請注意,裝飾器也可以為類編寫,提供另一種元編程方法(例如在 attrs 包中完成)

我們提供的服務(wù)有:網(wǎng)站建設(shè)、成都網(wǎng)站建設(shè)、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認證、相城ssl等。為上千余家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學管理、有技術(shù)的相城網(wǎng)站制作公司

在最簡單的形式中,裝飾器的定義類似于以下代碼:

def my_first_decorator(func):
def wrapped(*args, **kwargs):
# do something before
result = func(*args, **kwargs)
# do something after
return result
return wrapped
@my_first_decorator
def func(a):
return a

如上代碼,因為當定義了被包裝的嵌套函數(shù)時,它的周圍變量可以在函數(shù)內(nèi)訪問并保存在內(nèi)存中,只要該函數(shù)在某處使用(這在函數(shù)式編程語言中稱為閉包)。

很簡單, 但是這有一些缺點。最大的問題是修飾函數(shù)會丟失它的之前的函數(shù)名字(你可以用inspect.signature看到這個),它的文檔字符串,甚至它的名字, 這些是源代碼文檔工具(例如 sphinx)的問題,但可以使用標準庫中的 functools.wraps 裝飾器輕松解決:

from functools import wraps
from typing import Any, Callable, TypeVar, ParamSpec
P = ParamSpec("P") # 需要python >= 3.10
R = TypeVar("R")
def my_second_decorator(func: Callable[P, R]) -> Callable[P, R]:
@wraps(func)
def wrapped(*args: Any, **kwargs: Any) -> R:
# do something before
result = func(*args, **kwargs)
# do something after
return result
return wrapped
@my_second_decorator
def func2(a: int) -> int:
"""Does nothing"""
return a
print(func2.__name__)
# 'func2'
print(func2.__doc__)
# 'Does nothing'

在這個例子中,我已經(jīng)添加了類型注釋,注釋和類型提示是對 Python 所做的最重要的補充。更好的可讀性、IDE 中的代碼完成以及更大代碼庫的可維護性只是其中的幾個例子。上面的代碼應(yīng)該已經(jīng)涵蓋了大多數(shù)用例,但無法參數(shù)化裝飾器??紤]編寫一個裝飾器來記錄函數(shù)的執(zhí)行時間,但前提是它超過了一定的秒數(shù)。這個數(shù)量應(yīng)該可以為每個裝飾函數(shù)單獨配置。如果沒有指定,則應(yīng)使用默認值,并且應(yīng)使用不帶括號的裝飾器,以便更易于使用:

@time(threshold=2)
def func1(a):
...
# No paranthesis when using default threshold
@time
def func2(b):
...

如果你可以在第二種情況下使用括號,或者根本不提供參數(shù)的默認值,那么這個秘訣就足夠了:

from functools import wraps
from typing import Any, Callable, TypeVar, ParamSpec
P = ParamSpec("P") # 需要python >= 3.10
R = TypeVar("R")
def my_third_decorator(threshold: int = 1) -> Callable[[Callable[P, R]], Callable[P, R]]:
def decorator(func: Callable[P, R]) -> Callable[P, R]:
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> R:
# do something before you can use `threshold`
result = func(*args, **kwargs)
# do something after
return result
return wrapper
return decorator
@my_third_decorator(threshold=2)
def func3a(a: int) -> None:
...
# works
@my_third_decorator()
def func3b(a: int) -> None:
...
# Does not work!
@my_third_decorator
def func3c(a: int) -> None:
...

為了涵蓋第三種情況,有一些包,即 wraps 和 decorator,它們實際上可以做的不僅僅是添加可選參數(shù)。雖然質(zhì)量非常高,但它們引入了相當多的額外復(fù)雜性。使用 wrapt-decorated 函數(shù),在遠程集群上運行函數(shù)時,我進一步遇到了序列化問題。據(jù)我所知,兩者都沒有完全鍵入,因此靜態(tài)類型檢查器/ linter(例如 mypy)在嚴格模式下失敗。

當我在自己的包上工作并決定編寫自己的解決方案時,必須解決這些問題。它變成了一種可以輕松重用但很難轉(zhuǎn)換為庫的模式。

它使用標準庫的重載裝飾器。這樣,可以指定相同的裝飾器與我們的無參數(shù)一起使用。除此之外,它是上面兩個片段的組合。這種方法的一個缺點是所有參數(shù)都需要作為關(guān)鍵字參數(shù)給出(這畢竟增加了可讀性)

from typing import Callable, TypeVar, ParamSpec
from functools import partial, wraps
P = ParamSpec("P") # requires python >= 3.10
R = TypeVar("R
@overload
def typed_decorator(func: Callable[P, R]) -> Callable[P, R]:
...
@overload
def typed_decorator(*, first: str = "x", second: bool = True) -> Callable[[Callable[P, R]], Callable[P, R]]:
...
def typed_decorator(
func: Optional[Callable[P, R]] = None, *, first: str = "x", second: bool = True
) -> Union[Callable[[Callable[P, R]], Callable[P, R]], Callable[P, R]]:
"""
Describe what the decorator is supposed to do!
Parameters
----------
first : str, optional
First argument, by default "x".
This is a keyword-only argument!
second : bool, optional
Second argument, by default True.
This is a keyword-only argument!
"""
def wrapper(func: Callable[P, R], *args: Any, **kw: Any) -> R:
"""The actual logic"""
# Do something with first and second and produce a `result` of type `R`
return result
# Without arguments `func` is passed directly to the decorator
if func is not None:
if not callable(func):
raise TypeError("Not a callable. Did you use a non-keyword argument?")
return wraps(func)(partial(wrapper, func))
# With arguments, we need to return a function that accepts the function
def decorator(func: Callable[P, R]) -> Callable[P, R]:
return wraps(func)(partial(wrapper, func))
return decorator

稍后,我們可以分別使用我們的不帶參數(shù)的裝飾器

@typed_decorator
def spam(a: int) -> int:
return a
@typed_decorator(first = "y
def eggs(a: int) -> int:
return a

這種模式肯定有一些開銷,但收益大于成本。

原文:??https://lemonfold.io/posts/2022/dbc/typed_decorator/??


本文名稱:帶參數(shù)的全類型Python裝飾器
URL標題:http://www.dlmjj.cn/article/cccsdec.html