Unit 15Python Advanced Concepts
Follows IGNOU MCS-201, Unit 15
This unit covers four features that make Python code shorter, more reusable and more efficient. Decorators add behaviour to existing functions without changing their code. Iterators explain how every for loop really works. Generators produce values one at a time, saving memory. Coroutines let one program juggle many waiting tasks, such as network requests, without threads. Each builds on the idea from Unit 11 that functions are objects.
In this unit you will learn to
- Compare built-in, user-defined and lambda functions, and write decorators with and without the
@syntax. - Explain the iterator protocol, the difference between an iterable and an iterator, and how a
forloop usesiter()andnext(). - Write generator functions with
yieldand generator expressions, and explain why they save memory. - Explain coroutines and cooperative multitasking, and compare coroutines with subroutines and threads.
- Write and run asynchronous coroutines with
async,await,asyncio.run()andasyncio.create_task().
Sections in this unit
- 15.1DecoratorsBuilt-in, user-defined and lambda functions revised, and decorators that add behaviour to a function without changing its code, with and without @.12 min
- 15.2Iterables and IteratorsThe iterator protocol behind every for loop: iterables, iterators, iter() and next(), StopIteration, built-in iterators and writing an iterator class.9 min
- 15.3GeneratorsGenerator functions with yield and generator expressions, how a generator pauses and resumes, why generators save memory, and when to use lists instead.9 min
- 15.4Coroutines and Cooperative MultitaskingWhat coroutines are, how they differ from subroutines and threads, cooperative multitasking, and generator-based coroutines that receive data with send().10 min
- 15.5Asynchronous Coroutines with asyncioWriting native coroutines with async def and await, running them with asyncio.run, and running several concurrently with asyncio.create_task and gather.9 min