Python
Programming
Python Syntax
Decorators
Python Operators

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 is known as the "at sign" and serves several purposes depending on the context in which it is used. This article covers the various functionalities and use cases of the "at" symbol in Python, including decorators, matrix multiplication, and its role in special contexts within the language.

Decorators

What are Decorators?

In Python, decorators are a way to modify or enhance the behavior of a function or class method. The "at" symbol is used to apply decorators to functions or methods. A decorator is essentially a function that takes another function and extends its behavior without explicitly modifying it.

Example of a Function Decorator

python
1# Define a simple decorator that logs function execution
2def log_execution(func):
3    def wrapper(*args, **kwargs):
4        print(f"Executing {func.__name__}")
5        return func(*args, **kwargs)
6    return wrapper
7
8# Apply the decorator using the @ symbol
9@log_execution
10def say_hello():
11    print("Hello, World!")
12
13# Call the decorated function
14say_hello()

In this example, say_hello is decorated with log_execution, which logs the execution of the function.

Class Method Decorators

Class methods can also be decorated using the "at" symbol:

python
1class MyClass:
2    @staticmethod
3    def my_static_method():
4        return "This is a static method"
5
6    @classmethod
7    def my_class_method(cls):
8        return "This is a class method"
9
10# Usage
11print(MyClass.my_static_method())
12print(MyClass.my_class_method())

In this case, my_static_method and my_class_method are static and class methods, respectively, distinguished by the use of decorators.

Matrix Multiplication

With the introduction of PEP 465 in Python 3.5, the "at" symbol @ was adopted as an infix operator for matrix multiplication. It provides a clean and clear syntax for performing matrix operations, especially useful in scientific computing and data analysis.

Example of Matrix Multiplication

python
1import numpy as np
2
3# Define two matrices as NumPy arrays
4A = np.array([[1, 2], [3, 4]])
5B = np.array([[5, 6], [7, 8]])
6
7# Matrix multiplication using the @ symbol
8C = A @ B
9
10print(C)  # Output: [[19 22]
11          #          [43 50]]

Here, A @ B multiplies matrices A and B, resulting in a new matrix C.

Summary Table

Here's a quick summary of the different contexts in which the "at" symbol is used in Python:

ContextUsageDescription
Decorators@decoratorEnhances or modifies the behavior of a function or method.
Static Methods@staticmethodDefines a static method in a class.
Class Methods@classmethodDefines a class method that receives the class as its argument.
Matrix MultiplicationA @ BPerforms matrix multiplication between matrices A and B.

Additional Details

Chained Decorators

Python allows multiple decorators to be applied to a single function. They are applied from top to bottom, wrapping the function in multiple layers. Here's an example of chained decorators:

python
1def uppercase(func):
2    def wrapper(*args, **kwargs):
3        result = func(*args, **kwargs)
4        return result.upper()
5    return wrapper
6
7@log_execution
8@uppercase
9def greet(name):
10    return f"Hello, {name}"
11
12# Call the chained decorated function
13greet("Alice")
14# Output:
15# Executing greet
16# 'HELLO, ALICE'

In this example, greet is first decorated with uppercase, which transforms its output to uppercase, and then with log_execution to log its execution.

Custom Decorators

You can create custom decorators to do nearly anything. Based on the requirement, decorators can validate inputs, cache results, enforce access control, etc.

python
1def validate_non_empty(func):
2    def wrapper(string, *args, **kwargs):
3        if not string:
4            raise ValueError("String cannot be empty")
5        return func(string, *args, **kwargs)
6    return wrapper
7
8@validate_non_empty
9def process_text(text):
10    return f"Processing {text}"
11
12# The function with the empty string will raise an error
13try:
14    process_text("")  # Raises ValueError
15except ValueError as e:
16    print(e)  # Output: String cannot be empty

Conclusion

The "at" (@) symbol in Python is a versatile tool that plays a crucial role in enhancing the language's functionality. Whether it's decorating functions for more complex behavior, utilizing efficient matrix operations in numerical computing, or enabling cleaner syntax through scoped functionality, this symbol is a powerful feature in Python that promotes clean, readable, and efficient 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.