Skip to content

No error in function definition that returns unbound T #13061

Closed

Description

@denballakh
from typing import TypeVar

T = TypeVar('T')

def f() -> T: # no error
    ...

if f():
    print() # Statement is unreachable
else:
    print() # Statement is unreachable

Actual Behavior
No error in f definition. Two unreachable errors inside if f(): ... else: ...

Expected Behavior
Error in f definition. For example:

Type variable "T" is unbound
(Hint: Use "T" in function arguments to bind "T" to return type)

No errors inside if f(): ... else: ...

My Environment

  • mypy 0.961 (compiled: no)
  • no command-line flags, no config file
  • CPython 3.10.4
  • Windows 10

Activity

  1. JukkaL commented on Jul 16, 2022

    @JukkaL
    Collaborator

    Hints:

    • We'd only reject a plain type variable as a return type, but not things like list[T] where the type variable is a component of some other type. Returning list[T], for example, could be reasonable.
    • If a return type is an instance of TypeVarType but the return type is not present as a component in function argument types, generate an error.
    • You can use a TypeTraverserVisitor to traverse the argument types, and override visit_type_var to collect all the references to type variables within a type. See CollectAllInstancesQuery for an example of doing a similar thing.
  2. odesenfans commented on Jul 16, 2022

    @odesenfans

    Could you elaborate on why and when types like list[T] could be acceptable if Tis not bound to any type?

  3. JukkaL commented on Jul 16, 2022

    @JukkaL
    Collaborator

    @odesenfans The only example that I can think of is creating an empty container. For example, something like this:

    def make_bucket() -> Bucket[T]: ...
    
    b: Bucket[int]  = make_bucket()  # similar to x: list[int] = list()
    b.add(1)

    Usually you would just call the type object, but having a factory function seems like a plausible use case (e.g. we could do some extra things like logging or collect statistics in the factory function).

  4. added a commit that references this issue on Jul 19, 2022
  5. ilevkivskyi commented on Sep 25, 2022

    @ilevkivskyi
    Member

    I think this was already fixed by #13166, but accidentally was not closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions