News for hackers. Stuff that matters.
Re:Python’s “type hints” are a bit of a disappointment to me by Znafon on Thursday April 21, 2022 @05:37PM (#31115494)
Python typing supports duck typing: https://peps.python.org/pep-0544/

and heterogeneously typed ducts: https://peps.python.org/pep-0589/

Re:Python’s “type hints” are a bit of a disappointment to me by zmgsabst on Thursday April 21, 2022 @05:48PM (#31115598)
I read 0544 and the proposal for protocols fails to support the main benefit of duck typing, as it requires the substituted-for class to be defined as a protocol.

Traditionally, duck typing is used to inject types into a library that isn’t expecting extension at that particular point — eg, substituting a test class for a real class in a data object that normally wouldn’t be a protocol.

I’m not seeing how that PEP addresses that use case.

- - - -

Similarly, the heading on the dictionary says “for a fixed set of keys” — but what if I want a dynamic heterodox dict? Eg, unpacking JSON.

You just end up shoving “any” all over the place. At which point, are the types helping?

Though, protocols do help the dict case for typing:

dict : Hashable -> Any

Re:Python’s “type hints” are a bit of a disappointment to me by ljojiasdf on Thursday April 21, 2022 @06:20PM (#31115883)
Can you re-read please?

https://peps.python.org/pep-0544/#:~:text=Structural%20subty....

> substituted-for class to be defined as a protocol.

... which is false

> Similarly, the heading on the dictionary says “for a fixed set of keys” — but what if I want a dynamic heterodox dict? Eg, unpacking JSON.

You can quite obviously decode to recursive types (e.g. using pydantic), not sure what the problem is.

Re:Python’s “type hints” are a bit of a disappointment to me by zmgsabst on Thursday April 21, 2022 @06:32PM (#31115992)
Your link appears not to work (for me) — can you cite what you believe I have incorrect?

This section seems to agree with me, where it explains why normal classes can’t be subclassed to protocols:

> Now, C is a subtype of Proto, and Proto is a subtype of Base. But C cannot be a subtype of Base (since the latter is not a protocol). This situation would be really weird. In addition, there is an ambiguity about whether attributes of Base should become protocol members of Proto.

https://peps.python.org/pep-0544/#protocols-subclassing-norm...

- - - -

I’m not sure why you think it’s “obvious” that you can use a third party library to solve the problem — or why that addresses my complaint that the built-in type system doesn’t work for that.

If anything, the existence of a third party library hints the standard library doesn’t cover the use case.

Re:Python’s “type hints” are a bit of a disappointment to me by Spivak on Thursday April 21, 2022 @05:41PM (#31115533)
And you can make it work at runtime too! So as long as you have the right methods and attrs isinstance on your duck-typed object will return true!