How can I add type hints to my monkey-patched function to an existing module's class?

2.5k Views Asked by At

I want to know how I can add type hints (for PyCharm IDE code completion support) to a method def links(self) -> List[str] that I monkey-patched to an existing module's class:

My function

def issue_links(self) -> List[str]:
    links = []
    # ...
    return links

Monkey-patching the function to the Issue class of python-jira

from jira.resources import Issue

# {...} my defined function code is somewhere here

Issue.links = issue_links

Now I have the problem that PyCharm obviously not recognise this method when I call it on an Issue object. I tried to follow PEP 484 Stub Files and using the typing module in a .pyi file to get the IDE to find the definition of my monkey-patched function.

Issue.pyi

from typing import List

class Issue:
    def links(self) -> List[str]: ...

However, it won't work. My assumption is that the file structure is somehow not correct:

File Locations

jira-python module >> site packages (downloaded with pip install jira)

myFile.py >> /temp/myFile.py

Issue.pyi >> /temp/jira/resources/Issue.pyi folder

1

There are 1 best solutions below

0
JonnyOhneha On

Maybe using a stub-file is not the best approach for what you want to achieve - since in this case you would have to replicate the full interface of Issue in the stub, as already discussed in the comments.

Why not use inheritance for this purpose?

from jira.resources import Issue as JiraIssue
from typing import List

class Issue(JiraIssue):
    def links(self) -> List[str]:
        # your function code here

Or if you really only want to define the interface:

from jira.resources import Issue as JiraIssue
from typing import List, Protocol

class WithLinks():
    def links(self) -> List[str]: ...

class Issue(JiraIssue, WithLinks):
    pass