[Python-ideas] Conventions for Function Annotations

dag.odenhall at gmail.com dag.odenhall at gmail.com
Sun Aug 7 13:27:51 CEST 2011


This isn't really a proposal for any sort of language/stdlib change,
rather I felt like discussing the potential for informal standard
conventions with annotations.

Probably for the better, there is no special syntax for annotating
raised exceptions or yields from a generator. In line with how the
"->" syntax sets the 'return' key, I suggest an informal standard of
representing keywords this way, for example in a decorator for
raise/yield annotations:

# third-party decorator
@raises(ValueError)
def foo():pass

assert foo.__annotations__['raise'] == ValueError

This might be an obvious solution, but I just wanted to "put it out
there" up front, before inconsistent workarounds emerge. This
convention should work because it is primarily needed for control
structures that are reserved keywords anyway. The one exception I can
think of is the inverse of yield: generator.send() - "send" could
conflict with a function argument, and should therefore not be put in
__annotations__. (A hack could be to use a different but semantically
related keyword like 'import', or an otherwise invalid identifier like
'send()', but it might be best to simply not use __annotations__ for
this.)



More information about the Python-ideas mailing list