[Python-ideas] Conventions for Function Annotations

Nick Coghlan ncoghlan at gmail.com
Mon Aug 8 05:01:13 CEST 2011


On Mon, Aug 8, 2011 at 11:03 AM, dag.odenhall at gmail.com
<dag.odenhall at gmail.com> wrote:
>> Hi Dag,
>>
>> Are you currently using annotations? Could you post some of the cool
>> usages that you are making of annotations? The explicit plan with
>> annotations (read PEP 3107) was that significant use should precede
>> the creation of conventions for use. So please don't wait until a
>> convention has been established -- go ahead and have fun with them,
>> and let us know what you are doing with them!
>
> I'm toying with them for adaptation, interfaces and dependency
> injection from a component registry. Each use is about type constants,
> but not necessarily in the vein of static type checking, which I think
> stands to show their strengths and "Pythonicity".
>
> I do kinda think there's some need of informal conventions,
> examplified by Mathias post: his decorator sets the 'raises' key,
> effectively making "raises" a reserved keyword in function arguments
> using the decorator!

So far, the general approach has been for annotations to be paired
with decorator APIs, such that there is a cleaner less repetitive
syntax that relies on function annotations and a more general (but
more verbose) approach that uses arguments to a decorator factory.
That approach seems to work well, with the latter API used to handle
cases where a developer wants to use more than one annotation based
decorator on a single function. The general principle is that any
decorator that can use argument annotations should have an alternate
decorator factory based API that can be used when necessary (usually
either because the annotations are being used for something else or
because the function being decorated is an existing one from another
library that doesn't have any relevant annotations at all).

Using the annotation namespace to store arbitrary metadata doesn't
seem like a good idea at all. It is better to use the function
attribute namespace for that kind of thing - don't forget about the
old tools just because there is a shiny new tool to play with.

> Some convention for annotating 'yield' may still be useful though,
> although one alternative convention could use some form of
> "parametrized types" and the return annotation: foo() ->
> Iterator[tuple]. Now we just need to add this to ABCMeta. *cough* ;)

Why not just use the return field on the generator function as is? The
return type of calling something for which
'inspect.isgeneratorfunction(x)' is true is always going to be
'generator', so the return annotation is unlikely to be referring
directly to that.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list