Search⌘ K
AI Features

Decorators for Coroutines

Explore how to create decorators compatible with both regular Python functions and asynchronous coroutines. Learn techniques to properly await coroutines within decorators, maintain function types, and selectively handle timing or other logic. This lesson helps you write reusable decorators that respect Python's async syntax and behavior.

Difficulties with decorating coroutines

Since pretty much everything in Python is an object, pretty much anything can be decorated, and this includes coroutines as well. Coroutines are functions that can be suspended and resumed during execution, and are essential for enabling concurrency in programs.

However, there's a caveat here, and that is that asynchronous programming in Python introduces some differences in syntax. Therefore, these syntax differences will also be carried to the decorator.

Simply speaking, if we were to write a decorator for a coroutine, we could simply adapt to the new syntax. (Remember to await the wrapped coroutine and define the wrapped object as a coroutine itself, ...