[Python-ideas] Proposal: Use mypy syntax for function annotations
Steven D'Aprano
steve at pearwood.info
Sat Aug 23 03:36:47 CEST 2014
On Thu, Aug 21, 2014 at 09:23:39AM -0400, Antoine Pitrou wrote:
> I'm -1 on using __getitem__ for parametering types. It is indeed a hack
> and its limitations will bite us harshly when wanting to refine the type
> descriptions (for example to describe a constraint on a collection's size).
> >One last thing: let’s not add |List|, |TList|, etc. Just use |list| and
> >other existing types to generate new types.
>
> I'm -1 on that, for exactly the same reason as above.
It's not 100% clear to me whether you're -1 on re-using |list| or -1 or
adding |List|. I'm going to assume that you mean -1 on re-using list
(see below).
In a later message, Antoine wrote:
> Python has one of the most powerful and user-friendly function call
> syntaxes around, why reinvent something clearly inferior and alien?
I wouldn't say it is alien. abc[xyz] is clearly Python syntax. Nor would
I necessarily say it is inferior, although it is more limited.
Deliberately so, I think. How complex will the static type declarations
need to be for us to want to accept arbitrary keyword arguments, for
example? I think limiting the syntax possible is a good thing, it will
discourage people from trying to declare arbitrarily complex information
in the type notations.
But another reason for disliking call syntax for this is that it gets
confusing:
def function(param:Sequence(Spam, Eggs))->Mapping(Cheese, Toast):
suffers compared to this:
def function(param:Sequence[Spam, Eggs])->Mapping[Cheese, Toast]:
In the second case, the type annotations stand out more easily because
they use square brackets instead of round.
As far as the question of list versus List, I don't believe we can use
built-ins if we follow Antoine's suggestion of call syntax.
def function(param:list(int))->list(str):
for example, intends to declare param is a list of ints. But list(x)
already has a meaning, and if x is an int, it raises TypeError.
param:List(int) at least can work, but now consider int. Perhaps we
might like to specify a range of ints, from 0 to 9 (say). The obvious
syntax would be:
param:List(int(0, 10)) # inclusive lower bound, exclusive upper bound
but again that already has meaning. If we want the flexibility of
providing arguments to scalar types like int, I believe we need to use
subscripting syntax:
param:List[int[0, 10]]
-1 on re-using call syntax: it is more confusing to read inside a
parameter list, too flexible, and clashes with existing use calling
types.
+1 on subscripting syntax: it is more easily distinguishable from
calling, just flexible enough, and doesn't clash with existing
functionality.
--
Steven
More information about the Python-ideas
mailing list