當前位置: 妍妍網 > 碼農

必用的10個Python裝飾器

2024-02-28碼農

作者:Gabe A, M.Sc

裝飾器(Decorators) 是Python中一種強大而靈活的功能, 用於修改或增強函式或類的行為 。裝飾器本質上是一個函式,它接受另一個函式或類作為參數,並返回一個新的函式或類。它們通常用於在不修改原始程式碼的情況下添加額外的功能或功能。

裝飾器的語法使用 @ 符號,將裝飾器套用於目標函式或類。下面我們將介紹10個非常簡單但是卻很有用的自訂裝飾器。

1、@timer:測量執行時間

最佳化程式碼效能是非常重要的。@timer裝飾器可以幫助我們跟蹤特定函式的執行時間。透過用這個裝飾器包裝函式,我可以快速辨識瓶頸並最佳化程式碼的關鍵部份。下面是它的工作原理:

import time
deftimer(func):
defwrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} took {end_time - start_time:.2f} seconds to execute.")
return result
return wrapper
 @timer
defmy_data_processing_function():
# Your data processing code here

將@timer與其他裝飾器結合使用,可以全面地分析程式碼的效能。

2、@memoize:緩存結果

在數據科學中,我們經常使用計算成本很高的函式。@memoize裝飾器幫助我緩存函式結果,避免了相同輸入的冗余計算,顯著加快工作流程:

defmemoize(func):
cache = {}
defwrapper(*args):
if args in cache:
return cache[args]
result = func(*args)
cache[args] = result
return result
return wrapper
 @memoize
deffibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)

在遞迴函式中也可以使用@memoize來最佳化重復計算。

3、@validate_input:數據驗證

數據完整性至關重要,@validate_input裝飾器可以驗證函式參數,確保它們在繼續計算之前符合特定的標準:

defvalidate_input(func):
defwrapper(*args, **kwargs):
# Your data validation logic here
if valid_data:
return func(*args, **kwargs)
else:
raise ValueError("Invalid data. Please check your inputs.")
return wrapper
 @validate_input
defanalyze_data(data):
# Your data analysis code here

可以方便的使用@validate_input在數據科學計畫中一致地實作數據驗證。

4、@log_results:日誌輸出

在執行復雜的數據分析時,跟蹤每個函式的輸出變得至關重要。@log_results裝飾器可以幫助我們記錄函式的結果,以便於偵錯和監控:

deflog_results(func):
defwrapper(*args, **kwargs):
result = func(*args, **kwargs)
with open("results.log""a"as log_file:
log_file.write(f"{func.__name__} - Result: {result}\n")
return result
return wrapper
 @log_results
defcalculate_metrics(data):
# Your metric calculation code here

將@log_results與日誌庫結合使用,以獲得更高級的日誌功能。

5、@suppress_errors:優雅的錯誤處理

數據科學計畫經常會遇到意想不到的錯誤,可能會破壞整個計算流程。@suppress_errors裝飾器可以優雅地處理異常並繼續執行:

defsuppress_errors(func):
defwrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Error in {func.__name__}{e}")
returnNone
return wrapper
 @suppress_errors
defpreprocess_data(data):
# Your data preprocessing code here

@suppress_errors可以避免隱藏嚴重錯誤,還可以進行錯誤的詳細輸出,便於偵錯。

6、@validate_output:確保品質結果

確保數據分析的品質至關重要。@validate_output裝飾器可以幫助我們驗證函式的輸出,確保它在進一步處理之前符合特定的標準:

defvalidate_output(func):
defwrapper(*args, **kwargs):
result = func(*args, **kwargs)
if valid_output(result):
return result
else:
raise ValueError("Invalid output. Please check your function logic.")
return wrapper
 @validate_output
defclean_data(data):
# Your data cleaning code here

這樣可以始終為驗證函式輸出定義明確的標準。

7、@retry:重試執行

@retry裝飾器幫助我在遇到異常時重試函式執行,確保更大的彈性:

import time
defretry(max_attempts, delay):
defdecorator(func):
defwrapper(*args, **kwargs):
attempts = 0
while attempts < max_attempts:
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Attempt {attempts + 1} failed. Retrying in {delay} seconds.")
attempts += 1
time.sleep(delay)
raise Exception("Max retry attempts exceeded.")
return wrapper
return decorator
 @retry(max_attempts=3, delay=2)
deffetch_data_from_api(api_url):
# Your API data fetching code here

使用@retry時應避免過多的重試。

8、@visualize_results:漂亮的視覺化

@visualize_results裝飾器數據分析中自動生成漂亮的視覺化結果

import matplotlib.pyplot as plt
defvisualize_results(func):
defwrapper(*args, **kwargs):
result = func(*args, **kwargs)
plt.figure()
# Your visualization code here
plt.show()
return result
return wrapper
 @visualize_results
defanalyze_and_visualize(data):
# Your combined analysis and visualization code here

9、@debug:偵錯變得更容易

偵錯復雜的程式碼可能非常耗時。@debug裝飾器可以打印函式的輸入參數和它們的值,以便於偵錯:

defdebug(func):
defwrapper(*args, **kwargs):
print(f"Debugging {func.__name__} - args: {args}, kwargs: {kwargs}")
return func(*args, **kwargs)
return wrapper
 @debug
defcomplex_data_processing(data, threshold=0.5):
# Your complex data processing code here

10、@deprecated:處理廢棄的函式

隨著我們的計畫更新叠代,一些函式可能會過時。@deprecated裝飾器可以在一個函式不再被推薦時通知使用者:

import warnings
defdeprecated(func):
defwrapper(*args, **kwargs):
warnings.warn(f"{func.__name__} is deprecated and will be removed in future versions.", DeprecationWarning)
return func(*args, **kwargs)
return wrapper
 @deprecated
defold_data_processing(data):
# Your old data processing code here

總結

裝飾器是Python中一個非常強大和常用的特性,它可以用於許多不同的情況,例如緩存、日誌記錄、許可權控制等。透過在計畫中使用的我們介紹的這些Python裝飾器,可以簡化我們的開發流程或者讓我們的程式碼更加健壯。

加入知識星球【我們談論數據科學】

600+小夥伴一起學習!