[Python-3000] Type annotations: annotating generators
collinw at gmail.com
Fri May 19 03:59:01 CEST 2006
On 5/18/06, Guido van Rossum <guido at python.org> wrote:
> On 5/18/06, Collin Winter <collinw at gmail.com> wrote:
> > 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.
> My first response: specify the return type as Generator[Number] so the
> whole thing would look like
> def my_range(min: Number, max: Number) -> Generator[Number]: ...
> I don't like adding syntax specific to generators (especially since
> most of the time send() won't be used at all).
> I could extend my Generator[Number] example by also allowing
> Generator[Number, Number] where the 2nd type would specify the
> argument accepted by send(). (Making it 2nd makes it easy to omit.)
> Or if you don't like this (I'm not crazy about letting people guess
> what the second type is for either) you could write Generator(Number,
> send=Number) or even Generator(returns=Number, send=Number). I think
> it's fine to specify the return type of the generator by position and
> the rest by keyword since the return type is always present.
> Generator[Number] and Generator(Number) could mean the same thing
> assuming Generator is not a real type like list but a pseudo type only
> used for type annotations, like Sequence, Mapping, Iterator etc.
I like using Generator[yields, send] in combination with "->". The
send parameter might be a good candidate for keyword-only arguments.
More information about the Python-3000