Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

python - Using `and` instead of `,` when starting multiple context managers in `with` statement

When writing unit tests, I was often using following pattern:

with self.subTest("Invalid input") and self.assertRaises(ValueError):
  ...

But only today I learned that according to python specs, I should be using , here:

with self.subTest("Invalid input"), self.assertRaises(ValueError):
  ...

And the specifications don't mention and as an option. Yet the tests always seemed to be working fine.

What are the possible problems when using and here? Why does it seem to usually work the same way as ,?

Related: Multiple variables in a 'with' statement?

question from:https://stackoverflow.com/questions/66060365/using-and-instead-of-when-starting-multiple-context-managers-in-with-sta

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you have is an expression with the and operator. The and operator returns its first operand if it is falsey, or its second operand otherwise. Assuming self.subTest(...) returns something truthy, your code is equivalent to:

ctx = self.subTest("Invalid input") and self.assertRaises(ValueError)
with ctx: ...

Which is equivalent to:

self.subTest("Invalid input")
ctx = self.assertRaises(ValueError)
with ctx: ...

Or:

self.subTest("Invalid input")
with self.assertRaises(ValueError): ...

So, at best, what you have may be misleading. At worst it's a bug, since subTest's context manager isn't being used.

If self.subTest returns a falsey value, then self.assertRaises(...) is never executed, which would be a clear bug in your test.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...