[英]Python decorator to transform input and/or output of a function or method
下面的函數做了(似乎做了)這項工作,但似乎有比必要更多的樣板。
我相信那里有更優雅的方式。 可以將其中的一些代碼分解出來,使其看起來不像現在的復制/粘貼/編輯補丁工作。
但請注意,優雅並不是一切:我不希望性能受到影響。 例如,我可以通過做兩個裝飾器將代碼減半:一個用於輸入轉換,另一個用於輸出轉換。 但這會比當前版本效率低。
def input_output_decorator(preprocess=None, postprocess=None):
def decorator(func):
if inspect.ismethod(func):
if preprocess is not None:
if postprocess is not None: # both pre and post processes
@wraps(func)
def func_wrapper(self, *args, **kwargs):
return postprocess(func(self, preprocess(*args, **kwargs)))
else: # a preprocess but no postprocess
@wraps(func)
def func_wrapper(self, *args, **kwargs):
return func(self, preprocess(*args, **kwargs))
else: # no preprocess
if postprocess is not None: # no preprocess, but a postprocess
@wraps(func)
def func_wrapper(self, *args, **kwargs):
return postprocess(func(*args, **kwargs))
else: # no pre or post process at all
func_wrapper = func
return func_wrapper
else:
if preprocess is not None:
if postprocess is not None: # both pre and post processes
@wraps(func)
def func_wrapper(*args, **kwargs):
return postprocess(func(preprocess(*args, **kwargs)))
else: # a preprocess but no postprocess
@wraps(func)
def func_wrapper(*args, **kwargs):
return func(preprocess(*args, **kwargs))
else: # no preprocess
if postprocess is not None: # no preprocess, but a postprocess
@wraps(func)
def func_wrapper(*args, **kwargs):
return postprocess(func(*args, **kwargs))
else: # no pre or post process at all
func_wrapper = func
return func_wrapper
return decorator
一些使用示例:
>>> # Examples with "normal functions"
>>> def f(x=3):
... '''Some doc...'''
... return x + 10
>>> ff = input_output_decorator()(f)
>>> print((ff(5.0)))
15.0
>>> ff = input_output_decorator(preprocess=int)(f)
>>> print((ff(5.0)))
15
>>> ff = input_output_decorator(preprocess=int, postprocess=lambda x: "Hello {}!".format(x))(f)
>>> print((ff('5')))
Hello 15!
>>> ff = input_output_decorator(postprocess=lambda x: "Hello {}!".format(x))(f)
>>> print((ff(5.0)))
Hello 15.0!
>>> print((ff.__doc__))
Some doc...
>>>
>>> # examples with methods (bounded, class methods, static methods
>>> class F:
... '''This is not what you'd expect: The doc of the class, not the function'''
... def __init__(self, y=10):
... '''Initialize'''
... self.y = y
... def __call__(self, x=3):
... '''Some doc...'''
... return self.y + x
... @staticmethod
... def static_method(x, y):
... return "What {} {} you have".format(x, y)
... @classmethod
... def class_method(cls, x):
... return "{} likes {}".format(cls.__name__, x)
>>>
>>> f = F()
>>> ff = input_output_decorator()(f)
>>> print((ff(5.0)))
15.0
>>> ff = input_output_decorator(preprocess=int)(f)
>>> print((ff(5.0)))
15
>>> ff = input_output_decorator(preprocess=int, postprocess=lambda x: "Hello {}!".format(x))(f)
>>> print((ff('5')))
Hello 15!
>>> ff = input_output_decorator(postprocess=lambda x: "Hello {}!".format(x))(f)
>>> print((ff(5.0)))
Hello 15.0!
>>> print((ff.__doc__))
This is not what you'd expect: The doc of the class, not the function
我的最終實現基於@micky-loo 的(已接受)答案,並受到@a_guest 答案的啟發:
def input_output_decorator(preprocess=None, postprocess=None):
def decorator(func):
if preprocess and postprocess:
def func_wrapper(*args, **kwargs):
return postprocess(func(preprocess(*args, **kwargs)))
elif preprocess:
def func_wrapper(*args, **kwargs):
return func(preprocess(*args, **kwargs))
elif postprocess:
def func_wrapper(*args, **kwargs):
return postprocess(func(*args, **kwargs))
else:
return func
return wraps(func)(func_wrapper)
return decorator
使用兩個不同的裝飾器可以實現更緊湊的實現。 確實,在進行預處理后處理的情況下,鏈中還會有一個函數調用,但這幾乎不會影響性能。
import functools
import inspect
def preprocess(pre):
def decorator(func):
if inspect.ismethod(func):
def wrapper(self, *args, **kwargs):
return func(self, pre(*args, **kwargs))
else:
def wrapper(*args, **kwargs):
return func(pre(*args, **kwargs))
return functools.wraps(func)(wrapper)
return decorator
def postprocess(post):
def decorator(func):
def wrapper(*args, **kwargs):
return post(func(*args, **kwargs))
return functools.wraps(func)(wrapper)
return decorator
您不需要進行檢查檢查。 if/else 嵌套可以展平,使代碼更具可讀性。
from functools import wraps
def input_output_decorator(preprocess=None, postprocess=None):
def decorator(func):
if preprocess and postprocess:
@wraps(func)
def func_wrapper(*args, **kwargs):
return postprocess(func(preprocess(*args, **kwargs)))
elif preprocess:
@wraps(func)
def func_wrapper(*args, **kwargs):
return func(preprocess(*args, **kwargs))
elif postprocess:
@wraps(func)
def func_wrapper(*args, **kwargs):
return postprocess(func(*args, **kwargs))
else:
func_wrapper = func
return func_wrapper
return decorator
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.