On Thu, 22 Apr 2021 at 11:06, 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.
Hmm, I sort of wondered about that as I wrote it. But in which case, what's the problem here? My understanding was that people were concerned that static typing was somehow in conflict with duck typing, but if the static checkers enforce the inferred duck type on untyped arguments, then that doesn't seem to be the case. Having said that, I thought that untyped arguments were treated as if they had a type of "Any", which means "don't type check". So I guess the point here is that either the typing community/documentation isn't doing a very good job of explaining how duck types and static types work together, or that people who like duck typed interfaces¹ aren't reading the available documentation in type checkers explaining how to do that with static typing :-) Paul ¹ And I include myself in that - maybe I need to go and read the mypy docs properly rather than just learning what I need by following examples in existing code...