对 Python 来说是新手,但我试图理解这段代码:
with pytest.raises(ValueError):
group_adjust(vals, [grps_1, grps_2], weights)
看完之后本教程与 http://effbot.org/zone/python-with-statement.htm, 我明白pytest.raises()
返回一个上下文管理器,用于设置和清理之前和之后的内容group_adjust()
叫做。我也明白group_adjust()
应该提出一个ValueError
如果出现问题。
当出现 ValueError 时 pytest 如何“反应”? AFAIK,只有设置和清理,所以我不确定它如何捕获异常。最终目标是了解使用 pytest 作为上下文管理器的好处。
__exit__ https://docs.python.org/3/reference/datamodel.html#object.__exit__魔术函数接受exception_type
, exception_value
and traceback
参数:
In [5]: class RaisesContext:
...: def __enter__(self):
...: return self
...: def __exit__(self, exception_type, exception_value, traceback):
...: print('Exception type:', exception_type)
...: print('Exception value:', exception_value)
...: print('Traceback:', traceback)
...: return True
...:
In [6]: with RaisesContext():
...: raise ValueError('Something went wrong')
...:
Exception type: <class 'ValueError'>
Exception value: Something went wrong
Traceback: <traceback object at 0x7fd92f4a2c48>
他们是None
,如果with
块正常结束:
In [7]: with RaisesContext():
...: pass
...:
Exception type: None
Exception value: None
Traceback: None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)