pytypes icon indicating copy to clipboard operation
pytypes copied to clipboard

Gradual typing with Any?

Open udim opened this issue 6 years ago • 5 comments

Using pytypes-1.0b5 I get:

$ python
Python 3.6.5 (default, Mar 31 2018, 05:34:57) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pytypes
>>> import typing
>>> T = typing.TypeVar('T')
>>> pytypes.is_subtype(T, typing.Any)
True
>>> pytypes.is_subtype(typing.Any, T)
False

Does pytypes support gradual typing? Is there a way to do verify an is-consistent-with relationship with its API?

Background: I'm trying to replace this method with a call to pytypes.is_subtype (using Python typing types): https://github.com/apache/beam/blob/a843a08439eddcf10f140767761f8e8c1f88d715/sdks/python/apache_beam/typehints/typehints.py#L1112-L1120

udim avatar May 11 '19 01:05 udim

Regarding this article http://wphomes.soic.indiana.edu/jsiek/what-is-gradual-typing/, what would ? be? Any or T? I'm not sure I ever considered unbound type variables as an explicitly valid use case for is_subtype. I think I handled them to allow checking of partly bound types. That said, if is_consistent_with only differs from is_subtype by additional rules for Any that feature would be trivial to add and I'd happily do. (Implementing a proper is_subtype is the highly non-trivial thing here.) As you observed, for is_subtype Any is never a subtype except of itself.

Stewori avatar May 11 '19 08:05 Stewori

? in the article you mentioned would be Any in my example.

I believe that the only difference between the is_consistent_with and is_subtype relationships is that is_consistent_with has that special rule for Any that always returns true regardless if it's on the LHS or RHS.

udim avatar May 13 '19 17:05 udim

If you like, write a PR for this. It shouldn't be too difficult, would safe me some work and you would be appropriately credited in the project history. Otherwise I'll see when I can add this...

Stewori avatar May 13 '19 18:05 Stewori

I can write the PR, no problem. I've already hacked my local copy of pytypes and it seems to work.

However, I am still investigating typing module types in Python 3.x to see if they can be used in our project. (Today's wrinkle is pickling, which seems to be broken for 3.5 and 3.6. https://github.com/python/typing/issues/511)

udim avatar May 14 '19 01:05 udim

Regarding pickling, maybe a solution by pytypes on this front is type_str. It creates a string representation of a type such that the type can be trivially reconstructed using eval. There are some pitfalls though: Imports must be sufficient and of course using eval requires a trusted source. Also, it might not support every type yet.

Stewori avatar May 23 '19 14:05 Stewori