Use walrus operator in Python 3.7
If the version of Python you're using doesn't contain an implementation of a feature, then you cannot use that feature; writing from __future__ import ...
cannot cause that feature to be implemented in the version of Python you have installed.
The purpose of __future__
imports is to allow an "opt-in" period for new features which could break existing programs. For example, when the /
operator's behaviour on integers was changed so that 3/2
was 1.5
instead of 1
(i.e. floor division), this would have broken a lot of code if it was just changed overnight. So both behaviours were implemented in the next few versions of Python, and if you were using one of those newer versions then you could choose the new behaviour with from __future__ import division
. But you were only able to do so because the version of Python you were using did implement the new behaviour.
The walrus operator was introduced in Python 3.8, so if you are using a version prior to 3.8 then it does not contain an implementation of that operator, so you cannot use it. There was no need to use __future__
to make the walrus operator "opt-in", since the introduction of a new operator with new syntax could not have broken any existing code.
You can read the PEP that introduced __future__
for insight. Primarily,
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.
The walrus operator is not a backwards-incompatible change: it changes nothing about the meaning of code that was already "working". :=
was just a syntax error before.
So adding it to __future__
was never even considered. You might object that, say, "with" statements were similarly brand new, but that's not entirely so: "with" was not a reserved word, and its introduction could potentially break working code that used "with" as an identifier.
So, sorry, use 3.8 or you're out of luck. Don't shoot the messenger ;-)