On Thu, Apr 22, 2021 at 5:43 AM Chris Angelico <rosuav@gmail.com> wrote:
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?".
My experience with so-called "file-like objects" is that the interface required most of the time consists of a single method: read()
Maybe in some cases, the "smaller protocols" option is practical, but it would need to have a useful name.
The authors of the typing module already came up with an excellent convention. For the narrow protocol I mentioned, the conventional name would be "SupportsRead". Maybe "SupportsRead[str]" and "SupportsRead[bytes]".
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".
Yes, file-like objects can and do have lots of methods. Often you don't need more than read() Cheers, Luciano On Thu, Apr 22, 2021 at 7:04 AM Chris Angelico <rosuav@gmail.com> wrote:
On Thu, Apr 22, 2021 at 7:53 PM Paul Moore <p.f.moore@gmail.com> wrote:
I wonder whether type checkers could handle a "magic" type (let's call it DuckTyped for now :-)) which basically means "infer a protocol based on usage in this function". So if I do:
def my_fn(f: DuckTyped): with f: data = f.read() for line in f: print(line) f.close()
then the type checker would automatically build a protocol type like the one I defined above and use that as the type of f? That would make it much easier to include duck typed arguments in function signatures while keeping the benefits of static type checking.
Someone will likely correct me if this is inaccurate, but my understanding is that that's exactly what you get if you just don't give a type hint. The point of type hints is to give more information to the type checker when it's unable to simply infer from usage and context.
ChrisA _______________________________________________ Python-Dev mailing list -- python-dev@python.org To unsubscribe send an email to python-dev-leave@python.org https://mail.python.org/mailman3/lists/python-dev.python.org/ Message archived at https://mail.python.org/archives/list/python-dev@python.org/message/RW5ACSLJ... Code of Conduct: http://python.org/psf/codeofconduct/
-- Luciano Ramalho | Author of Fluent Python (O'Reilly, 2015) | http://shop.oreilly.com/product/0636920032519.do | Technical Principal at ThoughtWorks | Twitter: @ramalhoorg