lebrice / SimpleParsing

Simple, Elegant, Typed Argument Parsing with argparse
MIT License
399 stars 49 forks source link

Decoding dataclass with old-style type annotations (e.g. Optional[int]) fails when postponed annotations #144

Closed lebrice closed 2 years ago

lebrice commented 2 years ago

Describe the bug When postponed evaluation of type annotations is enabled, and the dataclass uses "old-style" type annotations, the decoding function for fields aren't found properly.

To Reproduce

from __future__ import annotations
from simple_parsing import ArgumentParser
from dataclasses import dataclass
from simple_parsing.helpers.serialization.serializable import Serializable
from typing import Optional

@dataclass
class Foo(Serializable):
   bar: Optional[int] = 123

if __name__ == "__main__":
    foo = Foo.from_dict({"bar":  None})
    print(foo)

Expected behavior A clear and concise description of what you expected to happen.

$ python issue.py
Foo(bar=None)

Actual behavior A clear and concise description of what is happening.

$ python issue.py
Traceback (most recent call last):
(...)
  File "/home/fabrice/.conda/envs/dtp/lib/python3.9/site-packages/simple_parsing/helpers/serialization/serializable.py", line 159, in from_dict
    return from_dict(cls, obj, drop_extra_fields=drop_extra_fields)
  File "/home/fabrice/.conda/envs/dtp/lib/python3.9/site-packages/simple_parsing/helpers/serialization/serializable.py", line 552, in from_dict
    field_value = decode_field(field, raw_value)
  File "/home/fabrice/.conda/envs/dtp/lib/python3.9/site-packages/simple_parsing/helpers/serialization/decoding.py", line 65, in decode_field
    return get_decoding_fn(field_type)(raw_value)
  File "/home/fabrice/.conda/envs/dtp/lib/python3.9/site-packages/simple_parsing/helpers/serialization/decoding.py", line 118, in get_decoding_fn
    raise ValueError(
ValueError: Couldn't find a decoding function for the string annotation 'Optional[int]'.
This is probably a bug. If it is, please make an issue on GitHub so we can get to work on fixing it.