Skip to content
Advertisement

Can you yield from a lambda function?

I have a generator function in a class:

self.s = [['a',1],['b',2],['c',3]

def generator(self):
  for r in self.s:
    yield r

In another function I initalize it as a variable:

var = self.generator()

And it’s yielded as necessary:

>>> next(var) # returns ['a',1]
>>> next(var) # returns ['b',2]
>>> next(var) # returns ['c',3]

Can defining the generator be done in one line, however? I’ve considered the below:

var = lambda: [(yield r) for r in self.s]
>>> next(var) # SyntaxError: 'yield' inside list comprehension

Here’s a minimal code I’m working with:

class Foo():
  def __init__(self):
    self.s = {}

  def generator(self):
    for r in self.s:
      yield r

  def fetch(self):
    if not self.s:
      self.fetch_gen = self.generator()
      self.s['a'] = 1
      self.s['b'] = 2
      self.s['c'] = 3
    try:
      var = self.s.get(next(self.fetch_gen))
    except StopIteration:
      return None
    return var

BAR = Foo()
while True:
  OUT = BAR.fetch()
  if OUT is None:
    break
  print(OUT)

Output is below:

1
2
3

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:

var = (r for r in self.s)

that will generate a generator with the values you want. You test it later with next(var) is in your code.

User contributions licensed under: CC BY-SA
11 People found this is helpful
Advertisement