Stewori / pytypes

Typing-toolbox for Python 3 _and_ 2.7 w.r.t. PEP 484.
Apache License 2.0
200 stars 20 forks source link

Gradual typing with Any? #61

Open udim opened 5 years ago

udim commented 5 years ago

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

Stewori commented 5 years ago

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.

udim commented 5 years ago

? 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.

Stewori commented 5 years ago

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...

udim commented 5 years ago

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)

Stewori commented 5 years ago

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.