python / cpython

The Python programming language
https://www.python.org
Other
63.39k stars 30.36k forks source link

f-strings and string annotations #77733

Open serhiy-storchaka opened 6 years ago

serhiy-storchaka commented 6 years ago
BPO 33552
Nosy @ericvsmith, @ambv, @serhiy-storchaka

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: ```python assignee = None closed_at = None created_at = labels = ['interpreter-core', 'type-bug', '3.9', '3.10', '3.11'] title = 'f-strings and string annotations' updated_at = user = 'https://github.com/serhiy-storchaka' ``` bugs.python.org fields: ```python activity = actor = 'iritkatriel' assignee = 'none' closed = False closed_date = None closer = None components = ['Interpreter Core'] creation = creator = 'serhiy.storchaka' dependencies = [] files = [] hgrepos = [] issue_num = 33552 keywords = [] message_count = 1.0 messages = ['316886'] nosy_count = 3.0 nosy_names = ['eric.smith', 'lukasz.langa', 'serhiy.storchaka'] pr_nums = [] priority = 'normal' resolution = None stage = None status = 'open' superseder = None type = 'behavior' url = 'https://bugs.python.org/issue33552' versions = ['Python 3.9', 'Python 3.10', 'Python 3.11'] ```

serhiy-storchaka commented 6 years ago

There are problems with converting annotations containing f-strings into strings (from __future__ import annotations). For example f'''{"'"}''' is converted to f'{"\'"}', but the latter is a syntax error.

>>> from __future__ import annotations
>>> x: f'''{"'"}'''
>>> print(__annotations__['x'])
f'{"\'"}'
>>> x: f'{"\'"}'
  File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash

More complex examples:

f"""{"'''"}""" f"""{"'" '"'}""" f"""{"'''"}""" f'''{'"""'}'''

iritkatriel commented 1 month ago

Since 3.12 this fstring is not rejected:

>>> class X:
...   x: f'{"\'"}'
... 
>>> X.__annotations__
{'x': "'"}

>>> from __future__ import annotations
>>> class X:
...   x: f'{"\'"}'
... 
>>> X.__annotations__
{'x': 'f\'{"\\\'"}\''}
ericvsmith commented 1 month ago

I think this can be closed.