[Python-ideas] Proposal: Use mypy syntax for function annotations

Alexander Belopolsky alexander.belopolsky at gmail.com
Sat Aug 16 04:07:45 CEST 2014


On Fri, Aug 15, 2014 at 7:46 PM, Ethan Furman <ethan at stoneleaf.us> wrote:

> Sounds like what we *really* need is a decorator that will parse the
> docstring and fill in the annotations automatically.  :)


While it may be contrary to the TOOWTDI principle, but I think decorator-
and annotations-based type specifications can co-exist.  I have been using
the following decorator for about a year

def returns(type):
    """emulate -> attribute setting in python 2"""

    def decorator(func):
        func.__dict__.setdefault('__attributes__', {})['return'] = type
        return func

    return decorator

and I often find code that uses for example @returns(int) more readable
than the code that uses .. -> int:

The advantage of argument annotations over any decorator-based solution is
avoidance of repetition, but I often miss K&R-style declarations in C.
 Probably because

int
copy(from, to)
char *from;
char *to;
{..}

looks more "pythonic" than

int
copy(char *from, char *to)
{}

In python, what is more readable:

def copy(from:Sequence, to:MutableSequence):
       ..

or

@arg_types(from=Sequence, to=MutableSequence)
def copy(from, to):
    ..

or

def copy(from, to):
    ..

set_arg_types(copy, from=Sequence, to=MutableSequence)

?


I believe that having type specifications out of the way in the last
variant more than outweighs the need to repeat the names of arguments.

Even the repetition  can be avoided if we do something like

@arg_types(Sequence, MutableSequence)
def copy(from, to):
    ..

but this is still more intrusive than the after-body variant where function
name repetition is unavoidable and argument names repetition improves
readability.

I can imagine cases where having type specifications follow each argument
is helpful.  For example

def configure(d:Drawing, c:Configuration):
   d.background = c.get_parameter('background')
   d.height = c.get_parameter('height')
   ..

It really depends on the problem at hand and on the coding style whether
you may want type specification before or within the function declaration
or out of the way in docstring, after the function body or in a separate
"stubs" file altogether.

If Python gets an official standard for specifying types in function
attributes, it should not be hard to standardize docstring and decorator
alternatives as well.  As a bonus, these alternatives will be immediately
available to 2.x users.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140815/ea715471/attachment-0001.html>


More information about the Python-ideas mailing list