Pylint lazy loading a callable with a property causes an exception. How can I make this work?

Viewed 16

I'm trying to lazily construct a callable with pylint, but this seems to create an error.

I tried to produce a minimal repro.

"Module."

from typing import Callable


def callable_():
    return lambda x: x


class GPT3Statistics:
    def __init__(self):
        self._cached = None

    @property
    def f(self) -> Callable[[str], object]:
        self._cached = self._cached or callable_()
        return self._cached

    @property
    def g(self) -> Callable[[str], object]:
        self._cached = self._cached or callable_()
        # return self._cached
        return callable_()

    def complete(self):
        len(self.f("hello")) # <- this creates a warning but I don't think it should
        len(self.g("hello"))

Why is this producing a warning (preferrably while still type checking).

Interestingly I don't get the error if I don't use a property... so perhaps @property is destroying type information.

"Module."

from typing import Callable


def callable_() -> Callable[str]:
    return lambda x: x


class GPT3Statistics:
    def __init__(self):
        self._cached = None

    def f(self) -> Callable[[str], object]:
        self._cached = self._cached or callable_()
        return self._cached

    def g(self) -> Callable[[str], object]:
        self._cached = self._cached or callable_()
        # return self._cached
        return callable_()

    def h(self) -> Callable[[str], object]:
        self._cached = self._cached or callable_()
        # return self._cached
        return None

    def complete(self):
        len(self.f()("hello")) 
        len(self.g()("hello")) # now works
        len(self.h()("hello")) # errors out

So I guess one work around is to use a function rather than a property. But it might be nice to still use a property.

I think I'm using the latest version of pylint.

pylint --version
pylint 2.15.2
astroid 2.12.9
Python 3.10.6 (main, Aug 11 2022, 13:49:01) [Clang 13.0.0 (clang-1300.0.29.30)]

0 Answers
Related