0% found this document useful (0 votes)
4 views

python decorator

Uploaded by

Giruba Karan A
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

python decorator

Uploaded by

Giruba Karan A
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Decorators in Python are a powerful feature that allows you to modify the behavior of functions or

methods. They are often used for logging, enforcing access control, instrumentation, caching, and
more. Let’s delve into some common decorators and explain how they work in detail.

### What is a Decorator?

A decorator is essentially a function that takes another function as an argument, extends its behavior,
and returns a new function. Decorators are applied using the `@decorator_name` syntax above the
function definition.

### Common Decorators

#### 1. **Function Decorator**

Here's a simple example of a function decorator that logs the execution time of a function.

```python

import time

def time_logger(func):

def wrapper(*args, **kwargs):

start_time = time.time()

result = func(*args, **kwargs)

end_time = time.time()

print(f"Executed {func.__name__} in {end_time - start_time:.4f} seconds")

return result

return wrapper

@time_logger

def slow_function():

time.sleep(2)

print("Finished slow function!")


slow_function()

```

**Explanation:**

- `time_logger`: This is the decorator function that takes another function `func` as an argument.

- `wrapper`: Inside the decorator, we define a nested function that adds functionality before and
after the original function is called.

- `*args` and `**kwargs`: These allow the wrapper to accept any number of positional and keyword
arguments.

- `start_time` and `end_time`: Measure the time taken by the `func` to execute.

- The `@time_logger` syntax applies the decorator to `slow_function`.

#### 2. **Class Method Decorators**

Decorators can also be applied to class methods. A common built-in decorator is `@staticmethod`
and `@classmethod`.

```python

class MyClass:

@staticmethod

def static_method():

return "I am a static method"

@classmethod

def class_method(cls):

return f"I am a class method of {cls.__name__}"

print(MyClass.static_method()) # Output: I am a static method

print(MyClass.class_method()) # Output: I am a class method of MyClass

```
**Explanation:**

- `@staticmethod`: This decorator defines a method that does not require access to the instance
(`self`) or the class (`cls`).

- `@classmethod`: This decorator defines a method that takes the class as its first argument (`cls`),
allowing it to access class-level data.

#### 3. **Built-in Decorators**

Python provides several built-in decorators, including:

- **`@property`**: Allows you to define a method that can be accessed like an attribute.

```python

class Circle:

def __init__(self, radius):

self.radius = radius

@property

def area(self):

return 3.14 * (self.radius ** 2)

c = Circle(5)

print(c.area) # Output: 78.5

```

- **`@functools.lru_cache`**: This decorator caches the results of expensive function calls.

```python

from functools import lru_cache

@lru_cache(maxsize=None)

def fibonacci(n):
if n < 2:

return n

return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(35)) # Fast due to caching

```

### How Decorators Work

1. **Function Passing**: When you use a decorator, you're passing the function to the decorator,
which can modify or extend its behavior.

2. **Returning a Function**: The decorator returns a new function (the wrapper), which can call the
original function and add behavior around it.

3. **Syntax Sugar**: The `@decorator` syntax is syntactic sugar for `function = decorator(function)`.

### Summary

Decorators are a versatile feature in Python that enables you to enhance or modify the behavior of
functions or methods without altering their code directly. They can be user-defined or built-in and
are used in various applications, including logging, caching, access control, and more. Understanding
decorators can significantly improve your Python programming skills and enable you to write cleaner,
more maintainable code.

If you have any specific use cases or questions about decorators, feel free to ask!

You might also like