在 Python 3.7 中使用海象运算符
Use walrus operator in Python 3.7
为什么未来的导入仅限于某些功能?在Python 3.7 中没有办法获得海象运算符吗?我认为这行得通,但行不通:
from __future__ import walrus
它不起作用,因为海象不在支持的功能列表中:
__future__.all_feature_names
['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL', 'generator_stop', 'annotations']
除了使用 python 3.8 之外,还有其他选择吗?
您可以 read the PEP 介绍 __future__
以获取见解。首先,
From time to time, Python makes an incompatible change to the advertised semantics of core language constructs, or changes their accidental (implementation-dependent) behavior in some way. While this is never done capriciously, and is always done with the aim of improving the language over the long term, over the short term it's contentious and disrupting.
海象运算符不是向后不兼容的更改:它对已经“工作”的代码的含义没有任何改变。 :=
之前只是语法错误。
所以从来没有考虑过将它添加到 __future__
。你可能会反对,比如说,“with”语句同样是全新的,但并非完全如此:“with”不是保留字,它的引入可能会破坏使用“with”作为标识符的工作代码。
所以,抱歉,请使用 3.8,否则你就不走运了。不要开枪 ;-)
如果您使用的 Python 版本不包含某个功能的实现,那么您将无法使用该功能;编写 from __future__ import ...
不会导致该功能在您安装的 Python 版本中实现。
__future__
导入的目的是为可能破坏现有程序的新功能留出 "opt-in" 期限。例如,当 /
运算符对整数的行为发生变化时,3/2
变为 1.5
而不是 1
(即底除法),这会破坏很多代码如果只是一夜之间改变。因此 两种行为都在 Python 的下几个版本中实现,如果您使用的是其中一个较新的版本,那么您可以使用 from __future__ import division
选择新行为.但是您之所以能够这样做,是因为您使用的 Python 版本 确实 实现了新行为。
walrus 运算符是在 Python 3.8 中引入的,因此如果您使用的是 3.8 之前的版本,则它不包含该运算符的实现,因此您不能使用它。无需使用 __future__
来创建海象运算符 "opt-in",因为引入具有新语法的新运算符不会破坏任何现有代码。
为什么未来的导入仅限于某些功能?在Python 3.7 中没有办法获得海象运算符吗?我认为这行得通,但行不通:
from __future__ import walrus
它不起作用,因为海象不在支持的功能列表中:
__future__.all_feature_names
['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals', 'barry_as_FLUFL', 'generator_stop', 'annotations']
除了使用 python 3.8 之外,还有其他选择吗?
您可以 read the PEP 介绍 __future__
以获取见解。首先,
From time to time, Python makes an incompatible change to the advertised semantics of core language constructs, or changes their accidental (implementation-dependent) behavior in some way. While this is never done capriciously, and is always done with the aim of improving the language over the long term, over the short term it's contentious and disrupting.
海象运算符不是向后不兼容的更改:它对已经“工作”的代码的含义没有任何改变。 :=
之前只是语法错误。
所以从来没有考虑过将它添加到 __future__
。你可能会反对,比如说,“with”语句同样是全新的,但并非完全如此:“with”不是保留字,它的引入可能会破坏使用“with”作为标识符的工作代码。
所以,抱歉,请使用 3.8,否则你就不走运了。不要开枪 ;-)
如果您使用的 Python 版本不包含某个功能的实现,那么您将无法使用该功能;编写 from __future__ import ...
不会导致该功能在您安装的 Python 版本中实现。
__future__
导入的目的是为可能破坏现有程序的新功能留出 "opt-in" 期限。例如,当 /
运算符对整数的行为发生变化时,3/2
变为 1.5
而不是 1
(即底除法),这会破坏很多代码如果只是一夜之间改变。因此 两种行为都在 Python 的下几个版本中实现,如果您使用的是其中一个较新的版本,那么您可以使用 from __future__ import division
选择新行为.但是您之所以能够这样做,是因为您使用的 Python 版本 确实 实现了新行为。
walrus 运算符是在 Python 3.8 中引入的,因此如果您使用的是 3.8 之前的版本,则它不包含该运算符的实现,因此您不能使用它。无需使用 __future__
来创建海象运算符 "opt-in",因为引入具有新语法的新运算符不会破坏任何现有代码。