[Python-Dev] PEP 484 update proposal: annotating decorated declarations
Ivan Levkivskyi
levkivskyi at gmail.com
Mon May 15 09:20:26 EDT 2017
On 15 May 2017 at 10:48, Koos Zevenhoven <k7hoven at gmail.com> wrote:
> > Here's the proposed text (wordsmithing suggestions in the PR please):
> >
> > +Decorators
> > +----------
> > +
> > +Decorators can modify the types of the functions or classes they
> > +decorate. Use the ``decorated_type`` decorator to declare the type of
> > +the resulting item after all other decorators have been applied::
> > +
> > + from typing import ContextManager, Iterator, decorated_type
> > + from contextlib import contextmanager
> > +
> > + class DatabaseSession: ...
> > +
> > + @decorated_type(Callable[[str], ContextManager[DatabaseSession]])
> > + @contextmanager
> > + def session(url: str) -> Iterator[DatabaseSession]:
> > + s = DatabaseSession(url)
> > + try:
> > + yield s
> > + finally:
> > + s.close()
> > +
> > +The argument of ``decorated_type`` is a type annotation on the name
> > +being declared (``session``, in the example above). If you have
> > +multiple decorators, ``decorated_type`` must be topmost. The
> > +``decorated_type`` decorator is invalid on a function declaration that
> > +is also decorated with ``overload``, but you can annotate the
> > +implementation of the overload series with ``decorated_type``.
> > +
> >
>
> Would __annotations__ be set by the decorator? To me, not setting them
> would seem weird, but cases where the result is not a function could
> be weird. I also don't see a mention of this only working in stubs.
>
> I like Jukka's version, as it has a clear distinction between
> functions and other attributes. But that might require a language
> change to provide __annotations__ in a clean manner? Maybe that
> language change would be useful elsewhere.
With original syntax it is possible to overwrite annotations without
language changes.
However with Jukka's syntax it looks difficult. A possible pure-Python way
could be
to insert an item in an enclosing __annotations__, if an enclosing scope
is a class or module scope.
--
Ivan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20170515/acd23ce9/attachment.html>
More information about the Python-Dev
mailing list