[Python-ideas] Type Hinting Kick-off
Guido van Rossum
guido at python.org
Sun Dec 21 17:53:40 CET 2014
On Sat, Dec 20, 2014 at 2:00 PM, Dennis Brakhane <brakhane at googlemail.com>
wrote:
>
> Maybe I'm missing something, but wouldn't type hinting as it's defined
> now break "virtual subclassing" of ABC?
>
> For example, given the following code:
>
> from collections import Sequence
>
> class MySequence:
> ...
>
> Sequence.register(MySequence)
>
> it seems to me like the following would work:
>
> def foo(bar):
> if not isinstance(bar, Sequence):
> raise RuntimeError("Foo can only work with sequences")
> ...
>
> but when rewritten for static type checking
>
> def foo(bar: Sequence):
> ....
>
> it would cease to work. At least I don't see a way a static type checker
> could handle this relaiably (the register call might occur anywhere,
> after all)
>
> Is this intentional?
>
> Even if this might be more a mypy/implementation question, it should be
> clear to users of typing.py if they should expect ABCs to break or not
>
Well, the program will still run fine with CPython, assuming you keep the
isinstance() check in your program. The argument declaration does not cause
calls with non-Sequence arguments to be rejected, it just guides the static
checker (which is a program that you must run separately, in a similar way
as a linter -- it is not built into CPython).
The static checker may request the call foo(MySequence()) if it cannot see
that MySequence is a Sequence. You have two options there: if you can
change the code of MySequence, you should just inherit from Sequence rather
than using the register() call; if you cannot change the code of
MySequence, you should use a *stub* module which declares that MySequence
is a Sequence. You can read up on stub modules in the mypy docs:
http://mypy.readthedocs.org/en/latest/basics.html#library-stubs
--
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141221/404b3329/attachment.html>
More information about the Python-ideas
mailing list