python / python/mypy

'TypeVar's `bound` parameter does not play nice with overloads(?)

Open
#10,691 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-overloads topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report
'TypeVar's bound parameter does not play nice with overloads(?)

To Reproduce

from typing import Union, TypeVar, overload

class C1:...
class C2:...

T = TypeVar('T', bound=Union[C1, C2])

@overload
def update(elt: C1) -> C1:...

@overload
def update(elt:C2) -> C2:...

def update(elt: Union[C1, C2]) -> Union[C1, C2]:
  pass

def get_copy(elt: T) -> T:
  new_elt = update(elt)
  return new_elt

Expected Behavior

This should type-check(?)

Actual Behavior

I get errors:

type_tests.py:47: error: Argument 1 to "update" has incompatible type "T"; expected "B1"
type_tests.py:48: error: Incompatible return value type (got "D1", expected "T")    

If I replace T = TypeVar('T', bound=Union[C1, C2]) with T = TypeVar('T', C1, C2, Union[C1, C2]), it
passes just fine

Your Environment

  • Mypy version used: mypy 0.812
  • Mypy command-line flags: None: command was mypy type_tests.py
  • Mypy configuration options from mypy.ini (and other config files): default
  • Python version used: 3.7.8
  • Operating system and version: Ubuntu 16.04

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

Reproduce the reported errors by running mypy type_tests.py with the TypeVar bound and overload definitions shown in the issue, then compare them with the constrained-TypeVar variant. Trace how mypy handles the bound during overload resolution and return-type checking; done means determining the intended behavior and adding a regression test or documenting why the bound is rejected.

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.