python / python/mypy

Type variable across types gives an error when using Generics

Open
#11,854 7 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

Bug Report

When using a TypeVar defined in another local file, to parameterize a Generic, the following error is given:

Free type variable expected in Generic[...]

To Reproduce

Create file value.py:

from typing import TypeVar, Protocol

TValue = TypeVar('TValue', covariant=True)

# As an example, this does not give me any errors
class IValueProcessor(Protocol, Generic[TValue]):
    ...

Create service.py:

from abc import ABC
from typing import Generic

from  .value import TValue

class Service(ABC, Generic[TValue]):  # Error occurs here, on `Generic`
    ...

Expected Behavior

Should not give any errors (I think).

Actual Behavior

An error is produced, when parameterizing Generic:

Free type variable expected in Generic[...]

Your Environment

  • Mypy version used: 0.930
  • Mypy command-line flags: (none)
  • Mypy configuration options from mypy.ini (and other config files): (none was created, at least explicitly)
  • Python version used: CPython 3.8.10
  • Operating system and version: Ubuntu 20.04 LTS on WSL2

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 two-file reproduction in value.py and service.py, then run mypy 0.930 with no configuration or command-line flags to confirm the error. Trace how the imported TValue is handled when processing Generic[TValue], and add a regression test based on this example; done means the valid generic declaration no longer reports “Free type variable expected in Generic[...]”.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, 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.