如何让以下代码更加pythonic?所以我可以将if / else和2断言语句组合成一行吗?
@pytest.mark.parametrize('para', [1, -1, 0])
def test_xxxx(self, para):
def test(value):
return False if value >= 0 else True
if para >= 0:
assert test(para) is False
else:
assert test(para) is True
答案 0 :(得分:3)
明确并简单地用输入和预期输出写出3个断言(注意:我把你的函数放在测试之外并给它一个更清晰的名字)。
def my_func(value):
return False if value >= 0 else True
def test_my_func(self):
assert my_func(1) is False
assert my_func(-1) is True
assert my_func(0) is True
这是"是pythonic"因为正如PEP-8所说,"明确总是好于隐含"。当您处理测试时,编写尽可能少的功能代码比编写更少的代码更重要。
三个显式断言远不如一个古怪的参数化循环或试图使其成为一个单行的失败。
答案 1 :(得分:0)
Your test
function determines whether a value is negative or not, which can be simplified into the is_negative
function below (which is also more pythonic). Since you asked specifically for if - else
oneliner, I also added the second test function, but that is just more verbose (and less pythonic) way to rewrite the first one.
In this case the function is extremely simple, the tests have no real value, as they just do the same and assert that the results are the same, but I assume you have more complex case and the provided code is just a demonstration.
def is_negative(value):
return value < 0
@pytest.mark.parametrize("param", [1, -1, 0])
def test_is_negative(param):
assert (param < 0) == is_negative(param)
@pytest.mark.parametrize("param", [1, -1, 0])
def test_is_negative2(param):
assert is_negative(param) is True if param < 0 else is_negative(param) is False