[Python-3000] Type annotations: annotating generators
Collin Winter
collinw at gmail.com
Thu May 18 17:31:32 CEST 2006
In working on notes for the type annotations PEP, I've hit some
ambiguous/unresolved issues in the BDFL annotation syntax (drawing
primarily from [1] and other blog posts):
As a quick recap, the syntax looks something like this:
"""def foo(a: int, b: float, c: int = 5) -> list[int]"""
In looking through all of Guido's blog posts on the subject -- and all
the comments on them -- I haven't seen anyone consider the case of
generators. Assuming that "->" makes assertions only about the
function's return type, if I were to write a generator with the
following type,
"""def my_range(min: Number, max: Number) -> Number"""
it would blow up because the function returns a generator, not a Number.
Of course, "->" could be DWIMmy, in the sense that it knows whether
it's being used in a function or generator context. This doesn't solve
the other problem with annotating generators, though: send().
With the BDFL syntax, there's no way to add annotations for a
generator's send() method. One might suggest something like
"""def my_range(min: Number, max: Number) <- Number -> Number"""
where "<- Number" indicates that the generator's send() only accepts
Numbers, but this feels terribly kludgy to me.
My own proposal is to use keywords in the vein of "returns", "yields"
and "is_sent" (don't quibble with the names; the actual names can be
decided later). Under this modified syntax, the above send() example
looks something like this:
"""def my_range(min: Number, max: Number) is_sent Number, yields Number"""
In the same spirit, "->" would be replaced with "returns":
"""def foo(a: int, b: float, c: int = 5) returns list[int]"""
To combat overly long lines, users could wrap the annotation clauses
to the next line:
"""
def my_range(min: Number, max: Number) is_sent Number,
yields Number
"""
Nitpicky details:
1. Using is_sent and yields on a non-generator causes a SyntaxError.
2. Using returns on a generator causes a SyntaxError
Thanks,
Collin Winter
[1] - http://www.artima.com/weblogs/viewpost.jsp?thread=86641
More information about the Python-3000
mailing list