Eric V. Smith <e...@trueblade.com> added the comment:

See also [2]_ for a brief discussion of forward references, which makes 
get_type_hints() undesirable in this case.

> This is why attrs went with the fast way which covers most (but not all) 
> bases in this case. If the annotation is a string, just check if it starts 
> with "typing.ClassVar", "t.ClassVar", or just "ClassVar". That's a fast check 
> and doesn't ever require importing typing.  On the flip side, the 0.001% of 
> users [1]_ who import ClassVar differently, will not have their class 
> variables recognized.

I'm okay with the fast check for the string "ClassVar". My only concern is how 
the user would figure out what's going on, if for example they "import typing 
as T". The generated __init__ wouldn't have the params they expect, but with 
default values thrown in I'm not so sure how quickly they'd notice. Hopefully 
they'd figure out soon enough there's a problem, but I'm not sure they'd know 
the cause if it.

Maybe we could do some additional checking if typing has been imported? If we 
see "T.ClassVar" ("[identifier].ClassVar" appears at the beginning of the 
string) then if typing has been imported, further check that "T is typing"? 
Although this isn't going to help with "from typing import ClassVar as CV" (but 
only 0.00004% of users would do that [3]_) and I don't want to use regex's for 
this. str.partition() is likely good enough, if we decide to go this route.

Is there any scenario where the following code would be useful, or expected to 
work, if "import typing as T" hadn't been executed before @dataclass runs? 
After all, if we do decide to call get_type_hints() it wouldn't work without it.

  field: "T.ClassVar[SomeTypeReferencedLater]" = get_some_type_object()

But again, unless [2]_ is addressed, get_type_hints() will fail unless both T 
and SomeTypeReferencedLater are known when @dataclass runs, if we used 
get_type_hints().

So, I guess this is my roundabout way of saying we should do the best we can 
with string inspection, and not use get_type_hints(). Maybe we can discuss it 
with Guido at the sprints.

For all of this, I'm assuming we'll do something similar with InitVar. Although 
we obviously know it's been imported, it doesn't solve all of the other issues 
with get_type_hints.

[2] .. https://github.com/python/typing/issues/508

[3] .. Also a made up number.

----------
priority: normal -> release blocker

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue33453>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to