Advanced features of python function Flashcards
Recursion
Solves complex program
A function invoking itself within its function body
recursion limit can be set
sys.setrecursionlimit(100)
ensure that your recusion invocation is terminated based on some condition
Iterator
Any object that responds to the built in next() function
Generator
Infinite sequences cannot fit in a list because it won’t fit in Python memory
Generators are more memory efficient while generating infinite sequences
Simple way of creating iterators over a sequence
The object of generator is to create an iterator
generator contains It has a yield statement rather than a return statement
Infinite sequences used in for and while loops
it has a yield command in function body
invoking generator function, it return a generator object
The generator remembers the state of the local variables across function invocation
Nested function
defined within the outer function
closures
advanced programming construction decorator
A function nested is called closure
Nested function that can carry local state
closure can refer to local variables defined within outer functions
closure has access to local variables even when the outer function is no longer present in python memory
closures are used in implementing decorators
decorator
decorator add functionality to existing code without modifying the code
decorates any msge
@decorator_1
@decorator_2
def some_function():
print(“Hello”)
Which of the following statement(s) is/are true?
This is referred to as chaining decorators and is valid
decorator_2 will be applied to the function first
Recursive function
Decorators are technique to add functionality to code without modifying the code itself
Can be constructed in such a way that they can be used with functions which have any number of arguments
Are built using closure under the hood
A function which invokes itself within the function body
python has a limit of how many times a function can call itself
The limit is configurable
need to specify a terminating condition
recursive functions may or may not return values
Examples: Printing numbers in ascending order, Find the Fibonacci series