Skip to content
IT Vizag
← Advanced Python Features

▶ Sign up free for the video, slides & prompts

The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.

Checking…

Decorators

Lesson 5 of 10 · 2 min read

Wrap functions to add timing, logging or caching.

🎬 Video version coming soon — read it now

A decorator wraps a function to add behaviour, such as timing, logging, caching or access checks, without changing the function's code. You've already used @dataclass and @property. Now you'll write your own.

Functions are objects

🔒 Code example: sign up free (above) to unlock it.

Functions can be stored, passed as arguments and returned from other functions. Decorators depend on this.

A decorator by hand

🔒 Code example: sign up free (above) to unlock it.

timer takes a function and returns a new function, wrapper, that does extra work around the original. *args, **kwargs pass any arguments straight through.

The @ syntax

🔒 Code example: sign up free (above) to unlock it.

@timer above the def means exactly slow_sum = timer(slow_sum). It's just neater.

Keep the function's identity: functools.wraps

🔒 Code example: sign up free (above) to unlock it.

Without @wraps, the decorated function's name and docstring become wrapper's, which confuses debugging and documentation tools. Always add it.

Decorators with arguments

🔒 Code example: sign up free (above) to unlock it.

One more layer: retry(times=5) returns the actual decorator.

Built-in decorators you'll use

  • @functools.lru_cache: remember results of expensive calls (in the Async & Performance course)
  • @staticmethod, @classmethod: methods that don't need an instance
  • @property, @dataclass: from Objects & Classes
  • Frameworks: @app.get("/") in FastAPI, @pytest.fixture in testing
Tip: When you see @something in a library, read it as "this function is being registered with, or wrapped by, something". That one sentence demystifies most framework code.

In one line

A decorator takes a function and returns a wrapped version with extra behaviour; @name applies it, and functools.wraps keeps the original's identity.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend