[Python-Dev] is typing optional in dataclasses?
Eric V. Smith
eric at trueblade.com
Thu Dec 21 20:15:20 EST 2017
On 12/21/2017 7:55 PM, MRAB wrote:
> On 2017-12-22 00:19, Gregory P. Smith wrote:
>> (subject for this sub-thread updated)
>>
>> On Thu, Dec 21, 2017 at 4:08 PM Chris Barker <chris.barker at noaa.gov
>> <mailto:chris.barker at noaa.gov>> wrote:
>>
>> On Thu, Dec 21, 2017 at 3:36 PM, Gregory P. Smith <greg at krypto.org
>> <mailto:greg at krypto.org>> wrote:
>>
>> But we already have ... which does - so I'd suggest that for
>> people who are averse to importing anything from typing and
>> using the also quite readable Any. (ie: document this as the
>> expected practice with both having the same meaning)
>>
>>
>> I don't think they do, actually - I haven't been following the
>> typing discussions, but someone in this thread said that ... means
>> "use the type of teh default" or something like that.
>>
>>
>> indeed, they may not. though if that is the definition is it
>> reasonable to say that type analyzers recognize the potential
>> recursive meaning when the _default_ is ... and treat that as Any?
>>
>> another option that crossed my mind was "a: 10" without using =. but
>> that really abuses __attributes__ by sticking the default value in
>> there which the @dataclass decorator would presumably immediately need
>> to undo and fix up before returning the class. but I don't find
>> assigning a value without an = sign to be pythonic so please lets not
>> do that! :)
>>
> If you allowed "a: 10" (an int value), then you might also allow "a:
> 'foo'" (a string value), but wouldn't that be interpreted as a type
> called "foo"?
As far as dataclasses are concerned, both of these are allowed, and
since neither is ClassVar or InitvVar, they're ignored. Type checkers
would object to the int, and I assume also the string unless there was a
type foo defined. See
https://www.python.org/dev/peps/pep-0484/#the-problem-of-forward-declarations
and typing.get_type_hints().
It's a bug that dataclasses currently does not inspect string
annotations to see if they're actually ClassVar or InitVar declarations.
PEP 563 makes it critical (and not merely important) to look at the
string annotations. Whether or not that involves typing.get_type_hints()
or not, I haven't yet decided. I'm waiting for PEPs 563 and 560 to be
implemented before taking another look at it.
Eric.
>
> If you can't have a string value, then you shouldn't have an int value
> either.
>
> [snip]
>
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> https://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe:
> https://mail.python.org/mailman/options/python-dev/eric%2Ba-python-dev%40trueblade.com
>
More information about the Python-Dev
mailing list