Pycharm: Decorated function with default parameter alerted as unfilled

72 Views Asked by At

Pycharm Version: 2023.1.5 (up to date at time of writing)

I'm building a decorator for an async function, which should retry to execute the decorated function when an error is detected.

The code itself appears to work fine, but Pycharm still suggests the parameter with a default value is 'unfilled'.

In my experience, Pycharm is right more often than I am, thus I'm wondering what's triggering the problem here.

from typing import Callable, ParamSpec, TypeVar
import functools
import asyncio


def retry_execute(retries: int = 2, sleep_time: float = 2):
    """
    Retry decorator.
    :param retries: max number of retries
    :param sleep_time: time between retries
    """
    P = ParamSpec("P")
    T = TypeVar("T")

    def decorator(coroutine: Callable[P, T]) -> Callable[P, T]:
        @functools.wraps(coroutine)
        async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
            for attempt in range(retries):
                try:
                    return await coroutine(*args, **kwargs)
                except Exception as e:
                    if attempt == retries - 1:
                        raise e
                    else:
                        await asyncio.sleep(sleep_time)
                        continue
        return wrapper
    return decorator


@retry_execute()
async def my_fn(n: int, b='hi'):
    await asyncio.sleep(1)  # Simulate work
    print(b)
    print(n)
    raise ValueError  # generic error to trigger

async def main():
    await asyncio.gather(my_fn(n=1), my_fn(n=2, b='bye'))

asyncio.run(main())

Output:

hi
1
bye
2
hi
1
bye
2
> ValueError

Which would suggest that at least at execution this isn't an issue.

More explicitly defining my_fn(), e.g. my_fn(..., b: Optional[str] = 'hi'), does not fix the issue.

Are there any edge cases in which my code would not properly pass the default parameter? Or, how should I update my code to ensure PyCharm properly detects default paramaters of the decorated function?

Edit: I noticed one more place within Pycharm where these default parameters were 'lost', namely viewing the function parameters with <ctrl+P>. If it would recognise the default parameter here the issue would likely be resolved. Interestingly it does detect the default string indirectly, as Pycharm recognises b should be of type string.

0

There are 0 best solutions below