[Python-ideas] Proposal: Use mypy syntax for function annotations
Antoine Pitrou
antoine at python.org
Sat Aug 23 04:31:18 CEST 2014
Le 22/08/2014 21:36, Steven D'Aprano a écrit :
>
> 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).
Indeed.
> 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.
But it is completely uncommon for anything else than subscripting and
indexing containers. Python isn't known for reusing operators for
completely unrelated things, e.g. it doesn't overload ">>" for I/O
(thank goodness).
> 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.
I think this is an incredibly weak argument, and the proof is that it
hasn't been brought for anything else in the stdlib. Why the typing
module should be any different and use a deliberately repressive
parameter-passing syntax is beyond me - even though it's an advanced,
optional, feature and will be put in the hands of consenting adults.
> 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]:
If you find it confusing (which may simply be a matter of habit, I don't
know), you can simply alias the types:
spam_eggs_sequence = Sequence(Spam, Eggs)
cheese_toast_mapping = Mapping(Cheese, Toast)
def function(param: spam_eggs_sequence) -> cheese_toast_mapping:
...
Regardless of readability, I would expect people to create such aliases
anyway, the same way people tend to create "typedefs" in other
languages, because it helps condense and clarify which actual types are
in use in a module.
> 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.
And indeed this is exactly why I said I was against using built-ins for
this (or the existing ABCs) :-))
Really, for it to be powerful enough, the type description system has to
use its own set of classes. It can't try to hack away existing builtins
and ABCs in the hope of expressing different things with them, or it
*will* hit a wall some day (and, IMO, sooner rather than later).
Regards
Antoine.
More information about the Python-ideas
mailing list