12
Protocols in Python
(til.simonwillison.net)
Welcome to the Python community on the programming.dev Lemmy instance!
Past
November 2023
October 2023
July 2023
August 2023
September 2023
Got both of those wrong. The point of protocols is to have a way to validate duck typing errors by adding a single definition of a duck. This is not something that only applies to backwards compatible, nor does it affects backwards compatibility.
You're missing the whole point of prototypes. The point of a prototype is that you want duck typing, not inheritance. Those are entirely different things, and with prototypes you only need to specify a single prototype and use it in a function definition, and it automatically validates each and any object passed to it without having to touch it's definition or add a base class.
That still doesn't explain why duck typing is ever a thing beyond "I'm too lazy to write
extends BaseClass
". There's simply no reason to want it.I already explained it to you: protocols apply to types you do not own or control, let alone can specify a base class.
You just specify a protocol, specify that a function requires it, and afterwards you can pass anything to it as-is and you'll be able to validate your calls.
and I already explained that
Union
is a thing.I'm not sure you understand that what a union does or does not do is completely irrelevant and besides the point. Python's protocols add support for structural subtyping, and enable both runtime and build-time type checks without requiring major code changes. Don't you understand what that means?