Python 3.11中包装函数*args与**kwargs的最佳注解实践
包装函数中*args和**kwargs的类型注解最佳实践
请考虑以下包装函数:
import numpy as np from matplotlib import pyplot as plt from typing import Any def plot_histogram(data: np.ndarray, xlabel: str | None = None, ylabel: str | None = None, log: bool = False, *args: Any, **kwargs: Any) -> plt.Axes: _, ax = plt.subplots() if log: data = np.log10(data) hist, bins = np.histogram(data, bins='auto') hist = hist.astype(float) bins = 10 ** bins bin_widths = np.diff(bins) hist /= (bin_widths * np.sum(hist)) ax.loglog(bins[:-1], hist, *args, **kwargs) else: hist, bins = np.histogram(data, bins='auto', density=True) ax.plot(bins[:-1], hist, *args, **kwargs) if xlabel: ax.set_xlabel(xlabel) if ylabel: ax.set_ylabel(ylabel) return ax
我已阅读Python的typing文档以及PEP 612和PEP 692(后者针对Python 3.12),但仍不确定在该场景下注解*args和**kwargs的最佳实践。
如代码片段所示,我目前使用typing.Any作为*args和**kwargs的注解,但这似乎并非最佳实践。
补充说明: 本问题曾被判定为另一问题的重复项,但我的问题专门针对包装函数的注解,仅在其中一个回答中有所涉及。尽管该回答内容详尽,但我见过其他解决方案,希望针对此特定场景考量不同观点。本问题被关闭前仅收到一个相关回答示例。
内容的提问来源于stack exchange,提问作者Shayan Taheri
相关产品推荐
相关产品推荐

