Python Decorators

Reading time ~3 minutes

Main Course Link

This Series is a part of 30 Days of Learning.

The course is based on an older python version and the code is incompatible with the latest version.

Python Generators

  • Used for creating iterator operator. Not using a loop for interaction.
  • It maintains the state of the last operation.
  • Has a lazy evaluation
  • Iterators have the next () function, even the for loop uses iterators in the backed
  • Use of keyword yield. (Not return as other functions)
  • Generator function return the generator object which we can use in our code.
  • Generator objects cannot be reused.

Example as a list comprehension: (item for item in collection), we use () to create a generator object.

# Create Generator 

intg = (n for n in [1,2,3,1,3])

print (intg)

# Get Generated Objects
print (
print (
print (

# Get Remaining Items
print (list(intg))

# This will run into issues as now there nothing left in the generator
print (

Example: Fibonacci Series using Generators.

def fibb():
    tail, lead = 0,1
    while True:
        yield lead
        tail, lead = lead, tail + lead
fib = fibb()  

Generators pipelines: We can use package multiple generator objects to create a pipeline.

Context Manager:

Python Object that acts as a control manager. Python snippet with open (file) is a Content manager. This with open clause can be implemented as below.

Basic Framework for Context Manager

# Context Manager Decorator
def simple_context_manager(gen_obj):
        # Change the Object Value
        obj.prop +=1
        # Yield Control back to Caller 
        # Bring Object back to its original Value
        obj.prop -=1

Note: Context Manager is used with the with Python Block.


  • Receives Value
  • Different from Generator
  • Persists the properties of an object, unlike functions.
  • We have send method to send to coroutine.
  • We can use the co-routine decorators to skip the use of the next() primer.
  • We can also use and create Coroutines pipelines.
def coroutine(string):
    count = 0
    try : 
        while True:
            item = yield
            if isinstance(item, str):
                if item in string:
                    print item
                    print "No match found"
                print "Please enter String"
    except GeneratorExit:
        print ("Closed Coroutine")
c_obj = coroutine("Yogesh")

Python GUI Development: Tkinter

[Main Course Link]( Series is a part of [30 Days of Learning]...… Continue reading

Effective Note Taking

Published on June 20, 2021

Python Web Scraping

Published on June 19, 2021