是否存在可动态更新参数默认值的f-docstring类工具?
解决动态更新函数文档字符串中参数默认值的问题
你用f-string写文档字符串的思路没问题,但实例方法里直接用{checks}这种写法行不通——函数定义时,参数变量还没绑定到默认值,编辑器静态分析也没法提前解析动态求值的f-string内容,所以悬停显示会不符合预期。
下面给你两种实用的解决方法:
方法一:用装饰器自动填充默认值
写一个装饰器,利用inspect模块获取函数参数的默认值,自动替换文档字符串里的占位符,以后改参数默认值时,文档字符串会自动更新:
import inspect def fill_defaults_in_docstring(func): sig = inspect.signature(func) # 提取有默认值的参数及其值 default_vals = { name: repr(param.default) for name, param in sig.parameters.items() if param.default is not inspect.Parameter.empty } # 替换文档字符串里的占位符 if func.__doc__: func.__doc__ = func.__doc__.format(**default_vals) return func
使用方式:在文档字符串里用{参数名}作为占位符,然后给函数加上装饰器:
@fill_defaults_in_docstring def check_availability(self, checks: int = 10, timeout: float = 1.5, apply_filters: bool = False) -> list[dict]: ''' Checks which proxies on "https://free-proxy-list.net/" are really available by requesting visible IP returned by "http://icanhazip.com" Args: checks (int): amount of checks, corresponds to the first entries in the considered proxies list); defaults to {checks} timeout (float): accepted response waiting time in seconds; defaults to {timeout} apply_filters (bool): If True a before generated filtered proxies list is considered for the checks, otherwise the entire list is considered; defaults to {apply_filters} Returns: list[dict]: list of confirmed proxies ''' # 函数实现代码 pass
方法二:手动动态更新文档字符串
如果不想用装饰器,也可以在函数定义后,用inspect提取默认值并格式化文档字符串:
import inspect def check_availability(self, checks: int = 10, timeout: float = 1.5, apply_filters: bool = False) -> list[dict]: ''' Checks which proxies on "https://free-proxy-list.net/" are really available by requesting visible IP returned by "http://icanhazip.com" Args: checks (int): amount of checks, corresponds to the first entries in the considered proxies list); defaults to {checks} timeout (float): accepted response waiting time in seconds; defaults to {timeout} apply_filters (bool): If True a before generated filtered proxies list is considered for the checks, otherwise the entire list is considered; defaults to {apply_filters} Returns: list[dict]: list of confirmed proxies ''' # 函数实现代码 pass # 动态更新文档字符串 sig = inspect.signature(check_availability) default_params = { name: param.default for name, param in sig.parameters.items() if param.default is not inspect.Parameter.empty } check_availability.__doc__ = check_availability.__doc__.format(**default_params)
这两种方法都能实现:修改参数默认值后,不用手动改文档字符串,编辑器也能正确显示填充后的默认值。
内容的提问来源于stack exchange,提问作者rumpel360
相关产品推荐
相关产品推荐

