Will recursive or mutually recursive bounds on TypeVar be supported?

Open
#1,561 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
python
Domain
devtools

Research direction

Start with the recursive TypeVar example in example.py and review the linked typing discussion at issue 59. Compare it with the pymcts/tree.py example, then determine the expected behavior for TypedCons, IntCons, and the rejected BadCons case; done means recursive or mutually recursive bounds are either supported consistently or the limitation is clearly resolved.

Written by the indexing model from the issue text.

Description

feature needs discussion priority-2-low topic-recursive-types topic-type-variables

Reading through the discussion at https://github.com/python/typing/issues/59, there was an example that had TypeVar bound that referenced itself. Is this intended to be eventually implemented? The actual PEP just has a bare Comparable.

A motivating example (from the Java world) is discussed here, in the context of their Enum. An example in Python:

from typing import Generic, Optional, Tuple, TypeVar  

# Would like to write bound='TypedCons[T, V]' here, where T is self-referential
T = TypeVar('T', bound='TypedCons')
V = TypeVar('V')  


class TypedCons(Generic[T, V]):  
    def __init__(self, value: V, cdr: Optional[T]=None) -> None:  
        self.value = value  
        self.cdr = cdr  

    def first_two(self) -> Tuple[T, T]:  
        # Fails without cast with "Incompatible return value type: expected Tuple[T`1, T`1], got Tuple[example.TypedCons[T`1, V`2], T`1]"  
        return self, self.cdr  

class IntCons(TypedCons['IntCons', int]):  
    pass

# Recursive bound would reject this
class BadCons(TypedCons['IntCons', str]):  
    pass  

If I try to write the recursive bound, I get:

example.py:3: error: Invalid type "example.T"

A similar example where this is needed is at https://github.com/smallnamespace/pymcts/blob/b5e1375e67983ef7b5baa2511c680074fd31b00c/pymcts/tree.py#L78 -- here we need to use the fact that N and Node are identical.

Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

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.

More from python/mypy

All issues in python/mypy

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.