[Python-ideas] Annotations (and static typing)
Steven D'Aprano
steve at pearwood.info
Thu Aug 21 02:02:39 CEST 2014
On Wed, Aug 20, 2014 at 05:31:50PM +0100, Paul Moore wrote:
> The obvious thought is, if a decorator is a sufficiently good
> notation, is there any need for annotations at all (even for static
> typing)?
Decorators are *not* sufficiently good notation.
Decorators have many nice uses, but they are second class for this
purpose since they require you to write the parameters twice: once in
the decorator, and once in the actual function declaration. They also
visually separate the parameter from its value.
If you're thinking about editing code with one or two such functions,
with simple parameter declarations, it's no big deal. They're not *very*
far away, a line or two maybe, it's easy to cope. But as the number of
parameters increases, or the complexity of the type declaration
increases, you get code like this:
@annotate(fe=Str[blah blah blah blah])
@annotate(fi=List[blah blah blah blah])
@annotate(fo=Dict[blah blah blah blah])
@annotate(fum=Tuple[blah blah blah blah])
@returns(int)
def spam(fe=aaa, fi=bbb, fo=ccc, fum=ddd):
...
and now you're looking at a solid wall of annotations, and the distance
between the first decorator and the parameter list isn't "a line or two"
any more. Or you get something like this, which may be a bit better:
@annotate(fe=Str[blah blah blah blah],
fi=List[blah blah blah blah],
fo=Dict[blah blah blah blah],
fum=Tuple[blah blah blah blah])
@returns(int)
def spam(fe=aaa, fi=bbb, fo=ccc, fum=ddd):
...
but still separates the type of fe from the declaration of fe by four
lines. With annotations, everything[1] stays together:
def spam(fe:Str[blah blah blah blah]=aaa,
fi:List[blah blah blah blah]=bbb,
fo:Dict[blah blah blah blah]=ccc,
fum:Tuple[blah blah blah blah]=ddd,
)->int:
...
I'm going to take the liberty of quote Nick from an earlier message:
[quote]
I once had the "pleasure" of inheriting some code written in K&R style
C, where the parameter type declarations were separate from the
signature line:
void foo(a, b, c)
double a;
char b;
{
...
}
ANSI C, with inline typing, is far more readable :)
[end quote]
C programmers, hands up if you prefer to use K&R style declarations?
I expect you will be in a very small minority.
There is a reason why most languages with type declarations normally put
them together with the parameter declarations.
If anyone wishes to argue for decorator style *in preference* to
annotations, a good place to start is with a list of programming
languages which use similar syntax for their type declarations.
[1] Not quite, you still have to write documentation separately, but
since the documentation for a single parameter might be an entire
paragraph of text, we don't want to put that in the parameter list.
Some problems are just intractable.
--
Steven
More information about the Python-ideas
mailing list