[Python-ideas] Conventions for function annotations

Thomas Kluyver thomas at kluyver.me.uk
Sun Dec 2 16:25:24 CET 2012


On 2 December 2012 11:43, Nick Coghlan <ncoghlan at gmail.com> wrote:

> However, the flip-side of the argument is that if we assume my opinion is
> correct and document it as an official recommendation in PEP 8, then many
> people won't even *try* to come up with good approaches to composition for
> function annotations. Maybe there *is* an elegant, natural solution out
> there that's superior to using explicit calls to decorator factories for
> the cases that involve composition. If PEP 8 declares "just use decorator
> factories for cases involving composition, and always design your APIs with
> a non-annotation based fallback for such cases", would we be inadvertently
> shutting down at least some of the very experimentation we intended to
> allow?


My concern with this is that it's tricky to experiment with composition. If
you want to simultaneously use annotations for, say, one framework that
checks argument types, and one that documents individual arguments based on
annotations, they need to be using the same mechanism to compose annotation
values. Alternatively, the first one to access the annotations could
decompose the values, leaving them in a form the second can understand -
but that sounds brittle and opaque.

Another proposed mechanism (Robert's idea) which I didn't mention above is
to override __add__, so that multiple annotations can be composed like this:

def my_io(filename, mode: tab('read','write') + typed(str) ='read'):
    ...

As a possible workaround, here's a decorator for decorators that makes the
following two definitions equivalent:
https://gist.github.com/4189289

@check_argtypes
def checked1(a:int, b:str):
    pass

@check_argtypes(a=int, b=str)
def checked2(a, b):
    pass

With this, it's easy to use annotations where possible, and you benefit
from the extra clarity, but it's equally simple to pass the values as
arguments to the decorator, for instance if the annotations are already in
use for something else. It should also work under Python 2, using the
non-annotated version.

Thomas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20121202/17e0b3eb/attachment.html>


More information about the Python-ideas mailing list