Nitzan
Nitzan

Reputation: 1805

How to define a custom generic type so pycharm would enforce it well

In my project, we've adopted a return-value pattern, very similar to what you see in go.
Where we utilize being able to return multiple values to also convey expected errors, like so:

def test_model(model):

    if something_wrong(model):
        return None, "somethings wrong"

    if something_else_wrong(model):
        return None, "somethings else wrong"

    return TestResult(), None

This works fine, but we're encountering some problems with pycharm's typing comprehension when I try and add type hinting.

What's required is this:

def test_model(model) -> Union[Tuple[TestResult, None], Tuple[None, str]]

Which pycharm comprehends well:

pycharm good typing comprehension

So I was set to write a utility type to avoid writing long union typings since we're only interested in the types of the possible left or right outcomes.

And according to the documentation on user defined generic types for the python typing library, I came up with this:

EitherA = TypeVar("EitherA")
EitherB = TypeVar("EitherB")

Either = Union[Tuple[EitherA, None], Tuple[None, EitherB]]

But sadly, pycharm doesn't manage around this complexity:

pycharm bad typing comprehension

Am I constructing the Either type correctly?
Is there a way to have pycharm recognize it well, or write it differently so it will?

Upvotes: 3

Views: 629

Answers (1)

user2235698
user2235698

Reputation: 7639

Known bug, please vote for https://youtrack.jetbrains.com/issue/PY-29564 (thumbs up near the title)

Upvotes: 1

Related Questions