microsoft / pyright

Static Type Checker for Python

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Consider functions decorated by another variable's decorator not unused

InSyncWithFoo opened this issue · comments

Minimal reproducible example (playground):

(from this Stack Overflow question)

from collections.abc import Callable

class App:
    def register(self, f: Callable[..., object]) -> None: ...

def c() -> App:
    app = App()

    @app.register
    def index() -> None:
#       ~~~~~ Function "index" is not accessed (reportUnusedFunction)
        ...
    
    return app

The decorator used in this case is not pure, and it would be nice if Pyright could detect that.

Pyright is working as intended here.

When you apply a decorator to a function, it is effectively writing the result of the decorator back to the symbol.

In other words, your code is doing the equivalent of the following:

def c() -> App:
    app = App()
    def _index() -> None:
        ...
     index = app.register(_index)
    return app

The symbol index is not accessed here, so pyright is correct to flag it as unused.

If your intent is to simply register a function, you should do this:

def c() -> App:
    app = App()
    def index() -> None:
        ...
     app.register(index)
    return app