With some of the dataclass threads in python-ideas ongoing, I wanted to add another to the fray.

There's an area where typing.get_type_hints on dataclass and __init__ produce inconsistent results. Example:

@dataclass
class Foo:
    x: int = None

>>> typing.get_type_hints(Foo)
{'x': <class 'int'>}

>>> typing.get_type_hints(Foo.__init__)
{'x': typing.Optional[int], 'return': <class 'NoneType'>}

My wish list item would be for the dataclass annotations to match __init__'s.

Rationale: by explicitly specifying a default value of a different type, the resulting type annotation for the field should be a Union of the specified type and the type of the default value.

I might go so far as to say this could be how the type hints of function parameters should be encoded. Example to illustrate my thoughts—it does not work this way presently:

def foo(x: str = 1):
    ...

>>> typing.get_type_hints(foo)
{'x': typing.Union[str, int]}

This example could be construed as an error that a static type checker should catch and flag; if this is the consensus, then I fall back on the proposal to only supporting Union[type, None]—i.e. Optional[type]which is how get_type_hints performs currently.

Thoughts?

Paul