yield

yield is a keyword in Python that when used in a function, will return a 202206081814# where no code will be run. Each time when the caller extract an object from the generator, it will proceed to the remaining code of the callee until meet the next yield statement or the end of the function.

The following example shows how it works:

def custom_generator():
  for i in range(3):
    yield i * i   # Everytime the interpreter met the yield statement, it will
                  # pause the execution sequence and return the generator object

my_generator = custom_generator()
for i in my_generator:
  print(i)        # This will print 0, 1, 4 consequently

It is commonly used in #context manager.

Links to this page
  • Python Context Management Protocol

    Instead of using classes, we can import the decorator contextmanager and put it on the function for it to behave as a context manager similar to its class counterpart. This is shown as below, note that it uses 202206081813# keyword:

#python