One of the most commonly asked question in Python interviews is "Have you worked with generators? How and what was the need to use it?" This post will try to explore what are they how and why they are used? Basically, Generator in simple terms can be thought as the function which returns series of results instead of one single result. Syntactic difference between function and generator is, Generator uses "yield" keyword instead of "return" keyword. Generators give us an iterator(Something which we can loop on for ex. list or dictionary) so they can be used with looping constructs such as 'for' and 'while' loops. Example: # Define a generator. def generator(number): while True: number += 1 yield number # Use the generator. x = generator(5) # Now calling the decorator print("Calling generator:") x.next() print("Calling generator:")
In this post, we will look at decorators. We will try to address following questions: What are they? Why they are needed? and when are they useful? Ok, let's look at them one by one. First: What are they? Simply put, From what I understand: Decorators are functions that take another function as input and modifies/extends its functionality. Wait...what? A function that takes another as input? Yes, In Python everything is an object (Classes too.). So we can pass a function as arguments. What do you call a function which takes another function as arguments? : Higher order function. Till now all text, no code. Let's look at an example. Let's write a simple decorator: # Create a simple function. def hello(): print("Hello user!.") # Now we Define a decorator. def my_decorator(some_function): def wrapper(): print("I will check if the user is logged in or not before saying hello!") some_function()