Argument Decorators Enhancement?

birchb at ozemail.com.au birchb at ozemail.com.au
Tue May 16 06:42:11 CEST 2006


Guido has proposed a syntax for type annotations in Python-3000.
Example:

def foo(x: t1, y: t2) -> t3:
    ...body...


http://www.artima.com/weblogs/viewpost.jsp?thread=87182

The types are dynamic and there is significant execution of code prior
to the function body being called. Which tends to make the above closer
to a decorator than a static type declaration. That being so, it
occurred to me that perhaps an argument decorator would be more general
and perhaps less restrictive. The example using decorators:

def foo(@T1 x, @t2 y) @ t3:
    ...body...

The compiler would do something like this:

def foo__(x, y):  # original function
    ...body...

def foo(x, y):    # wrapper function
    x = T1.__decarg__(foo_, x)
    y = t2.__decarg__(foo_, y)
    r = foo__(x, y)
    return t3.__decreturn___(foo__, r)

More examples:

def func(@between(1,400) x) @bool :   #  between checks input range

def func(@NotNone x):    #  x must be a real object

def func(@long x) @coerce(float):   # coerce forces type conversion

def func(@sequence s, @function fn) @sequence: # more abstract types

To someone used to reading decorators, the @ character is a flag that
some kind of dynamic magic is being run. So IMHO using @ here too is
consistent with its existing usage.

Argument decorators would be an object (not a function) with methods
corresponding to their usage:

class T1(object):
     def __decarg__(self, function, arg):  # returns arg
     def __decreturn__(self, function, arg):  # returns arg

This will allow existing types to be used if they implement these
methods:

def bar(@int x, @float y) @float :
    ...body...

Because this syntax is just a decorator, you could use or abuse it as
you wished.

So you could define and use your own type-checking classes and
semantics:

def bar(@StrictlyInt x, @DuckCompatibleSequence seq) :
    ...body...

Since the decorator is an *object*, not a function, we could add other
methods for use by IDEs for intellisense etc.

Any views on this? Something to put forward to the python-3000 list
maybe?




More information about the Python-list mailing list