mypy
mypy copied to clipboard
Regression for truthy bool with getattr
The following code generates an error on latest master but no on latest release (with --enable-error-codes=truthy-bool):
def f(obj: object) -> None:
print("{}".format(
getattr(type(obj), "__foo__", "") or "unknown" # E: "builtins.getattr" returns "object" which does not implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool]
))
f("")
It's clearly a false positive, if your run the code you see that it prints unknown.
Using @hauntsaninja's mypy_primer, it pointed to #14178.
$ cat test.py
# flags: --enable-error-code truthy-bool
def f(obj: object) -> None:
print("{}".format(
getattr(type(obj), "__foo__", "") or "unknown" # E: "builtins.getattr" returns "object" which does not implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool]
))
$ python3 mypy_primer.py -p test.py --bisect --debug --old v0.991
...
4471c7e76f27ee51eb8d47a4803097ec15c62128 is the first bad commit
...
This is likely the same underlying issue as #14481.
@ilevkivskyi
Here's a bit simpler example that reproduces the issue:
def f(t: type[object]) -> None:
o: object = getattr(t, "x", "") or ""
This looks different from #14481, as there are no TypedDicts involved here.