[issue46552] typing: get_type_hints can't handle stringified annotations with leading spaces

Gregory Beauregard report at bugs.python.org
Thu Jan 27 15:04:08 EST 2022


New submission from Gregory Beauregard <greg at greg.red>:

```
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.

This is covered in dataclasses unit tests: https://github.com/python/cpython/blob/26b0482393a313e3bda364a35e7417e9db52c1c4/Lib/test/test_dataclasses.py#L3033
The relevant failing code in typing.py is here: https://github.com/python/cpython/blob/26b0482393a313e3bda364a35e7417e9db52c1c4/Lib/typing.py#L671

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.

----------
components: Library (Lib)
messages: 411914
nosy: GBeauregard, Jelle Zijlstra, eric.smith
priority: normal
severity: normal
status: open
title: typing: get_type_hints can't handle stringified annotations with leading spaces
type: behavior
versions: Python 3.10, Python 3.11, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46552>
_______________________________________


More information about the Python-bugs-list mailing list