konradhalas / dacite

Simple creation of data classes from dictionaries.
MIT License
1.72k stars 107 forks source link

Optional field nonsense #121

Closed kacirekj closed 3 years ago

kacirekj commented 3 years ago

When I have dataclass:

@dataclass
class A:
  myObject: MyObject

Then I have defined that myObject is not optional and must be filled in.

When I have dataclass:

@dataclass
class A:
  myObject: MyObject = None

Then I have already defined that field myObject is optional and may or may not be filled in.

However default behavior of dacite is to throw this error:

dacite.exceptions.WrongTypeError: wrong value type for field "myObject" - should be "MyObject" instead of value "None" of type "NoneType"

This behavior is nonsense and lead to this redundant and ugly definition:

@dataclass
class A:
  myObject: Optional[MyObject] = None

Can it be fixed?

konradhalas commented 3 years ago

Hi @kacirekj - thank you for using dacite.

No, I can not fix it in dacite because:

1) MyPy behaves in the same way, it raises:

error: Incompatible types in assignment (expression has type "None", variable has type "MyObject")

2) PEP 484 says:

A past version of this PEP allowed type checkers to assume an optional type when the default value is None (...) This is no longer the recommended behavior. Type checkers should move towards requiring the optional type to be made explicit.

I think that dacite should be as close as possible to MyPy and PEP484 when it deals with types.