[Python-ideas] Structural type checking for PEP 484
Sven R. Kunze
srkunze at mail.de
Thu Sep 10 19:01:34 CEST 2015
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
As usual with type hints, functionality is not guaranteed. But it
simplifies sanity checks OR decision making:
if implements(obj, protocol1):
# do this
elif implements(obj, (protocol2, protocol3)):
# do that
The ability to extract all protocols of a type would provide a more
flexible way of decision making and processing such as:
if my_protocol in obj.__protocols__:
# iterate over the protocols and do something
@Jukka
I haven't found the abilities described above. Would it make sense to
add it (except it's already there)?
Best,
Sven
More information about the Python-ideas
mailing list