facebook / pyre-check

Performant type-checking for python.

Home Page:https://pyre-check.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Pyre doesn't seem to understand universal quantification

vthemelis opened this issue · comments

Pyre Bug

Bug description
I'm trying to type a lambda-based encoding of cons from Lisp:

from typing import Callable, TypeVar

T = TypeVar('T')
U = TypeVar('U')
V = TypeVar('V')

def cons(a: T, b: U) -> Callable[[Callable[[T, U], V]], V]:
    return lambda f : f(a, b)

This fails with:

Invalid type variable [34]: The type variable `Variable[V]` isn't present in the function's parameters.

mypy seems to have no issue type-checking this

Reproduction steps
Run pyre with the snippet above

Expected behavior
The above should type-check.

Hi! As far as I know, TypeVars must be present in the function's parameters. To work around this, you could use a similar strategy as decorator factories from our documentation for this error. I did it here

@kinto0 thank you ver much! Indeed, I should have seen this earlier.

With some modification, it looks like I can type check car and cdr as well:

Pyre playground here

Something that may be of interest is that I need to write car like:

def car(cons: MyCallableProtocol[T, U]) -> T:
    cont: Callable[[T, U], T] = lambda x, _: x
    return cons(cont)

rather than

def car(cons: MyCallableProtocol[T, U]) -> T:
    return cons(lambda x, _: x)

to get full type safety. Without this change, changing the return type of car from T to something else doesn't elicit a type error.

In other words, it doesn't seem like pyre can infer the type of the lambda correctly.

Thanks a lot for the help!