Repository navigation
typing: get_type_hints can't handle stringified annotations with leading spaces #90710
Description
Activity
GBeauregard commented
on Jan 27, 2022 GBeauregardmannequinMannequinAuthorMore actionsclass 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.
This is covered in dataclasses unit tests:
cpython/Lib/test/test_dataclasses.py
Line 3033 in 26b0482
' typing.ClassVar[str]',
The relevant failing code in typing.py is here:Line 671 in 26b0482
code = compile(arg, '<string>', 'eval') 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.
- added3.9 (EOL)end of lifeend of life3.10 (EOL)end of lifeend of life3.11only security fixesonly security fixesstdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
on Jan 27, 2022 I vote we don't change this. PEP-484 says:
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.
The dataclasses tests were in fact just added for completeness. I'd be okay with changing dataclasses to reject leading spaces.
We should not accept leading spaces.--
--Guido (mobile)I agree with Jelle and Guido
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields: