Argument Decorators Enhancement?

B

birchb

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?
 
B

bayerj

Hi,

-1 because I find it extremly hard to read and not necessary in that
scale.

Actually, there are a lot of recipes in the Cookbook [1] on how to use
decorators for type-checking. On example is:

@require(int, int)
def add(x,y): return x + y

Which I find much more readable, easier to implement and even backwards
compatible:

def add(x,y): return x + y
add = require(int, int)(add)

g2g,
Justin

[1] http://aspn.activestate.com/ASPN/Cookbook/Python/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,696
Latest member
BarbraOLog

Latest Threads

Top