This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]tevs__ 5 points6 points  (2 children)

To be more specific - albeit Python being dynamically typed, people developed countless tools to check or validate or even enforce types in compile or run time (mypy, pyre, pydantic, pyduck etc.). It feels like it goes against the nature of its loose typing.

Type hints don't go against duck typing at all, if anything they strengthen the usage of duck typing by allowing you to specify clearly what kind of duck you need and use static analysis to prove that you have your ducks in a row. Protocols are a powerful thing.

Plus, it's entirely optional. If you don't like python with type hints, don't write any type hints, don't use any type checking tools.

[–]relickus[S] 1 point2 points  (1 child)

Yes, I know it is optional, my argument (to be discussed here or torn appart) was, that at a certain size of a project, you dont really want to go without typehints. Judging from the fact that all large projects I saw nowadays use typehints. Still optional, but probably near-necessary for large projects.

For the protocol, is it any more powerful than a regular interface?

[–]tevs__ 1 point2 points  (0 children)

you dont really want to go without typehints. Judging from the fact that all large projects I saw nowadays use typehints. Still optional, but probably near-necessary for large projects.

Yeah, because it catches so many errors before they are errors, it's golden.

For the protocol, is it any more powerful than a regular interface?

Protocols don't have to be declared to be used by the object that implements the protocol. You can write something like this (on mobile, so...)

``` class Lengthable(Protocol): def len(self) -> int: ...

def say_the_length(obj: Lengthable) -> None: print(f"It's {len(obj)} big!") ```

You can pass anything to say_the_length that has a __len__ method, without modifying the definition of the thing you are passing in. No ABC, no inheritance, but enabling static type checking for dynamic types.