Decorators and Generators in Python

  • Decorators allow us to change the behavior of existing functions or classes by adding new functionality to them.
  • To add the new functionality to the existing function, you need to pass that function as an argument in the decorator function, and call it inside the inner function of the decorator.
  • A function can be decorated by using the @ symbol along with the name of the decorator function and placing it above that function definition which you want to decorate.

Python implementation

Generators

Python generators are functions that are similar to normal functions, but use yield statements instead of return statements.

A generator function returns the generator object with a sequence of elements, which we can iterate over.

Element in a generator object can be accessed either by using the next() function or using a for loop.

Creating generator:

Accessing generator element using next():

Accessing generator element using for loop:

The generator object can be iterated only once. As you can see, in previous example we iterated over generated object two times but the generator elements are printed only once which illustrated that we can iterate over generator object only once.

So to iterate over generator again, we need to create another generator object as shown in this example.

Generator expression

Generator expression provides an easy and concise way to create generators without defining the generator function.

Generator expression is similar to the list comprehension in Python. But the only difference is that it uses round parenthesis instead of square brackets.

A list comprehension produces the entire list, whereas the generator expression doesn’t produce the immediate result instead it returns the generator object and produce one item at a time (only when asked for).

Popular Posts

Spread the knowledge
 
  

Leave a Reply

Your email address will not be published. Required fields are marked *