我有一些计算功能,用于驱动硬件设置的软件配置.在某些情况下,用户可能输入无效的配置值.我通过在使用无效值时抛出异常来处理此问题,或者只是在配置有效时返回我的计算值:
def calc_exhale_dur(breath_rate, inh_dur, breath_hold_dur):
"""Calculate exhalation duration.
Args:
breath_rate (float): animal breath rate (br/min)
inh_dur (float): animal inhalation duration (ms)
breath_hold_duration (float): animal breath hold duration (ms)
"""
single_breath_dur = calc_breath_dur(breath_rate)
exhale_dur = single_breath_dur - (inh_dur + breath_hold_dur)
if (inh_dur + breath_hold_dur + exhale_dur) > single_breath_dur:
raise error.ConfigurationError
elif exhale_dur <= 0:
raise error.ConfigurationError
else:
return exhale_dur
Run Code Online (Sandbox Code Playgroud)
以这种方式这样做被认为是不好的做法吗?如果有一个返回值,我是否总是需要一些有效的返回值?我正在努力学习如何最好地编写Pythonic代码,同时仍然满足我的计算方法的需要.
引发异常的目的是在无法找到有效返回值的情况下提供备用退出点.您正在使用与其预期完全相同的异常.
但是,我可能会先检查是否exhale_dir为非正数,这样可以避免执行带有无效值的计算.
if exhale_dur <= 0:
raise error.ConfigurationError
elif (inh_dur + breath_hold_dur + exhale_dur) > single_breath_dur):
raise error.ConfigurationError
# You can also omit the else, since the only way to reach this point
# is to *not* have raised an exception. This is a matter of style, though.
return exhale_dur
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
68 次 |
| 最近记录: |