I have a generator function in a class:
JavaScript
x
6
1
self.s = [['a',1],['b',2],['c',3]
2
3
def generator(self):
4
for r in self.s:
5
yield r
6
In another function I initalize it as a variable:
JavaScript
1
2
1
var = self.generator()
2
And it’s yielded as necessary:
JavaScript
1
4
1
>>> next(var) # returns ['a',1]
2
>>> next(var) # returns ['b',2]
3
>>> next(var) # returns ['c',3]
4
Can defining the generator be done in one line, however? I’ve considered the below:
JavaScript
1
3
1
var = lambda: [(yield r) for r in self.s]
2
>>> next(var) # SyntaxError: 'yield' inside list comprehension
3
Here’s a minimal code I’m working with:
JavaScript
1
27
27
1
class Foo():
2
def __init__(self):
3
self.s = {}
4
5
def generator(self):
6
for r in self.s:
7
yield r
8
9
def fetch(self):
10
if not self.s:
11
self.fetch_gen = self.generator()
12
self.s['a'] = 1
13
self.s['b'] = 2
14
self.s['c'] = 3
15
try:
16
var = self.s.get(next(self.fetch_gen))
17
except StopIteration:
18
return None
19
return var
20
21
BAR = Foo()
22
while True:
23
OUT = BAR.fetch()
24
if OUT is None:
25
break
26
print(OUT)
27
Output is below:
JavaScript
1
4
1
1
2
2
3
3
4
I just wanted to see if I could get rid of Foo.generator
and instead declare the generator in one line.
Advertisement
Answer
You are returning a list comprehension. You can just do:
JavaScript
1
2
1
var = (r for r in self.s)
2
that will generate a generator with the values you want. You test it later with next(var)
is in your code.