How to fix the `Argument missing for parameter - Pylance reportCallIssue` issue for Python decorator of method?

227 Views Asked by At

I have a decorator which works at run time, but the Pylance report Argument missing for parameter - Pylance "arg" reportCallIssue, how can I fix it?

environment

  • Python 3.10
  • Pylance at VSCode

the code

import functools
from typing import Any, Callable


def decorator(func: Callable[[Any, str], str]):
    """Intention:

    a decorator for a method which takes one string argument after the self and returns a string
    """

    @functools.wraps(func)
    def display_and_return_the_result(self, arg: str) -> str:
        result = func(self, arg)
        print(result)
        return result

    return display_and_return_the_result


class MyClass:
    @decorator
    def method(self, name: str) -> str:
        return f"Hello {name}!"

run

run with no error

-> Hello world!

Screenshot

enter image description here

I want to change some code and report no error, but do not know what to do?

More

I have applied the fix from @STerliakov's comments, and the code becomes

import functools
from typing import Callable, TypeVar

_S = TypeVar("_S", bound="MyClass")


def decorator(func: Callable[[_S, str], str]) -> Callable[[_S, str], str]:
    @functools.wraps(func)
    def display_and_return_the_result(self: _S, arg: str) -> str:
        result = func(self, arg)
        print(result)
        return result

    return display_and_return_the_result


class MyClass:
    @decorator
    def method(self, name: str) -> str:
        return f"Hello {name}!"


c = MyClass()
c.method("world")

This code can pass Pylance check, however, there are still errors if I use a keyword argument

enter image description here

is that possible to support both positional and keyword argument?

0

There are 0 best solutions below