@@ -151,66 +151,15 @@ to tell Python which namespace to use.
151151Why can't I use an assignment in an expression?
152152-----------------------------------------------
153153
154- Many people used to C or Perl complain that they want to use this C idiom:
154+ Starting in Python 3.8, you can!
155155
156- .. code-block :: c
156+ Assignment expressions using the walrus operator `:= ` assign a variable in an
157+ expression::
157158
158- while (line = readline(f)) {
159- // do something with line
160- }
161-
162- where in Python you're forced to write this::
163-
164- while True:
165- line = f.readline()
166- if not line:
167- break
168- ... # do something with line
169-
170- The reason for not allowing assignment in Python expressions is a common,
171- hard-to-find bug in those other languages, caused by this construct:
172-
173- .. code-block :: c
174-
175- if (x = 0) {
176- // error handling
177- }
178- else {
179- // code that only works for nonzero x
180- }
181-
182- The error is a simple typo: ``x = 0 ``, which assigns 0 to the variable ``x ``,
183- was written while the comparison ``x == 0 `` is certainly what was intended.
184-
185- Many alternatives have been proposed. Most are hacks that save some typing but
186- use arbitrary or cryptic syntax or keywords, and fail the simple criterion for
187- language change proposals: it should intuitively suggest the proper meaning to a
188- human reader who has not yet been introduced to the construct.
189-
190- An interesting phenomenon is that most experienced Python programmers recognize
191- the ``while True `` idiom and don't seem to be missing the assignment in
192- expression construct much; it's only newcomers who express a strong desire to
193- add this to the language.
194-
195- There's an alternative way of spelling this that seems attractive but is
196- generally less robust than the "while True" solution::
197-
198- line = f.readline()
199- while line:
200- ... # do something with line...
201- line = f.readline()
202-
203- The problem with this is that if you change your mind about exactly how you get
204- the next line (e.g. you want to change it into ``sys.stdin.readline() ``) you
205- have to remember to change two places in your program -- the second occurrence
206- is hidden at the bottom of the loop.
207-
208- The best approach is to use iterators, making it possible to loop through
209- objects using the ``for `` statement. For example, :term: `file objects
210- <file object> ` support the iterator protocol, so you can write simply::
159+ while chunk := fp.read(200):
160+ print(chunk)
211161
212- for line in f:
213- ... # do something with line...
162+ See :pep: `572 ` for more information.
214163
215164
216165
0 commit comments