[Python-ideas] Optional static typing -- the crossroads

Andrew Barnert abarnert at yahoo.com
Mon Aug 18 03:12:58 CEST 2014


> On Sunday, August 17, 2014 5:04 PM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:

> > Andrew Barnert wrote:
>>  The obvious way that already works (with MyPy, and also with ABCs for 
> isinstance checking):
>> 
>>      class HashableIterable(Iterable, Hashable): pass
>> 
>>      def spam(a: HashableIterable):
>>          pass
> 
> That way might be obvious, but it's wrong. It says that spam()
> only takes an instance of the specific class HashableIterable
> or a subclass thereof. It won't accept anything else, even if
> it implements Iterable and Hashable perfectly well.

typing.Iterable and typing.Hashable are both typing.Protocols, so HashableIterable is also a typing.Protocol, so, if I understand Protocol correctly, isinstance will return True iff every method and attribute in HashableIterable (that is, every method and attribute in Iterable, plus every method and attribute in Hashable) is implemented by the type. Which is what we want here, right?

That obviously doesn't work for nominal rather than structural ABCs, or for ad-hoc structural ABCs like the ones in collections.abc that don't automatically compose, but isn't that the whole point of Protocol, to provide structural subtyping that follows the rules of structural rather than nominative subtyping?

> 
>> 
>>  But, there's no reason typing.py couldn't add a wrapper that does 
> this automatically:
>> 
>>      class Multiple:
>>          @staticmethod
>>          def __getitem__(*types);
>>              return type(types[0])(
>>                  '_'.join(t.__name__ for t in types), types, 
> {})
> 
> Automating it won't make it any more right. There needs to
> be a distinct concept such as Intersection() as a counterpart
> to Union().
> 
> 
> -- 
> Greg
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
> 


More information about the Python-ideas mailing list