ericvsmith / dataclasses

Apache License 2.0
587 stars 53 forks source link

Support string type annotations #92

Closed ericvsmith closed 6 years ago

ericvsmith commented 6 years ago

The implementation needs some work with regards to string annotations. This only affects ClassVar and InitVar, since other annotations are ignored.

@dataclass
class C:
   context: "InitVar[context]"
   count: "ClassVar[Counter]"

This is all the more important with regards to PEP 563, "Postponed Evaluation of Annotations".

I'd like to keep the property that typing isn't imported by dataclasses.py, so maybe I'll resort to inspecting the string. I'll probably wait until PEP 563 is finalized before doing anything about this.

ericvsmith commented 6 years ago

See https://github.com/python-attrs/attrs/issues/265 and https://github.com/python-attrs/attrs/pull/302 for the same issue with attrs.

ilevkivskyi commented 6 years ago

I think the easiest option is just using typing.get_type_hints() (as recommended by PEP 526). However, importing typing takes some time, but after PEP 560 it will be approx. 7x faster.

ericvsmith commented 6 years ago

My limited understanding of typing.get_type_hints() is that it would still be a problem, in the case of a forward reference (and probably other cases).

@dataclass
class A:
    b: "ClassVar[B]"

class B:
    pass

Isn't it true that dataclass(), when processing class A, would get an error when calling typing.get_type_hints() because B isn't defined yet?

ilevkivskyi commented 6 years ago

Isn't it true that dataclass(), when processing class A, would get an error when calling typing.get_type_hints() because B isn't defined yet?

I think this is rather a problem with get_type_hints (and it can be easily fixed).

ilevkivskyi commented 6 years ago

Opened https://github.com/python/typing/issues/508

ambv commented 6 years ago

This needs addressing before the last beta. I will handle that.

ericvsmith commented 6 years ago

See bpo-33453 for further discussion.