You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
typing: get_type_hints can't handle stringified annotations with leading spaces #90710
class C:
a: " ClassVar[int]" = 3
get_type_hints(C, globals()) # SyntaxError: Forward reference must be an expression -- got ' ClassVar[int]'
I discovered while investigating the viability of moving dataclasses.py to using typing.py's internal type introspection tools that it can't handle stringified annotations with leading spaces.
Leading spaces are treated like indention so there's a syntax error.
This would be trivial to fix by adding an lstrip() to the compilation code, but it's not clear to me this should be considered a bug. Should this be left as-is, or changed? I'm happy to submit a patch if there's agreement it's a bug.
The string literal should contain a valid Python expression (i.e., compile(lit, '', 'eval') should be a valid code object) and it should evaluate without errors once the module has been fully loaded.
But compile() fails for leading whitespace.
I also don't see a real use case for this. The dataclasses tests were presumably just added for completeness. If there's evidence this is a common pattern in the wild maybe we can reconsider.
Activity
GBeauregard commentedon Jan 27, 2022
I discovered while investigating the viability of moving dataclasses.py to using typing.py's internal type introspection tools that it can't handle stringified annotations with leading spaces.
This is covered in dataclasses unit tests:
cpython/Lib/test/test_dataclasses.py
Line 3033 in 26b0482
The relevant failing code in typing.py is here:
cpython/Lib/typing.py
Line 671 in 26b0482
Leading spaces are treated like indention so there's a syntax error.
This would be trivial to fix by adding an lstrip() to the compilation code, but it's not clear to me this should be considered a bug. Should this be left as-is, or changed? I'm happy to submit a patch if there's agreement it's a bug.
JelleZijlstra commentedon Jan 27, 2022
I vote we don't change this. PEP-484 says:
But compile() fails for leading whitespace.
I also don't see a real use case for this. The dataclasses tests were presumably just added for completeness. If there's evidence this is a common pattern in the wild maybe we can reconsider.
ericvsmith commentedon Jan 27, 2022
The dataclasses tests were in fact just added for completeness. I'd be okay with changing dataclasses to reject leading spaces.
gvanrossum commentedon Jan 27, 2022
We should not accept leading spaces.--
--Guido (mobile)
AlexWaygood commentedon Jan 27, 2022
I agree with Jelle and Guido