On Oct 1, 2019, at 06:23, Richard Musil <risa20...@gmail.com> wrote:
> 
> Where *virtual* is a hyperlink to an ABC definition.
> 
> `issubclass` will be fine without virtual and I am not sure why virtual has 
> been added to it

Virtual subclassing is key to the way ABCs work. It would be nice if it were 
explained better in the docs, but I suppose usually people don’t need to know 
the details unless they’re actually getting involved in something like 
designing new ABCs, so…

The general feature is that any class can define a subclass-testing dunder 
method to tell issubclass what to do, and likewise for isinstance. That’s what 
virtual subclassing means: your class’s subclass hook can say that something is 
a subclass even though it didn’t inherit from you.

This is what allows ABCs like Iterable to simulate structural subtyping. In 
Java, you can implement all the methods you want, but you won’t be usable as an 
iterable unless you also inherit from the IIterable interface. In Go, if you 
implement the right methods, you are automatically usable as an Iterable 
without inheriting anything. ObjC allows you to define both kinds of 
relationships, because sometimes one is useful, sometimes the other. 

Python gives you a general framework that lets you define both kinds of 
relationships—and more; e.g., you can handle relationships that aren’t quite 
structurally (Go-style) checkable, like Sequence, and you can fudge around 
legacy issues rather than having to get everything perfect before you can use 
new features. 

And it does it without needing any special language-level magic like Go, by 
just treating issubclass itself (and likewise isinstance) as a protocol, with a 
dunder method, like __getattr__ or anything else.

The ABC metaclass gives you some helpers to make it easier to implement virtual 
subclassing correctly and consistently, like a single simpler method you can 
override to handle both hooks at once, a registry to allow classes to 
explicitly claim they match your ABC, and a few other things. The 
collections.abc module adds an additional helper on top of that to help its 
ABCs test for methods properly (because it’s not as simple as it should be). 
But the real magic is making issubclass a protocol that’s overridable the same 
as everything else in Python. 
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/QEGAOLVXE6YJ67PD6HYNFEHPWBNPRXNC/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to