[Python-ideas] Proposal: Use mypy syntax for function annotations
Steven D'Aprano
steve at pearwood.info
Fri Aug 15 03:13:14 CEST 2014
On Fri, Aug 15, 2014 at 10:29:21AM +1000, Chris Angelico wrote:
> On Fri, Aug 15, 2014 at 10:14 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> > I don't think this one is justified. At the very least, I think the
> > decision to deprecate or not should be deferred until at least 3.7. It's
> > enough to say that:
> >
> > - you can use function annotations for type checking; or
> >
> > - you can use function annotations for something else;
>
> But who is "you"? Presumably the application author.
The author of the code containing the annotations.
> What about imported modules - what will they use annotations for?
Whatever they choose.
If they import typing and don't explicitly disable typechecking, they
will get the default meaning of annotations, which is typechecking. If
they perform whatever step is required to tell the linter "don't check
here", the linter will treat that module as if it had no annotations.
(That doesn't necessarily mean ignoring the module, it only means ignore
the annotations. A type checker with type inference might still be able
to work with the module, so long as it needs no type hints.)
> Will
> conflicting uses break stuff? Or, conversely, will every use of
> annotations have to be meta-annotated with its purpose, to try to
> avoid breaking things?
No. I think Guido has the right instinct to make annotations' default
purpose be for type-checking, but it's easy enough to make it opt-out.
Since this is Python-Ideas, here are some ideas:
* If "typing" is not imported at all in the module, linters should
ignore annotations inside that module.
* Have a decorator that tells linters and other tools "these are
not type annotations":
from typing import skip
@skip
def function(x: Spam, y: Eggs)->Cheese:
pass
Compliant linters and IDEs will now skip function, treating it as
if it had no annotations at all, leaving the interpretation of the
annotations up to the author of the module.
Non-compliant linters, of course, should be beaten with a large halibut,
like any other buggy software :-)
The last one will probably require a standardized convention for how
compliant tools recognise whether or not annotations are for them.
Perhaps something like:
if '+state' in func.__annotations__:
# skip type-checking.
I picked '+state' because it is an invalid identifier and so cannot
clash with any parameter name. The value of __annotations__['+state']
can remain unspecified, different tools could use it for whatever they
like without Python's blessing, only the existence of that key is enough
to mark the function as "don't treat these as type annotations".
--
Steven
More information about the Python-ideas
mailing list