[Python-ideas] Structural type checking for PEP 484

Brendan Barnwell brenbarn at brenbarn.net
Thu Sep 10 20:24:19 CEST 2015


On 2015-09-10 10:01, Sven R. Kunze wrote:
>
>
> On 10.09.2015 03:50, Brendan Barnwell wrote:
>> On 2015-09-09 13:17, Guido van Rossum wrote:
>>> Jukka wrote up a proposal for structural subtyping. It's pretty good.
>>> Please discuss.
>>>
>>> https://github.com/ambv/typehinting/issues/11#issuecomment-138133867
>>
>>     I'm not totally hip to all the latest typing developments,
>
> You bet what I am.
>
>> but I'm not sure I fully understand the benefit of this protocol
>> concept.  At the beginning it says that classes have to be explicitly
>> marked to support these protocols.  But why is that? Doesn't the
>> existing __subclasshook__ already allow an ABC to use any criteria it
>> likes to determine if a given class is considered a subclass?  So
>> couldn't ABCs like the ones we already have inspect the type
>> annotations and decide a class "counts" as an iterable (or whatever)
>> if it defines the right methods with the right type hints?
>>
>
> The benefit from what I understand is actually really, really nice. It's
> basically adding the ability to shorten the following 'capability' check:
>
> if hasattr(obj, 'important') and hasattr(obj, 'relevant') and
> hasattr(obj, 'necessary'):
>       # do
>
> to
>
> if implements(obj, protocol):
>       # do

	Right, but can't you already do that with ABCs, as in the example in 
the docs (https://docs.python.org/2/library/abc.html)?  You can write an 
ABC whose __subclasshook__ does whatever hasattr checks you want (and, 
if you want, checks the type annotations too), and then you can use 
isinstance/issubclass to check if a given instance/class "provides the 
protocol" described by that ABC.

-- 
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is no 
path, and leave a trail."
    --author unknown


More information about the Python-ideas mailing list