Python
Programming
Coding
Syntax
Python Functions

What does the at (@) symbol do in Python?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

The "at" (@) symbol in Python, commonly known as the decorator symbol, is a powerful feature that allows developers to modify the behavior of functions or classes. The @ symbol is placed before a function, indicating that a decorator is being applied. Decorators have the ability to run additional code before and after the function they decorate, without modifying the function itself. This enables more modular and expressive code.

What is a Decorator?

In Python, decorators are essentially functions that add functionality to an existing function or method, without changing its structure. The typical structure of a decorator involves a higher-order function, a function that takes one or more functions as inputs and returns a new function.

Basic Example of a Decorator

Here is a simple example of a decorator that logs the activity of a function:

python
1def my_decorator(func):
2    def wrapper():
3        print("Something is happening before the function is called.")
4        func()
5        print("Something is happening after the function is called.")
6    return wrapper
7
8@my_decorator
9def say_hello():
10    print("Hello!")
11
12say_hello()

When say_hello() is called, the output will be:

 
Something is happening before the function is called.
Hello!
Something is happening after the function is called.

Using Decorators with Parameters

More complex decorators can also accept arguments. To do this, you need another level of function nesting:

python
1def repeat(num_times):
2    def decorator_repeat(func):
3        def wrapper(*args, **kwargs):
4            for _ in range(num_times):
5                result = func(*args, **kwargs)
6            return result
7        return wrapper
8    return decorator_repeat
9
10@repeat(num_times=3)
11def greet(name):
12    print(f"Hello {name}")
13
14greet("Alice")

This will output "Hello Alice" three times.

Decorators in Python Standard Library

Python's standard library comes with several built-in decorators, like @staticmethod, @classmethod, and @property.

  • @staticmethod is used to declare a method as a static method, which means it doesn't operate on an instance of the class nor modify the class state.
  • @classmethod modifies a method to pass the class itself as the first argument instead of an instance of the class.
  • @property allows a method to be accessed like an attribute instead of as a method with parentheses.

Summary in a Table

DecoratorDescriptionTypical Use Case
@staticmethodConverts a method into a static method, without class scope.Methods not modifying class instance.
@classmethodA method that receives the class as implicit first argument.Factory methods.
@propertyMakes a method accessible as an attribute.Simplifies access to calculations.

Advanced Decorator Concepts

Decorators can also be used to manage authentication, enforce permissions, cache results, and log operations in a uniform way across multiple functions or classes.

Conclusion

The @ symbol in Python is not only syntactically elegant but also extremely powerful, providing developers with a flexible tool to adhere to the DRY (Don't Repeat Yourself) principle and extend functionality without modifying existing code. It is a hallmark of Python's support for writing clean, efficient, and reusable code.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.