Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> I typically show candidates a snippet that uses typing.Protocol as part of a broader technical discussion, and I can’t recall any candidates having seen that specific construct before

I think the `typing.Protocol` [1] (aka "structural subtyping" or "static duck typing") does not get enough spotlight! This is one of the keys to migrate a very pythonic codebase to type hints, and allows to avoid infinite type hints shenanigans all over the place. Of course, MyPy supports this feature natively [2].

[1] https://docs.python.org/3/library/typing.html [2] https://mypy.readthedocs.io/en/stable/protocols.html



I had looked into protocols the other day but found no advantages over ABCs. In fact, failing to implement an ABC's interface is a 'compile-time' error, which is impossible to miss. Using protocols and mypy would be a soft-fail in comparison, where code runs but can fall flat at runtime still, if mypy is simply ignored/forgotten (it's optional).

I guess implementing multiple protocols (interfaces in other languages like C#) is possible and more awkward using ABCs?


There's some info in the PEP for protocols about their advantages versus other approaches:

https://peps.python.org/pep-0544/#rationale-and-goals

https://peps.python.org/pep-0544/#existing-approaches-to-str...

As to mypy being optional, it's easy enough to make it required via git hooks and/or CI. If your process doesn't make this easy for mypy or any other tool (e.g. formatting), I'd wager there are more fundamental issues.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: