On Thu, Apr 22, 2021 at 5:03 PM Ryan Gonzalez <rymg19@gmail.com> wrote:
On Apr 21, 2021, 5:29 PM -0500, Paul Bryan <pbryan@anode.ca>, wrote:
As demonstrated, protocols don't get us there because duck typing isn't a matter of having an object exhibit all of the attributes of a duck, but rather some subset of attributes to be used by the consumer. I want this duck to quack; someone else will want it to waddle. I don't see how type hints could reasonably support "file like object" in the duck type sense (unless the consumer were to specify the exact attributes of the duck it's interested in, which I fear would become a tedious type writing style).
I'd argue that, if you frequently have cases where functions use a relatively small subset of a much larger interface, it's simply that your interfaces are too large. You're always free to define your own, smaller protocols that just implement the subset of the interfaces you need.
File-like objects are used VERY frequently in the stdlib, and actual open file objects have quite a large interface. The use-case is a pretty real one: "if I were to create a simulant file object to pass to json.load(), what methods do I need?". Maybe in some cases, the "smaller protocols" option is practical, but it would need to have a useful name. For instance, if it needs to be readable, iterable, closeable, and autocloseable via __enter__/__exit__, that's ... uhh.... a readable, iterable, closeable context manager? Not an improvement over "file-like object". ChrisA