Decorators Flashcards

(12 cards)

1
Q

What is a closure?

A

A function that remembers variables from its outer scope even after the outer function has finished.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why use closures instead of globals?

A

Closures provide private, safe, and reusable state; globals are shared, unsafe, and hard to debug.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a decorator?

A

A function that wraps another function to add extra behavior without modifying it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Closure vs Decorator

A

Closure = concept (function remembers data)

Decorator = use-case built using closures (wraps functions)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Decorator Structure

A

def decorator(func):
def wrapper(args, **kwargs):
# extra work
return func(
args, **kwargs)
return wrapper

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does @decorator mean?

A

It is syntactic sugar for:

func = decorator(func)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Why are decorators useful?

A

To avoid code repetition, add reusable behavior (logging, timing, retry, caching), and keep code clean.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does a timer decorator do? @timer

A

Measures execution time of a function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does a retry decorator do?

A

Retries a function multiple times if it fails.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What does a cache decorator do?

A

Stores function results to avoid recomputation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Why not directly use functools.lru_cache?

A

To understand memoization, hashing of arguments, and performance optimization.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the core idea behind decorators?

A

Add extra functionality to functions without changing their original code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly