[Python-ideas] Improving the expressivity of function annotations

Nick Coghlan ncoghlan at gmail.com
Mon Apr 4 16:08:03 CEST 2011


On Mon, Apr 4, 2011 at 11:33 PM, Masklinn <masklinn at masklinn.net> wrote:
> On 2011-04-04, at 15:06 , Nick Coghlan wrote:
>> If what you want is static typing, perhaps using a statically typed
>> language would be a good place to start?
> Mostly what I was interested in was making function annotations useful. I'm guessing they were introduced to be used yet due to the limitations I outlined their actual value falls like a rock as soon as you're using anything more complex than strings and numbers, especially if you tend to use "duck" types a lot.

They're not useful for comprehensive static typing without defining
additional conventions. But that's OK, since that's not their purpose
- at the language level, they're just a place to associate arbitrary
data with parameters and the function as a whole, typically for use by
specific decorators that are also applied at function definition time.
Which annotations you use and which decorators you use will
accordingly be task specific. (For example, here's a simple one that
uses function annotations to define relatively type safe calls out to
C functions via ctypes:
http://code.activestate.com/recipes/576731-c-function-decorator/)

As it stands, there's absolutely nothing stopping you implementing the
suggestions in your original post as an external library (albeit
without being able to use infix syntax on the builtin types, but using
tuples instead should work just fine for the sum case, and you can
define your own Generic ABCs for the generics case). As far as the
structural types go, just use function annotations and appropriate
decorators on the methods in an ABC definition (although you would
want your own new metaclass to enforce the additional rules).

As far as the language itself goes, however, we made a deliberate
decision not to ascribe any specific semantics to function
annotations, and nothing has happened in the intervening time to
convince us to go back on that decision.

It would require an annotations-based approach to a task to prove
incredibly popular for us to bless for it inclusion in the standard
library. If anything was going to happen on that front, my money would
actually be on some utilities in ctypes, such as the cookbook recipe I
linked above. This is *not* an area where theoretical arguments are
going to hold any water: only practical solutions that help make code
dealing with real-world problems significantly more readable.

Cheers,
Nick.

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



More information about the Python-ideas mailing list