Search code examples
pythonstringf-string

Can I import Python's 3.6's formatted string literals (f-strings) into older 3.x, 2.x Python?


The new Python 3.6 f-strings seem like a huge jump in string usability to me, and I would love to jump in and adopt them whole heartedly on new projects which might be running on older interpreters. 2.7, 3.3-3.5 support would be great but at the very least I would like to use these in Python 3.5 code bases. How can I import 3.6's formatted string literals for use by older interpreters?

I understand that formatted string literals like f"Foo is {age} {units} old" are not breaking changes, so would not be included in a from __future__ import ... call. But the change is not back-ported (AFAIK) I would need to be sure that whatever new code I write with f-strings is only ran on Python 3.6+ which is a deal breaker for a lot of projects.


Solution

  • Unfortunately if you want to use it, you must require Python 3.6+, same with the matrix multiplication operator @ and Python 3.5+ or yield from (Python 3.4+ I think)

    These made changes to how the code is interpreted and thus throw SyntaxErrors when imported in older versions. That means you need to put them somewhere where these aren't imported in older Pythons or guarded by an eval or exec (I wouldn't recommend the latter two!).

    So yes, you are right, if you want to support multiple python versions you can't use them easily.