[New-bugs-announce] [issue43893] typing.get_type_hints does not accept type annotations with leading whitespaces

Jarry Shaw report at bugs.python.org
Tue Apr 20 09:03:19 EDT 2021


New submission from Jarry Shaw <jarryshaw at icloud.com>:

`typing.get_type_hints` does not accept type annotations (in string capsulated form) with leading whitespaces.

```
>>> def foo(arg) -> ' str': ...
>>> typing.get_type_hints(foo)
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/typing.py", line 519, in __init__
    code = compile(arg, '<string>', 'eval')
  File "<string>", line 1
    str
IndentationError: unexpected indent

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.9/typing.py", line 1448, in get_type_hints
    value = ForwardRef(value)
  File "/usr/local/lib/python3.9/typing.py", line 521, in __init__
    raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
SyntaxError: Forward reference must be an expression -- got ' str'
```

When elaborating on this issue, an inconsistency of hevaiour between ``eval`` function call and ``compile`` in ``'eval'`` mode was also noticed, where the former accepts leading whitespaces and the latter does not.

However, as discussed in https://bugs.python.org/issue41887 , I would then propose manually ``lstrip`` whitespaces from the type annotations:

```
519c519
<             code = compile(arg.lstrip(' \t'), '<string>', 'eval')
---
>             code = compile(arg, '<string>', 'eval')
```

----------
components: Library (Lib)
messages: 391434
nosy: jarryshaw
priority: normal
severity: normal
status: open
title: typing.get_type_hints does not accept type annotations with leading whitespaces
type: behavior
versions: Python 3.10

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


More information about the New-bugs-announce mailing list