Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Does not work when from __future__ import annotations is in scope #179

Closed
ykrasik opened this issue Sep 22, 2024 · 2 comments
Closed

Does not work when from __future__ import annotations is in scope #179

ykrasik opened this issue Sep 22, 2024 · 2 comments

Comments

@ykrasik
Copy link

ykrasik commented Sep 22, 2024

Hi,

The following example will not work

from __future__ import annotations
from dataclasses import dataclass
import dataconf

@dataclass
class Test:
    my_var: str

conf = """
my_var = test
"""

print(dataconf.string(conf, Test))

Getting this error:

  File "...\.venv\Lib\site-packages\dataconf\main.py", line 108, in string
    return multi.string(s, **kwargs).on(clazz)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "...\.venv\Lib\site-packages\dataconf\main.py", line 93, in on
    return parse(conf, clazz, self.strict, **self.kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "...\.venv\Lib\site-packages\dataconf\main.py", line 26, in parse
    return utils.__parse(conf, clazz, "", strict, ignore_unexpected)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "...\.venv\Lib\site-packages\dataconf\utils.py", line 91, in __parse
    fs[f.name] = __parse(
                 ^^^^^^^^
  File "...\.venv\Lib\site-packages\dataconf\utils.py", line 269, in __parse
    subtype = value.pop("_type", default=None)
              ^^^^^^^^^
AttributeError: 'str' object has no attribute 'pop'

This line does not pass because when from __future__ import annotations, dataclass.fields returns the type as a string whose value is "str" rather then the class str. There are some more details about this here: https://stackoverflow.com/a/55938344

According to the above StackOverflow, the way to fix it is to not rely on the type from the field, but get it from typing.get_type_hints:

resolved = typing.get_type_hints(C)
f = dataclasses.fields(C)[0]
ftype = resolved[f.name]
@ykrasik
Copy link
Author

ykrasik commented Sep 22, 2024

Woops, duplicate of #43

@zifeo
Copy link
Owner

zifeo commented Sep 23, 2024

See indeed #43 (comment).

@zifeo zifeo closed this as completed Sep 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants