basedpyright icon indicating copy to clipboard operation
basedpyright copied to clipboard

Custom behavior on decorated functions

Open vikigenius opened this issue 10 months ago • 2 comments

Description

I have a custom decorator that uses the docstring of a function as a template

@prompt
def prompt_args_test(name: str, age: int):
    """Hello, I am {{ name }} and I am {{ age }} years old."""

Obviously pyright complains about unused args. Is there some specific way such as a plugin or something that I can use to disable this check only for functions decorated with this decorator?

vikigenius avatar Apr 20 '25 00:04 vikigenius

i would like to have some sort of functionality to tell the type checker that a decorator does something to the function signature that it should know about. some cases i've come across include:

  • the decorator calls the function or "registers" it somewhere to be called later (ie. prevents reportUnusedFunction from being reported)
  • the decorator evaluates type annotations (ie. treats the function as if from __future__ import annotations is not present, even if it is)
  • the decorator uses the function parameters (your example)

though i think your example is a bit strange. why not just rewrite the decorator such that the function returns an f-string? doing this would probably make the implementation of that decorator much simpler and more typesafe. (assuming you control the decorator and it isn't from some 3rd party module)

@prompt
def prompt_args_test(name: str, age: int):
    return f"Hello, I am {name} and I am {age} years old."

i think a better example is pytest hookspec functions

DetachHead avatar Apr 20 '25 01:04 DetachHead

I am using Jinja templating rather than f strings so I went for this approach. I could still use a return I guess rather than use a doctoring. But you captured the general idea

vikigenius avatar Apr 20 '25 22:04 vikigenius