我可以将Python 3.6的格式化字符串文字(f字符串)导入较旧的3.x,2.x Python吗? [英] Can I import Python's 3.6's formatted string literals (f-strings) into older 3.x, 2.x Python?

查看:110
本文介绍了我可以将Python 3.6的格式化字符串文字(f字符串)导入较旧的3.x,2.x Python吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对我来说,新的Python 3.6 f字符串在字符串可用性方面似乎是一个巨大的飞跃,我很乐意加入并全心全意地将其应用于可能在较旧的解释器上运行的新项目. 2.7、3.3-3.5支持会很棒,但至少我想在Python 3.5代码库中使用它们.如何导入3.6的格式化字符串文字以供较早的解释程序使用?

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?

我知道像f"Foo is {age} {units} old"这样的格式化字符串文字不会破坏更改,因此不会包含在from __future__ import ...调用中.但是更改不会被反向移植(AFAIK),我需要确保我用f字符串编写的任何新代码都只能在Python 3.6+上运行,这对于许多项目来说都是一个重大问题.

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.

推荐答案

不幸的是,如果要使用它,必须要求Python 3.6+,与矩阵乘法运算符@Python 3.5+yield from相同(Python 3.4+我认为)

Unfortunatly 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)

这些更改了代码的解释方式,因此在较旧版本中导入时会引发SyntaxErrors.这意味着您需要将它们放置在不使用较旧的Python导入或使用evalexec保护的位置(我不建议使用后两个!).

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!).

是的,是的,如果您想支持多个python版本,就不能轻易使用它们.

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

这篇关于我可以将Python 3.6的格式化字符串文字(f字符串)导入较旧的3.x,2.x Python吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆