python / python/mypy

assigning a TypeVar to an identical value is reported as an error.

Open
#12,528 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

In my project, I have multiple definitions of the same TypeVar. They originated from merging (with pytype) the original modules with their generated stub files. It may be that pytype was in error, but I'll look into that later.
In this example, the TypeVar Self appears several times in the stub files. The result is:

A.py:
from B import *
Self = TypeVar('Self')

B.py:
Self = TypeVar('Self')

mypy reports the redefinition of Self in A as an error.

I expect that a type checker should consider this as a benign redefinition. It would ignore it, and replace the existing symbol table node (called B.Self) with a new node called A.Self. On any subsequent reanalysis of A, I believe that mypy would treat this as already analyzed and do nothing.

You might disagree with me about this. Does the PEP have any specification about this?

In semanal.py line 3157 is the fail message. I would say that the existing node should first be compared with the new name, values, and bound for equality. When they are equal, skip the subsequent fail message and the return of False.

Your Environment

  • Mypy version used: 0.931
  • Python version used: 3.7

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

Start with the redefinition handling in semanal.py around line 3157 and reproduce the A.py/B.py example from the issue. Check the relevant PEP or typing semantics before deciding whether identical TypeVar definitions should be accepted; done means the behavior and diagnostic match the resolved specification.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.