Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial stub in PyCharm

I would like to introduce partial type annotation to my project. For example for overloading. I found that pep561 introduce partial stub file support.

I develop my project with PyCharm and I add corresponding *.pyi file. And got expected information, but PyCharm reports that cannot find reference in pyi file.

It is possible to force PyCharm to look to orginal py file when there is no entry in pyi file? Or maybe it is also doable with partial entry for class?

I create sample project to show problem (orginal is to big): cannot find reference 'CC' in '__init__.pyi'

├── main.py
└── pep561_test
    ├── __init__.py
    └── __init__.pyi

main.py

from pep561_test import AA, BB, CC

AA().test1(1)
AA().test1(True)
AA().test1('a')
AA().test2(1)

BB().test1(1)
BB().test2(1)

__init__.py

class AA:
    def test1(self, a):
        pass

    def test2(self, a):
        pass


class BB:
    def test1(self, a):
        pass

    def test2(self, a):
        pass


class CC:
    def test1(self, a):
        pass

    def test2(self, a):
        pass

__init__.pyi

class AA:
    def test1(self, a: int) -> int: ...

    def test1(self, a: bool) -> str: ...

    def test2(self, a):
        pass


class BB:
    def test1(self, a):
        pass
like image 980
Grzegorz Bokota Avatar asked Mar 14 '19 11:03

Grzegorz Bokota


1 Answers

Indicating to look in the .py for missing top-level reference (CC)

According to PEP 484, this is possible, simply add the following line at the top-level of your .pyi (I checked that it works with PyCharm 11.0.7, EDIT: does not work in PyCharm 2020.3):

def __getattr__(name) -> Any: ...

Indicating to look in the .py for missing attribute/method (BB)

Other libraries (at least typeshed) allow a similar syntax to merge an incomplete class stub with the class definition in the .py

class Foo:
    def __getattr__(self, name: str) -> Any: ...  # incomplete
    x: int
    y: str

However this does not seem to be part of PEP 484, and is not implemented in PyCharm (as of 11.0.7) as far as I know. I just created a request for this feature: I stumbled on this stackoverflow question while looking for a way to merge my incomplete class stub with the class definition and concluded that it is not feasible yet.

like image 75
ernesttg Avatar answered Nov 11 '22 04:11

ernesttg