100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
HomeBlogPython Decorators Explained With Examples
Programming

Python Decorators Explained With Examples

SV

SkillVeris Team

Engineering Team

Mar 13, 2026 12 min read
Share:
Python Decorators Explained With Examples
Key Takeaway

A decorator is a function that takes another function and returns an enhanced version of it.

In this guide, you'll learn:

  • The at-symbol syntax is convenient shorthand for wrapping a function with a decorator.
  • Decorators shine for cross-cutting concerns like logging, timing, caching, and access control.
  • Understanding that functions are first-class objects in Python is the key to understanding decorators.

1What Is A Decorator

A Python decorator is a function that takes another function as input and returns a new function that usually adds some behavior around the original. It lets you extend or modify what a function does without editing the function's own code. You apply a decorator by writing its name with an at symbol on the line above a function definition, and from then on calling that function runs the wrapped, enhanced version.

The purpose is to handle concerns that would otherwise be repeated across many functions, such as logging every call, measuring how long a function takes, checking permissions, or caching results. Instead of pasting the same setup and teardown into every function, you write it once in a decorator and apply that decorator wherever it is needed. This keeps the core logic clean and the shared behavior in one place.

Decorators can look like magic at first, but they rest on a few simple ideas about how Python treats functions. Once those ideas are clear, the at-symbol syntax reveals itself as a tidy shorthand for something you could write by hand, and decorators become a natural, readable tool rather than a mysterious feature.

2Functions Are First-Class Objects

The foundation of decorators is that in Python, functions are first-class objects. This means a function is a value like any other: you can assign it to a variable, store it in a list, pass it as an argument to another function, and return it from a function. A function name without parentheses refers to the function itself, while adding parentheses calls it.

Because functions can be passed around, you can write a function whose job is to accept another function and do something with it. And because functions can be returned, you can write a function that builds and hands back a brand new function. Combine these two abilities and you have everything you need to wrap one function inside another, which is exactly what a decorator does.

Getting comfortable with this idea is the single biggest step toward understanding decorators. Practice passing functions as arguments and returning them from other functions until it feels ordinary, and the rest of decorators will follow almost automatically.

3Nested Functions And Closures

Decorators also rely on nested functions and closures. You can define a function inside another function, and the inner function has access to the variables of the outer one, including the function that was passed in. When the outer function returns the inner function, that inner function remembers the environment it was created in, a behavior called a closure.

This memory is what lets a decorator wrap a specific function. The outer decorator receives the original function, defines an inner wrapper that calls it while adding behavior, and returns that wrapper. The wrapper carries a reference to the original function inside its closure, so whenever the wrapper runs, it knows exactly which function to call in the middle.

Closures might sound abstract, but they are what make decorators reusable and self-contained. Each time you apply a decorator to a different function, a fresh closure captures that particular function, so the same decorator can wrap many functions independently without any interference between them.

4Writing Your First Decorator

A basic decorator is a function that accepts a function and returns a wrapper. Inside the wrapper you typically do something before calling the original function, then call it, then optionally do something after. For example, a logging decorator might print a message announcing the call, run the real function, and print another message when it finishes, all without the original function knowing.

To apply it, you place the decorator name with an at symbol on the line above the function you want to enhance. This syntax is exactly equivalent to defining the function normally and then reassigning its name to the result of passing it through the decorator. The at-symbol form is simply a cleaner way to express that same idea right where the function is defined.

Writing one simple decorator by hand demystifies the whole concept. Once you see that the wrapper is just an ordinary inner function that calls the original with a little extra behavior around it, decorators stop feeling special and start feeling like a convenient pattern you fully understand.

5Handling Arguments

Real functions take arguments, so a useful decorator must pass them through. The wrapper accepts flexible arguments, commonly written as args and keyword args, and forwards them to the original function unchanged. This way the same decorator works on functions with any number of parameters, from none to many, without needing to know their signatures in advance.

The wrapper should also return whatever the original function returns, so the decorated function behaves like the original from the caller's point of view. Forgetting to return the result is a common beginner bug that makes the decorated function silently produce nothing. A correct wrapper captures the return value, optionally acts on it, and hands it back.

By accepting and forwarding arbitrary arguments and returning the result, your decorator becomes truly general. This generality is what lets a single logging or timing decorator be applied across an entire codebase, regardless of what each individual function looks like.

6Preserving Function Metadata

When you wrap a function, the new wrapper replaces the original, which means the function's name, documentation string, and other metadata get hidden behind the wrapper's. Tools that inspect functions, generate documentation, or debug your code may then see the wrapper's generic name instead of the real one, which is confusing.

Python's standard library solves this with a helper that copies the original function's identity onto the wrapper. Applying this helper inside your decorator restores the original name and documentation, so from the outside the decorated function looks and identifies exactly like the original. This small step is considered a best practice for any decorator you intend to reuse.

Preserving metadata is easy to overlook because code works without it, but it pays off the moment you debug or document a decorated function. Making it a habit ensures your decorators are polite citizens that do not distort the identity of the functions they enhance.

7Practical Uses

Decorators earn their keep on cross-cutting concerns, behaviors that many functions need but that do not belong in any single function's core logic. Logging is a classic example: a decorator can record every call and its result without cluttering the functions themselves. Timing is another, measuring how long a function takes so you can find slow spots across a whole program.

Caching is a particularly satisfying use. A decorator can remember the results of previous calls and return the stored answer when the same inputs come again, saving expensive recomputation. Access control is another common case, where a decorator checks whether the current user is allowed to run a function before letting the call proceed.

Because these concerns recur throughout real applications, decorators become a favorite tool for keeping code both clean and consistent. The behavior lives in one well-tested place, and applying it is as simple as adding one line above a function definition.

8Decorators That Take Arguments

Sometimes you want to configure a decorator, such as a retry decorator that should attempt a call a certain number of times, or a cache with a size limit. This requires a decorator that itself takes arguments, which adds one more layer of nesting. You write a function that accepts the configuration and returns a decorator, which in turn returns the wrapper.

The extra layer can be confusing because there are now three nested functions: the outermost takes the settings, the middle takes the function, and the innermost is the wrapper that runs at call time. Reading it slowly from the outside in makes the structure clear, and the payoff is a flexible decorator you can tune each time you apply it.

This pattern shows the true power of first-class functions and closures working together. Each layer captures what it needs, so the final wrapper has access to both the configuration and the original function. Once you can read this three-layer form comfortably, you understand decorators thoroughly.

9Stacking Decorators

You can apply more than one decorator to a single function by stacking them, writing several at-symbol lines above the definition. Each decorator wraps the result of the one below it, so the order matters. The decorator closest to the function is applied first, and the ones above it wrap that result in turn, forming layers like an onion.

This layering lets you compose behaviors cleanly. You might combine a logging decorator, a timing decorator, and an access-control decorator on the same function, each adding its own concern. Because each decorator is independent and reusable, mixing and matching them is straightforward once you keep the application order in mind.

The main caution is to think about order deliberately. Whether logging happens inside or outside timing, for instance, changes what gets measured and recorded. Being intentional about the sequence prevents surprises and lets you get exactly the layered behavior you intend.

10Common Mistakes

The most frequent decorator bug is a wrapper that forgets to return the original function's result, causing the decorated function to silently return nothing. Always capture and return the result unless you have a deliberate reason not to. This single omission accounts for a large share of decorator confusion among beginners.

Another common mistake is not forwarding arguments correctly, so the decorator only works on functions with a specific signature. Accepting flexible arguments and passing them through keeps your decorator general and reusable. Similarly, forgetting to preserve the original function's metadata leads to confusing names and missing documentation later.

Finally, beginners sometimes reach for decorators when a simpler approach would do. Decorators are best for behavior that genuinely repeats across many functions. If only one function needs the extra logic, writing it directly is clearer. Reserving decorators for true cross-cutting concerns keeps your code both clean and honest.

11Built-In Decorators

Python and its standard library ship with useful decorators you will meet often. Some mark methods that belong to a class rather than an instance, others turn a method into something you access like a simple attribute, and still others provide ready-made caching so you do not have to write it yourself. Recognizing these when you see them helps you read real code.

Frameworks lean heavily on decorators too. Web frameworks commonly use them to connect a function to a URL, so a single decorator line declares that a function handles requests to a particular address. Testing tools use decorators to mark or configure tests. Encountering these in the wild reinforces how central the pattern is across the Python ecosystem.

Seeing decorators used throughout libraries and frameworks confirms that they are not an obscure trick but a mainstream tool. The same understanding you build writing your own decorators lets you read and use these built-in and framework decorators with confidence.

12Practice Writing Decorators

Decorators become intuitive only through writing them. Start by building a simple logging decorator, then extend it to forward arguments and return results, then preserve metadata, and finally try a decorator that takes its own arguments. Apply your decorators to a few different functions and stack a couple together to feel how the layers combine.

SkillVeris walks you through this progression with hands-on exercises that move from first-class functions and closures to real, reusable decorators for logging, timing, and caching. Each concept in this article maps to a task you can run and inspect. Write a decorator, apply it to your own functions, and let the immediate feedback turn the pattern from mysterious to obvious.

📄

Get The Print Version

Download a PDF of this article for offline reading.

About the Publisher

SV

SkillVeris Team

Engineering Team

Our engineering writers turn abstract code concepts into hands-on, project-driven learning experiences.

View all posts

Never miss an update

Get the latest tutorials and guides delivered to your inbox.

No spam. Unsubscribe anytime.

Frequently Asked Questions

21 categories · pick one to explore

Does SkillVeris have a tech blog, and what does it cover?
Yes, the SkillVeris blog has over 500 articles covering AI and machine learning, programming, web development, DevOps, cloud, security, databases and career guidance. Articles are practical and answer-first, and many use the Learn Through Hobbies approach, teaching technical concepts through cricket, music, gaming or cooking analogies. Everything is free to read.
What is the SkillVeris tech glossary and how big is it?
The SkillVeris glossary is a free reference of roughly 2,000-plus technology terms, each with a clear plain-language definition. It spans AI, programming, web, DevOps, cloud, security and database vocabulary, so whenever a lesson, article or job description uses jargon you do not recognise, the glossary gives you a fast, reliable answer.
Are the developer cheat sheets on SkillVeris free to download?
The cheat sheets are completely free to use, like everything else on SkillVeris. Each sheet condenses a language or tool into its essential syntax, commands and patterns for quick reference while coding. They are designed for rapid lookup during real work, complementing the deeper explanations found in study notes and courses.
Which programming references and cheat sheets are available?
Cheat sheets cover the platform's main domains, including programming languages, AI and ML tooling, web development, DevOps, cloud, security and databases, matching the topics of the 37 live courses. Each sheet lists related reading links and hashtags, so you can jump from a quick reference into fuller study notes or blog articles.
How do I find the meaning of a technical term quickly?
Search the SkillVeris glossary, which holds around 2,000-plus terms with concise, plain-language definitions. Each entry gets to the point in its first sentence, then links to related reading like blog posts or study notes for deeper context. It is faster and more consistent than sifting through scattered search results.
Is the SkillVeris blog good for beginners learning to code?
Yes, many blog articles are written specifically for beginners, and the Learn Through Hobbies style makes them unusually approachable: you might learn Python concepts through cricket or understand APIs through cooking. With 500-plus articles across skill levels, beginners can start with fundamentals and keep reading as they advance, entirely free.
Can cheat sheets replace full courses for learning a language?
No, cheat sheets are references, not teaching tools; they assume you already understand the concepts and just need syntax or commands fast. To actually learn a language, take a structured SkillVeris course with its 24–40 lessons and assessments, then keep the cheat sheet beside you while practising in Code Lab.
How often are new blog articles published on SkillVeris?
The blog grows regularly and already exceeds 500 articles, with new posts added as courses launch and technologies evolve. Topics track the platform's catalogue across AI, programming, web development, DevOps, cloud and security, so checking the Blog section periodically surfaces fresh tutorials, explainers and career-focused pieces, all free to read.
Does the glossary cover AI and machine learning terms?
Yes, AI and machine learning vocabulary is a major part of the roughly 2,000-plus term glossary, covering everything from foundational terms to modern concepts around LLMs, RAG and MLOps. Definitions are plain-language and answer-first, which helps when dense AI papers or course lessons throw unfamiliar jargon at you.
Are there cheat sheets for interview preparation?
Cheat sheets work well as interview-day refreshers because they compress syntax, commands and key concepts into scannable references. For dedicated preparation, combine them with the SkillVeris interview questions feature, which includes readiness scoring, plus study notes for depth. Reviewing a relevant cheat sheet just before an interview steadies recall under pressure.
Can I read the tech blog without signing up?
Yes, the blog is freely readable, and SkillVeris never charges for content. All 500-plus articles are open, covering tutorials, concept explainers and career advice. Creating a free account adds value elsewhere on the platform, like course progress tracking and certificates, but reading the blog requires no commitment at all.
How is the SkillVeris glossary different from Wikipedia?
The glossary is purpose-built for learners: definitions are short, plain-language and answer-first, sized for a quick lookup mid-lesson rather than a deep encyclopedic read. Entries also cross-link to related SkillVeris study notes, blog posts and courses, so a definition becomes a doorway into structured learning instead of a dead end.
Do blog articles use the Learn Through Hobbies method?
Many blog articles teach technical topics through hobby analogies, a hallmark of the SkillVeris blog, so you will find articles explaining programming through cricket, machine learning through music, or system design through cooking. The analogy is the teaching device; the article still delivers the real technical concept underneath.
Where can I find quick programming references while coding?
Open the SkillVeris cheat sheets, which are built exactly for that moment: compact, scannable references for syntax, commands and common patterns across languages and tools. Keep the relevant sheet in a browser tab while you work in Code Lab or your own editor, and dip into the glossary for terminology.
Is there a glossary entry for terms I meet in job descriptions?
Very likely yes, with roughly 2,000-plus terms across AI, programming, web, DevOps, cloud, security and databases, the glossary covers most jargon that appears in tech job descriptions. Decoding a listing this way helps you judge role fit honestly and prepares you to discuss those terms in interviews.
Are the blog articles written for the Indian tech audience?
The blog serves Indian learners plus a worldwide audience. Content stays globally relevant while acknowledging realities that matter in India, such as free access being essential for students and freshers, and career guidance that connects naturally to the SkillVeris jobs portal, which aggregates roles across India, UK, USA, Germany and Remote.
Can I suggest a topic for the blog or glossary?
SkillVeris content grows in response to what learners need, so feedback is welcome through the platform's support channels. If a term is missing from the glossary or a topic deserves an article, telling the team helps prioritise it. Meanwhile, the AI Mentor can answer the question immediately, 24/7, at any depth.
Do cheat sheets and glossary entries link to deeper learning?
Yes, every cheat sheet and glossary entry carries related reading links into study notes, blog articles and courses, plus concept hashtags for discovering similar content. This cross-linking means a thirty-second lookup can smoothly become a structured learning session whenever you decide you want more than a quick answer.
What makes SkillVeris programming references trustworthy?
The references are written to strict internal quality standards, kept consistent with the platform's 37 live courses, and never padded with invented statistics or hype. Definitions and cheat sheets are reviewed against the same content contracts that govern courses, and the answer-first style makes any inaccuracy easy to spot and correct.
How do the blog, glossary and cheat sheets fit into my learning routine?
Use them as satellites around your main course: read blog articles for context and motivation, hit the glossary the instant jargon appears, and keep cheat sheets open while coding. Together with study notes, Code Lab and the 24/7 AI Mentor, they turn passive reading into a complete, free learning system.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse