Python函数参数共存术语及布尔参数签名设计咨询
Python 文件字节读取函数的两个问题
1. 参数配对错误的提示术语问题
我编写了一个读取文件字节的Python函数:
def read_bytes(path: pathlib.Path, tohex: bool = True, hexformat: Optional[Callable] = None) -> bytes | hex | Any:
其中tohex用于控制是否将字节转为十六进制,hexformat是格式化十六进制结果的可调用对象,示例调用如下:
read_bytes(pathlib.Path("myfile.txt"), tohex=True, hexformat = str.upper)
函数有个规则:tohex和hexformat必须同时传入或都不传,违反此规则时需要抛出错误,但我不知道错误提示里应该使用什么合适的术语。目前的错误判断代码如下:
def read_bytes(path: pathlib.Path, hex: bool = True, hexformat: Optional[Callable] = None) -> bytes | hex | Any: if hex and hexformat is not None: raise TypeError("hex and hexformat are ___")
2. 布尔参数toupper的函数签名选择问题
如果把hexformat替换为默认值为False的布尔参数toupper,以下两种函数签名写法哪种更优:
写法一
def read_bytes(path: pathlib.Path, tohex: bool = True, toupper: bool = False) -> bytes | hex | Any:
问题:无法检测调用者在tohex=False时显式传入toupper的情况,也就无法针对这种错误用法抛出错误。
写法二
def read_bytes(path: pathlib.Path, tohex: bool = True, toupper: bool = None) -> bytes | hex | Any: if toupper is None: toupper = False
问题:代码相对冗长。
内容的提问来源于stack exchange,提问作者Zach Joseph
相关产品推荐
相关产品推荐

