[Python-ideas] Optional static typing -- late to the party

Steven D'Aprano steve at pearwood.info
Wed Aug 20 14:35:09 CEST 2014


On Wed, Aug 20, 2014 at 10:08:48PM +1000, Tennessee Leeuwenburg wrote:

[...]
> I was led to a conclusion: what is wrong with allowing both? 

"Both" being function annotations and docstring annotations.

Docstring annotations will not suddenly go away if (when) 
Guido's proposal is accepted.

But remember that any annotations in docstrings may not be available at 
runtime, whereas function annotations will be unless you deliberately 
delete them. Also, docstring annotations have the disadvantage of being 
text only, instead of expressions which evaluate to arbitrarily powerful 
or useful objects.

> Indeed,
> clearly both are actually already supported by various tools. So perhaps
> there is actually a higher-level common concept -- what are the actual
> assertion which are going to be supported? Can I declare a variable only to
> be a list, or can it be a list-of-ints?

Yes. Using Guido's suggestion of mypy's syntax:

from typing import List
def spam(x:List)->List[int]:
    ...

declares that spam accepts as argument a list of anything, and 
returns a list of ints. But of course you're more likely to want to 
accept anything which quacks like a list:

from typing import Sequence
def spam(x:Sequence)->List[int]:
    ...


The precise details of the syntax aren't yet finalised, but this is 
suggestive of what it will likely be (I hope).


> Further, is it possible to standardise between some of the
> syntax/terminology, and some of the assertion types, such that they are
> consistent between function annotation syntaxes and docstring embedding
> syntaxes? Could I use function annotation for simple cases, but seamlessly
> move to a docstring-embedded approach for a more complex example?

That entirely depends on the tool you are using for static type analysis 
and/or linting.


-- 
Steven



More information about the Python-ideas mailing list