Skip to content

Commit 3c1c3e3

Browse files
authored
Merge pull request wilfredinni#322 from mohammedalrawi98/docs-decorators
Add Decorators
2 parents eb64832 + 691782a commit 3c1c3e3

File tree

2 files changed

+152
-0
lines changed

2 files changed

+152
-0
lines changed

docs/cheatsheet/decorators.md

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
---
2+
title: Python Decorators - Python Cheatsheet
3+
description: A Python Decorator is a syntax that provide a concise and reusable way for extending a function or a class.
4+
---
5+
6+
<base-title :title="frontmatter.title" :description="frontmatter.description">
7+
Python Decorators
8+
</base-title>
9+
10+
A Python Decorator is a syntax that provides a concise and reusable way for extending a function or a class.
11+
12+
## Bare bone decorator
13+
14+
A decorator in its simplest form is a function that takes another function as an argument and returns a wrapper function. The following example shows the creation of a decorator and its usage.
15+
16+
```python
17+
def your_decorator(func):
18+
def wrapper():
19+
# Do stuff before func...
20+
print("Before func!")
21+
func()
22+
# Do stuff after func...
23+
print("After func!")
24+
return wrapper
25+
26+
@your_decorator
27+
def foo():
28+
print("Hello World!")
29+
30+
foo()
31+
32+
# Before func!
33+
# Hello World!
34+
# After func!
35+
```
36+
37+
## Decorator for a function with parameters
38+
39+
```python
40+
def your_decorator(func):
41+
def wrapper(*args,**kwargs):
42+
# Do stuff before func...
43+
print("Before func!")
44+
func(*args,**kwargs)
45+
# Do stuff after func...
46+
print("After func!")
47+
return wrapper
48+
49+
@your_decorator
50+
def foo(bar):
51+
print("My name is " + bar)
52+
53+
foo("Jack")
54+
55+
# Before func!
56+
# My name is Jack
57+
# After func!
58+
```
59+
60+
## Template for a basic decorator
61+
62+
This template is useful for most decorator use-cases. It is valid for functions with or without parameters, and with or without a return value.
63+
64+
```python
65+
import functools
66+
67+
def your_decorator(func):
68+
@functools.wraps(func) # For preserving the metadata of func.
69+
def wrapper(*args,**kwargs):
70+
# Do stuff before func...
71+
result = func(*args,**kwargs)
72+
# Do stuff after func..
73+
return result
74+
return wrapper
75+
```
76+
77+
## Decorator with parameters
78+
79+
You can also define parameters for the decorator to use.
80+
81+
```python
82+
import functools
83+
84+
def your_decorator(arg):
85+
def decorator(func):
86+
@functools.wraps(func) # For preserving the metadata of func.
87+
def wrapper(*args,**kwargs):
88+
# Do stuff before func possibly using arg...
89+
result = func(*args,**kwargs)
90+
# Do stuff after func possibly using arg...
91+
return result
92+
return wrapper
93+
return decorator
94+
```
95+
96+
To use this decorator:
97+
98+
```python
99+
@your_decorator(arg = 'x')
100+
def foo(bar):
101+
return bar
102+
```
103+
104+
## Class based decorators
105+
106+
A decorator can also be defined as a class instead of a method. This is useful for maintaining and updating a state, such as in the following example, where we count the number of calls made to a method:
107+
108+
```python
109+
class CountCallNumber:
110+
111+
def __init__(self, func):
112+
self.func = func
113+
self.call_number = 0
114+
115+
def __call__(self, *args, **kwargs):
116+
self.call_number += 1
117+
print("This is execution number " + str(self.call_number))
118+
return self.func(*args, **kwargs)
119+
120+
@CountCallNumber
121+
def say_hi(name):
122+
print("Hi! My name is " + name)
123+
124+
say_hi("Jack")
125+
126+
say_hi("James")
127+
128+
# This is execution number 1
129+
# Hi! My name is Jack
130+
# This is execution number 2
131+
# Hi! My name is James
132+
```
133+
<base-disclaimer>
134+
<base-disclaimer-title>
135+
Count Example
136+
</base-disclaimer-title>
137+
<base-disclaimer-content>
138+
This count example is inspired by Patrick Loeber's <a href="https://youtu.be/HGOBQPFzWKo?si=IUvFzeQbzTmeEgKV" target="_blank">YouTube tutorial</a>.
139+
</base-disclaimer-content>
140+
</base-disclaimer>
141+
142+
143+
144+
145+
146+
147+

src/store/navigation.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,11 @@ export const useNavigationStore = defineStore('navigation', {
107107
path: '/cheatsheet/args-and-kwargs',
108108
updated: false,
109109
},
110+
{
111+
name: 'Decorators',
112+
path: '/cheatsheet/decorators',
113+
updated: false,
114+
},
110115
{
111116
name: 'Context manager',
112117
path: '/cheatsheet/context-manager',

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy