Skip to content

Commit f28ffe3

Browse files
Better example for W0640: cell-var-from-loop (#8960)
Co-authored-by: Pierre Sassoulas <[email protected]>
1 parent 9d59adc commit f28ffe3

File tree

4 files changed

+53
-10
lines changed

4 files changed

+53
-10
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,23 @@
11
def teacher_greeting(names):
2+
greetings = []
23
for name in names:
34

45
def greet():
6+
# do something
57
print(f"Hello, {name}!") # [cell-var-from-loop]
68

9+
if name.isalpha():
10+
greetings.append(greet)
11+
12+
for greet in greetings:
13+
# the "name" variable is evaluated when the function is called here,
14+
# which is the last value it had in the loop - "Not-A-Name"
715
greet()
816

917

1018
teacher_greeting(["Graham", "John", "Terry", "Eric", "Terry", "Michael"])
19+
# "Hello, Michael!"
20+
# "Hello, Michael!"
21+
# "Hello, Michael!"
22+
# "Hello, Michael!"
23+
# "Hello, Michael!"

doc/data/messages/c/cell-var-from-loop/good.py

Lines changed: 0 additions & 10 deletions
This file was deleted.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import functools
2+
3+
4+
def teacher_greeting(names):
5+
greetings = []
6+
for name in names:
7+
if name.isalpha():
8+
# "name" is evaluated when the partial is created here, so this
9+
# does not do lazy evaluation
10+
greetings.append(functools.partial(print, f"Hello, {name}!"))
11+
12+
for greet in greetings:
13+
# `partial`s are called like functions, but you've already passed the
14+
# arguments to them
15+
greet()
16+
17+
18+
teacher_greeting(["Graham", "John", "Terry", "Eric", "Terry", "Michael"])
19+
# "Hello, Graham!"
20+
# "Hello, John!"
21+
# "Hello, Eric!"
22+
# "Hello, Terry!"
23+
# "Hello, Michael!"
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
def teacher_greeting(names):
2+
def greet(name):
3+
# do something
4+
print(f"Hello, {name}!")
5+
6+
for name in names:
7+
if name.isalpha():
8+
# we're passing the value of "name" to the function here
9+
greet(name)
10+
11+
12+
teacher_greeting(["Graham", "John", "Terry", "Eric", "Terry", "Michael"])
13+
# "Hello, Graham!"
14+
# "Hello, John!"
15+
# "Hello, Eric!"
16+
# "Hello, Terry!"
17+
# "Hello, Michael!"

0 commit comments

Comments
 (0)