[Python-Dev] Is static typing still optional?
Terry Reedy
tjreedy at udel.edu
Thu Dec 21 14:55:17 EST 2017
On 12/21/2017 9:23 AM, Eric V. Smith wrote:
>
>
> On 12/21/17 6:25 AM, Sven R. Kunze wrote:
>> On 21.12.2017 11:22, Terry Reedy wrote:
>>>
>>>>> @dataclass
>>>>> class C:
>>>>> a: int # integer field with no default
>>>>> b: float = 0.0 # float field with a default
>>>>>
>>>>> And the types will be recognized by type checkers such as mypy.
>>>>>
>>>>> And I think the non-typed examples should go first in the docs.
>>>
>>
>> I still don't understand why "I don't care" can be defined by "leaving
>> out"
>>
>> @dataclass
>> class C:
>> b = 0.0 # float field with a default
>
> Because you can't know the order that x and y are defined in this example:
>
> class C:
> x: int
> y = 0
>
> 'x' is not in C.__dict__, and 'y' is not in C.__annotations__.
I think the understanding problem with this feature arises from two
factors: using annotations to define possibly un-initialized slots is
non-obvious; a new use of annotations for something other than static
typing is a bit of a reversal of the recent pronouncement 'annotations
should only be used for static typing'. Therefore, getting the
permanent doc 'right' is important.
The following naively plausible alternative does not work and cannot
sensibly be made to work because the bare 'x' in the class scope, as
opposed to a similar error within a method, causes NameError before the
class is created.
@dataclass
class C:
x
y = 0
I think the doc should explicitly say that uninitialized fields require
annotation with something (anything, not necessarily a type) simply to
avoid NameError during class creation. It may not be obvious to some
readers why x:'anything' does not also raise NameError, but that was a
different PEP, and the dataclass doc could here link to wherever
name:annotation in bodies is explained.
--
Terry Jan Reedy
More information about the Python-Dev
mailing list