Why does Python log a SyntaxWarning saying "assertion is always true"?2020-06-18
Take this code:
If we import its containing module, we’ll see a warning message on line 3:
This warning says that our test will pass, even though it should fail since
Indeed, if we run the function, it passes silently:
Python emits the
SyntaxWarning at import time because it can predict that the assertion will always pass.
So why is this the case?
assert is a conditional statement, like
This means it doesn’t take parentheses around its arguments.
In our code, we’ve used parentheses, which are being parsed as a tuple of two elements instead.
Our code is effectively the same as this:
Tuples are truthy (convert to
True in checks) if they contain any elements.
Our tuple contains two elements, so it’s always truthy, regardless of whether the equality check in the first element is
The solution is to follow the warning message and remove the parentheses from the original code:
Now Python sees the two elements as the arguments to
Running the code produces the expected error:
If you’re looking to improve the general quality of your Python code, running Flake8 as part of your development cycle will help.
I hope this helps you understand and fix this error,
Are your Django project's tests slow? Read Speed Up Your Django Tests now!
One summary email a week, no spam, I pinky promise.
- Why does Python log a SyntaxWarning saying "object is not callable"?
- Why does Python log a SyntaxWarning for 'is' with literals?
- Why does Python log a SyntaxWarning saying "object is not subscriptable"?
- Why does Python log a SyntaxWarning saying "list indices must be integers or slices"?
© 2020 All rights reserved.