[Python-ideas] Proposal: Use mypy syntax for function annotations
Steven D'Aprano
steve at pearwood.info
Thu Aug 14 21:02:38 CEST 2014
On Wed, Aug 13, 2014 at 10:29:48PM +0200, Christian Heimes wrote:
> 1) I'm not keen with the naming of mypy's typing classes. The visual
> distinction between e.g. dict() and Dict() is too small and IMHO
> confusing for newcomers. How about an additional 'T' prefix to make
> clear that the objects are referring to typing objects?
>
> from typing import TList, TDict
>
> def word_count(input: TList[str]) -> TDict[str, int]:
> ...
Would it be possible, and desirable, to modify the built-in types so
that we could re-use them in the type annotations?
def word_count(input: list[str]) -> dict[str, int]:
Since types are otherwise unlikely to be indexable like that, I think
that might work.
> 2) PEP 3107 only specifies arguments and return values but not
> exceptions that can be raised by a function. Java has the "throws"
> syntax to list possible exceptions:
>
> public void readFile() throws IOException {}
I understand that this is called a "checked exception" in Java. I also
understand that they are hated and derided as useless or even
counter-productive:
http://literatejava.com/exceptions/checked-exceptions-javas-biggest-mistake/
> May I suggest that we also standardize a way to annotate the exceptions
> that can be raised by a function? It's a very useful piece of
> information and commonly requested information on the Python user
> mailing list.
And as frequently explained on the python-list, it's almost impossible
to answer. Or rather, the answer is usually no more specific than
"raises Exception".
There are very few guarantees you can reliably make about what
exceptions *cannot* be raised by a function. To put it simply, given
almost any operation in your function, say, x+1, there's no limit on
what x.__add__ might raise. Even if you know x is a subclass of int, it
could do anything in its __add__ method. Only if you know x is *exactly*
a builtin int can you be confident that it won't raise (say)
ImportError.
Perhaps with a few years of experience, we might be able to extend this
to exceptions without making the same mistakes as Java's checked
exceptions, but I wouldn't rush into it.
--
Steven
More information about the Python-ideas
mailing list