Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[truthy-function] does not work with @cache #17013

Open
socketpair opened this issue Mar 11, 2024 · 5 comments
Open

[truthy-function] does not work with @cache #17013

socketpair opened this issue Mar 11, 2024 · 5 comments
Labels

Comments

@socketpair
Copy link

socketpair commented Mar 11, 2024

from functools import cache

def fun1():
    pass

if fun1:  # bug here is caught, nice!
    print(42)

@cache
def fun2():
    pass

if fun2:  # Fails to find a bug!
    print(42)

All messages:

main.py:6: error: Function "fun1" could always be true in boolean context  [truthy-function]
Found 1 error in 1 file (checked 1 source file)
@socketpair socketpair added the bug mypy got something wrong label Mar 11, 2024
@JelleZijlstra
Copy link
Member

This is closely related to python/typeshed#11280 but could perhaps be fixed in mypy independently. If you add a reveal_type(fun2) it says Revealed type is "functools._lru_cache_wrapper[Any]"; mypy could be enhanced to warn on boolean use of that type.

@JelleZijlstra JelleZijlstra added feature and removed bug mypy got something wrong labels Mar 11, 2024
@socketpair
Copy link
Author

socketpair commented Mar 11, 2024

@JelleZijlstra possibly consider any callable? Yes, incorrect in general, but correct in practice.

Or, better, maybe check anything that does not have explicit __bool__, not None, not a string, number or standard container? Possibly with some exceptions for common cases like regexp match (does it have __bool__ ?)

I think, any case of usage of an object in a condition without defined conversion to bool is a bug.

@JelleZijlstra
Copy link
Member

Yes, a generalization could make sense. I implemented something like that in pyanalyze and it's been useful, but it's not a simple change to make.

@hauntsaninja
Copy link
Collaborator

I think mypy already supports that, just is disabled by default: https://mypy.readthedocs.io/en/stable/error_code_list2.html#check-that-expression-is-not-implicitly-true-in-boolean-context-truthy-bool

@socketpair
Copy link
Author

image

Seems no such option here...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants