python / python/mypy

Unions with generic parameter reduces parameter too far

Open
#9,898 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-join-v-union
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When creating a method that takes a union of a type with a generic parameter it seems like the generic parameter is reduced to object instead of its original value.

To Reproduce

import typing as t

T = t.TypeVar('T', covariant=True)
Y = t.TypeVar('Y')


class Nothing(t.Generic[T]):
    def chain_none(self: 'Nothing[t.Optional[Y]]') -> 'Nothing[Y]':
        return self  # type: ignore


class Just(t.Generic[T]):
    def __init__(self, val: T) -> None:
        self._value = val

    def chain_none(
            self: 'Just[t.Optional[Y]]') -> t.Union[Nothing[Y], 'Just[Y]']:
        if self._value is None:
            return Nothing()
        return Just(self._value)


val: t.Union[Nothing[t.Union[None, int, str]], Just[t.Union[None, int, str]]]
reveal_type(val.chain_none())

This reveals 'Union[mypy_test.Nothing[builtins.object], mypy_test.Just[builtins.object]]' while I would expect 'Union[mypy_test.Nothing[Union[int, str]], mypy_test.Just[Union[int, str]]].

Please note that the example does work correctly when using Union[None, int] for val.

Your Environment

  • Mypy version used: 0.790
  • Python version used: 3.8.5

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Run the supplied Python 3.8.5 reproduction with mypy 0.790 and compare the reveal_type output with the expected union. Trace the generic-parameter reduction for the union case, then add coverage showing that the result preserves Union[int, str] rather than reducing it to object.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.