JelleZijlstra / autotyping

Automatically add simple type annotations to your code
233 stars 19 forks source link

Infer magic methods #1

Closed orsinium closed 3 years ago

orsinium commented 3 years ago

Thank you for the project. I tried it on the project, and it works. At least, doesn't break anything :)

The return type for some magic methods can be also auto-annotated. A few examples:

  1. __str__ and __repr__ return str
  2. __init__ returns None
  3. iter returns typing.Iterable
JelleZijlstra commented 3 years ago

Thanks, that's great to hear! I'm going to do some more work on in this in the next couple of weeks. I agree with __str__ and __repr__, but I don't think we can do __iter__, because you really want Iterable[SomeType] and autotyper is not nearly smart enough to know what that type should be.

Other methods we could infer:

orsinium commented 3 years ago

but I don't think we can do iter, because you really want Iterable[SomeType]

This is an interesting topic to discuss, BTW. I think autotyper can partially infer some types because it is better than nothing. In this case, typing.Iterator (or more explicitly, typing.Iterator[typing.Any]) will already allow mypy to find some bugs. The same applies to generic types like typing.List (or just list).

JelleZijlstra commented 3 years ago

That's a fair point. It will also introduce new mypy errors if you have --disallow-any-generics on, but on a codebase that you use autotyper on you might not want to worry about strictness options yet. :)

JelleZijlstra commented 3 years ago

Just merged support for most of this, except for __exit__ which I split out into #8.

Let me know if you have more ideas for improvements!

orsinium commented 3 years ago

Great! Thank you. I'll give it a try :)

Beautiful project, BTW, I always wanted something like this. I've added it into awesome-python-typing.