Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e77e31f

Browse files
Update Decorators.py
1 parent e2779ab commit e77e31f

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

‎Decorators.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,23 @@ def greet(name, greeting='Welcome Sir'):
4646

4747
greet('Ali', greeting='How are you?')
4848

49+
# Example 5: Cache decorator (stores results to avoid recalculation)
50+
def cache(func):
51+
cache_value = {} # Store previous results here
52+
def wrapper_3(*args):
53+
if args in cache_value:
54+
return cache_value[args] # Return cached result if available
55+
result_1 = func(*args)
56+
cache_value[args] = result_1 # Store result in cache
57+
return result_1
58+
return wrapper_3
59+
60+
@cache
61+
def log_running_function(a, b):
62+
time.sleep(4) # Simulate slow computation
63+
return a + b
64+
65+
print(log_running_function(2, 3))
66+
print(log_running_function(2, 3)) # This call will return instantly from cache
67+
print(log_running_function(4, 3))
68+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /