ericvsmith / dataclasses

Apache License 2.0
587 stars 53 forks source link

Type information lost if using forward reference for type name #136

Closed jbasko closed 6 years ago

jbasko commented 6 years ago

I'm on Python 3.6.6

Maybe I'm using typing incorrectly, but isn't the type information of amount in the code below supposed to not forget that it's an int?

import dataclasses
import typing

Currency = typing.NewType("Currency", str)
Amount = typing.NewType("Amount", int)

@dataclasses.dataclass
class CurrencyAmount:
    currency: Currency
    amount: "Amount"

fields = {f.name: f for f in dataclasses.fields(CurrencyAmount)}

# prints something like <function NewType.<locals>.new_type at 0x10642be18>   - good
print(repr(fields["currency"].type))

# prints 'Amount'  - not good
print(repr(fields["amount"].type))
gvanrossum commented 6 years ago

No, the fields function is supposed to return exactly what you gave it. It is agnostic of the meaning of type hints. To get the actual types of the fields, use typing.get_type_hints(CurrencyAmount) instead. Only that function resolves forward references at runtime.

jbasko commented 6 years ago

Oh, ok. get_type_hints is exactly what I needed, thanks!