On Thu, Apr 22, 2021, at 1:01 PM, Brett Cannon wrote:
On Thu, Apr 22, 2021 at 4:11 AM Paul Moore <p.f.moore@gmail.com> wrote:
On Thu, 22 Apr 2021 at 11:21, Paul Moore <p.f.moore@gmail.com> wrote:
On Thu, 22 Apr 2021 at 11:06, Chris Angelico <rosuav@gmail.com> wrote:
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".
Looks like it doesn't:
cat .\test.py def example(f) -> None: f.close()
import sys example(12) example(sys.stdin) PS 12:00 00:00.009 C:\Work\Scratch\typing
mypy .\test.py Success: no issues found in 1 source file
What I was after was something that gave an error on the first call, but not on the second. Compare this:
In PyCharm, the above code will result in it highlighting the number `12` with the following warning: "Type 'int' doesn't have expected attribute 'close'" Similarly, for: def f(x: int): ... def g(x: str): ... def main(t: DuckTyped) -> None: if t[0] == 'version': f(t[1]) elif t[0] == 'name': g(t[1]) If you replace `f(t[1])` or `g(t[1])` with just `t.` and activate auto-completion, it'll show `__getitem__` as an option (but it won't show any additional int/str methods). If instead you add an `elif isinstance(t, str):`, under that condition it'll auto-complete `t.` with all string properties/methods.