MattDMo / PythonImproved

The best Python language definition for Sublime Text - ever. Includes full support for Unicode, as well as both Python 2 and Python 3 syntax. Check out the Neon Color Scheme for highlighting.
https://packagecontrol.io/packages/Python%20Improved
MIT License
93 stars 11 forks source link

Literal string interpolation (f-strings) for Python 3.6 #56

Open MattDMo opened 8 years ago

MattDMo commented 8 years ago

PEP-0498 is due to be implemented in Python 3.6, which is scheduled to be released in December 2016. The PEP describes a new string formatting method, aside from the previously-existing % formatting, str.format(), and string.Template (which I'll admit I've never used). The new strings, which are called "f-strings" (short for _f_ormatting strings) have an f character before the opening quote, and essentially operate like so:

>>> name = "Matt"
>>> age = "too many"
>>> f"Hi, I'm {name} and I'm {age} years old."
"Hi, I'm Matt and I'm too many years old."

Here's a slightly more complex example, from the PEP:

>>> import datetime
>>> name = 'Fred'
>>> age = 50
>>> anniversary = datetime.date(1991, 10, 12)
>>> f'My name is {name}, my age next year is {age+1}, my anniversary is {anniversary:%A, %B %d, %Y}.'
'My name is Fred, my age next year is 51, my anniversary is Saturday, October 12, 1991.'
>>> f'He said his name is {name!r}.'
"He said his name is 'Fred'."

Expressions to be interpolated are inside a single set of curly braces { }, and the string is preceded by either f or F, which can be combined (in any order) with [rR], but not with [uU] or [bB], because reasons. Full expressions are allowed, unlike the rather limited set of expressions allowed with str.format().

So, as far as highlighting is concerned, we'll need to scan f-strings for a single set of braces, scope the contents as string.interpolated.f-string or something, then apply standard highlighting to it. One issue I can foresee is this:

rf"{var_name}\s{1,4}"

although this may be solvable using the .sublime-syntax format. There are also other issues when using multiple sets of braces, as the PEP proposes this:

>>> f'{{ {4*10} }}'
'{ 40 }'
>>> f'{{{4*10}}}'
'{40}'

using double braces to denote a single brace in the output.

There are also format specifiers to be dealt with, and a bunch of other stuff, so read the PEP through several times and let me know your thoughts. We have about a year to do this, so it's pretty low-priority (I'd rather get #38 implemented first), but I just wanted to get this out there to start thinking about it.

reagle commented 7 years ago

Any news?