Title: Forward reference is not resolved by dataclasses.fields()
Type: behavior Stage: patch review
Components: Library (Lib) Versions: Python 3.7
Status: open Resolution:
Dependencies: Superseder:
Assigned To: eric.smith Nosy List: eric.smith, levkivskyi, mdrachuk, plammens
Priority: normal Keywords: patch

Created on 2019-04-16 19:44 by mdrachuk, last changed 2021-07-24 11:41 by eric.smith.

Pull Requests
URL Status Linked Edit
PR 27330 open mdrachuk, 2021-07-24 11:12
Messages (5)
msg340361 - (view) Author: Misha Drachuk (mdrachuk) * Date: 2019-04-16 19:44
Forward reference is not resolved by `dataclasses.fields()`, but it works with `typing.get_type_hints()`.


from dataclasses import dataclass, fields
from typing import Optional, get_type_hints

class Nestable:
    child: Optional['Nestable']

o = Nestable(None)
print('fields:', fields(o))
print('type hints:', get_type_hints(Nestable))

... outputs the following:
fields: (Field(name='child',type=typing.Union[ForwardRef('Nestable'), NoneType] ... )
type hints: {'child': typing.Union[__main__.Nestable, NoneType]}
msg397043 - (view) Author: Paolo Lammens (plammens) * Date: 2021-07-06 15:03
I was about to create the exact same ticket; I'm nudging this.
msg398024 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-07-23 01:48
It can’t be resolved in fields(): it is still undefined when the fields are created. 

I think the best solution is PEP 649.
msg398141 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-07-24 11:14
I’m deferring any action on this until PEP 649 is ruled on.
msg398142 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-07-24 11:41
Also, when dataclasses was originally written, it deliberately did not import typing, for performance reasons. I don't know if PEP 560 (I think) improved performance enough to make a difference. But adding this dependency needs to be looked at.

But if we are going to import typing, there are other changes that I'd like to make, like improving the ClassVar stuff.
Date User Action Args
2021-07-24 11:41:27eric.smithsetmessages: + msg398142
2021-07-24 11:14:09eric.smithsetassignee: eric.smith
messages: + msg398141
2021-07-24 11:12:05mdrachuksetkeywords: + patch
stage: patch review
pull_requests: + pull_request25873
2021-07-23 01:48:06eric.smithsetmessages: + msg398024
2021-07-06 15:03:04plammenssetnosy: + plammens
messages: + msg397043
2019-04-19 23:32:44levkivskyisetnosy: + levkivskyi
2019-04-16 20:04:45xtreaksetnosy: + eric.smith
2019-04-16 19:44:38mdrachukcreate