[Python-Dev] Postponed annotations break inspection of dataclasses (original) (raw)
Ivan Levkivskyi levkivskyi at gmail.com
Thu Sep 27 12:05:57 EDT 2018
- Previous message (by thread): [Python-Dev] Postponed annotations break inspection of dataclasses
- Next message (by thread): [Python-Dev] Postponed annotations break inspection of dataclasses
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Do we have a b.p.o. issue about this? If no, then I would recommend to open one, so that we will not loose track of this.
-- Ivan
On Sat, 22 Sep 2018 at 16:32, David Hagen <david at drhagen.com> wrote:
The new postponed annotations have an unexpected interaction with dataclasses. Namely, you cannot get the type hints of any of the data classes methods.
For example, I have some code that inspects the type parameters of a class's
_init_
method. (The real use case is to provide a default serializer for the class, but that is not important here.)_ _from dataclasses import dataclass_ _from typing import gettypehints_ _class Foo:_ _pass_ _@dataclass_ _class Bar:_ _foo: Foo_ _print(gettypehints(Bar._init_))_ _
In Python 3.6 and 3.7, this does what is expected; it prints{'foo':_ _<class '_main_.Foo'>, 'return': <class 'NoneType'>}
. However, if in Python 3.7, I addfrom _future_ import annotations
, then this fails with an error:_ _NameError: name 'Foo' is not defined_ _
I know why this is happening. The_init_
method is defined in thedataclasses
module which does not have theFoo
object in its environment, and theFoo
annotation is being passed todataclass
and attached to_init_
as the string"Foo"
rather than as the original objectFoo
, butgettypehints
for the new annotations only does a name lookup in the module where_init_
is defined not where the annotation is defined. I know that the use of lambdas to implement PEP 563 was rejected for performance reasons. I could be wrong, but I think this was motivated by variable annotations because the lambda would have to be constructed each time the function body ran. I was wondering if I could motivate storing the annotations as lambdas in class bodies and function signatures, in which the environment is already being captured and is code that usually only runs once.
Python-Dev mailing list Python-Dev at python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/levkivskyi%40gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20180927/f610edfc/attachment.html>
- Previous message (by thread): [Python-Dev] Postponed annotations break inspection of dataclasses
- Next message (by thread): [Python-Dev] Postponed annotations break inspection of dataclasses
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]