Incorrect reportAssertAlwaysTrue when asserting Tuple[T] not empty
Describe the bug
When asserting a Tuple[T] variable as truthy (i.e., nonempty), PyRight reports the assertion always holds. However, a tuple of this type can be the empty tuple and evaluate as false.
This was hit when asserting that at least one value was provided to a varargs function.
To Reproduce
def g():
x: Tuple[Any] = tuple()
assert x # Produces: Assert expression always evaluates to true (reportAssertAlwaysTrue)
g() # raises AssertionError
Expected behavior This should not report the assert always holds.
The report can be suppressed with an explicit cast to bool, which changes the type of the assert expression away from Tuple.
Screenshots or Code Actual use-case was more like:
def f(*args: int):
assert args # Produces: Assert expression always evaluates to true (reportAssertAlwaysTrue)
...
f() # raises AssertionError
VS Code extension or command-line
Running from CLI. Version: pyright 1.1.48.
Additional context
I think this occurs because of the logic to detect erroneous multi-line asserts that are actually tuples. The check might need to be scoped down to trigger on specifically an expression of known tuple size two, though I am not sure if this would be fragile.
I think there are a couple of bugs here, but it's not the one you reported.
The type annotation Tuple[Any] indicates that there is a tuple with a single element that is of type Any. This will always evaluate to truthy. If you want to indicate a tuple that is truly empty (zero elements), you would need to use the annotation Tuple[()]. And if you want to indicate that the tuple is of indeterminate length, you would need to use the annotation Tuple[Any, ...].
As I said above, there are a couple of bugs:
- If you change your annotation to
Tuple[()], Pyright indicates thattuple()cannot be assigned to it. - If you change your annotation to
Tuple[Any, ...], Pyright still insists that the assert is unnecessary, when it's possible for the value to be truthy or falsy depending on the number of elements.
Digging into this a bit more, I think that bug #1 isn't actually a bug. It's a side effect of the way the __new__ method for the tuple class is defined in the builtins.pyi stub file.
#2 is definitely a bug, and I've introduced a fix. It will be included in the next version of Pyright.
This is addressed in Pyright 1.1.49, which I just published.