-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
372 lines (346 loc) · 14.2 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible"
content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<link rel="stylesheet"
href="style.css">
<title>fcc Technical Document Project</title>
</head>
<body>
<nav id="navbar">
<header id="nav-header">Python<br>Function Decorators</header>
<a href="#Intro_to_Decorators"
class="nav-link">Intro to Decorators</a>
<a href="#Decorators_As_Functions"
class="nav-link">Decorators As Functions</a>
<a href="#Decorator_Functions_Using_the_'@'_Symbol"
class="nav-link">Decorator Functions Using the '@' Symbol</a>
<a href="#Decorators_with_Different_Signatures"
class="nav-link">Decorators with Different Signatures</a>
<a href="#Preserving_the_Decorated_Function's_Metadata"
class="nav-link">Preserving the Decorated Function's Metadata</a>
<a href="#Using_A_Decorator_With_Arguments"
class="nav-link">Using A Decorator With Arguments</a>
<a href="#References"
class="nav-link">References</a>
</nav>
<main id="main-doc">
<section class="main-section"
id="Intro_to_Decorators">
<header>
<h2>Intro to Decorators</h2>
</header>
<p>Added to the Python language in version 2.4 <a
href="https://docs.python.org/3/whatsnew/2.4.html?highlight=PEP318#pep-318-decorators-for-functions-and-methods"
target="_blank"
rel="noopener noreferrer">PEP 318: Decorators for Functions and Methods</a>, a <dfn
title="decorator">decorator</dfn> is a function that wraps another function, usually used
for enhancing the wrapped function's behavior.
</p>
<p>The decorator was added because developers were requesting easier access to create static methods and
class
methods. </p>
<p>Decorators are usually applied using a special decorator <code>@wrapper</code> <a href="#symbol">syntax</a>,
though it isn't necessary.
</p>
</section>
<section class="main-section"
id="Decorators_As_Functions">
<header>
<h2>Decorators As Functions</h2>
</header>
<p>A decorator is an example of a higher-order function. It takes another function as an argument and then
either returns that same fuction, or returns another, new object.</p>
<p>The following is an example of a decorator function and a function to be modified:</p>
<pre class="code">
<code id="decorator_function">
def decorator(fn):
def wrapped():
print("Inside the decorator function")
fn() #call the passed in function
print("Still inside the decorator function")
return wrapped
def decorated():
print("Calling the decorated function")</code>
</pre>
<p>As seen in the above example, a decorator function (in this case <code>decorator()</code>) accepts a
seperate function, the decorat<em>ed</em> function <code>decorated()</code>. The decorator contains an inner
function (wrapped) that has access to and can modify the decorated function, which must then be returned to
the decorated function to use . It's important to understand that
the decorator function returns a function object which still needs to be executed later.</p>
<p>
Calling decorated() prints out it's message.
<pre class="code">
<code>
decorated()
# Calling the decorated function
</code>
</pre>
</p>
<p>
Calling decorator with decorated as the argument just returns a function object, which then needs to be called
itself.
<pre class="code">
<code>
decorator(decorated)
# < function decorator.< locals>.wrapped at 0x000001B62CA131C0>
</code>
</pre>
</p>
<p>
decorator() needs to be called and saved to a variable, usually named the same as the function, and then
called
as a function.
<pre class="code">
<code>
decorated = decorator(decorated)
decorated()
# Inside the decorator function
# Calling the decorated function
# Still inside the decorator function
</code>
</pre>
</p>
<p>
In another example the decorated function takes a list of numbers, adds them together and displays a value.
Adding a decorator function which accepts the add() function and the list argument, filters the list for even
numbers only and then returns the function object to be called later. The new object then adds only the even
numbers from the list and displays a different value.
<pre class="code">
<code>
def evens(fn):
def wrapped(lst):
new_lst = []
for i in lst:
if i % 2 == 0:
new_lst.append(i)
return fn(new_lst)
return wrapped
lst = [1,2,3,4,5,6,7,8,9,10]
def add(lst):
a = 0
for i in lst:
a += i
return a # 55
# decorate the add() function with the evens decorator
add = evens(add)
print(add(lst)) # 30</code>
</pre>
</p>
</section>
<section class="main-section"
id="Decorator_Functions_Using_the_'@'_Symbol">
<header>
<h2>Decorator Functions Using the '@' Symbol</h2>
</header>
<p>While assigning a function to a variable and calling the variable is obviously valid code, there is a more
common and easier way to decorate a function. Use the '@' symbol and the decorator function name above the
function to be decorated.
<pre class="code">
<code>
@decorator
def decorated():
print("Calling the decorated function")</code>
</pre>
</p>
<p>
Now all that needs to be done is to call the decorated() function, and the rest is done automatically.
<pre class="code">
<code>
decorated()
# Inside the decorator function
# Calling the decorated function
# Still inside the decorator function</code>
</pre>
</p>
<p>
Using this format is considered "syntactic sugar", meaning this is just an easier way to do the same thing,
plus it looks better and is easier to read.
</p>
</section>
<section class="main-section"
id="Decorators_with_Different_Signatures">
<header>
<h2>Decorators with Different Signatures</h2>
</header>
<p>Decorated functions often have a signature where arguments are passed to them. So the arguments will also
pass to the decorator function. THe decorator function doesn't necessarily need to do anything with the passed
arguments, but it does have to accept them also. The functino signature can be in the form of a single
argument, multiple arguments, or a single or multiple keyword argument. It's usually important that the
wrapped function inside the decorator function does something with
the passed arguments.</p>
<p>If the decorator function's argument signature is known and will always be used with decorated functions with
the same argument signatures, this is easier to deal with. Just make sure that wrapped() has the same argument
signature, like below.</p>
<p>
In the following example, the add() function accepts a list of numbers, iterates over the list and returns all
of
the numbers in the list added together.
</p>
<p>
The decorator function acts as a filter, only returning the even numbers from the list, which are then added
in the add() decorated function.
</p>
<pre class="code">
<code>
def evens(fn):
def wrapped(lst):
new_lst = []
for i in lst:
if i%2==0:
new_lst.append(i)
return fn(new_lst) #need to return the passed function and argument
return wrapped
lst = [1,2,3,4,5,6,7,8,9,10]
@evens
def add(lst):
a=0
for i in lst:
a+=i
return a
print(add(lst))
# with @evens, returns 30
# without @evens, returns 55
</code>
</pre>
<p>Sometimes there are multiple functions that would benefit from a decorator function, but they may have
different argument signatures. To get the wrapped function to take different function signatures, use *args
and **kwargs.
<pre class="code"
style="margin-bottom: 0;">
<code>
def shout(fn):
def wrapped(*args, **kwargs):
return fn(*args, **kwargs).upper()
return wrapped
@shout
def greet(name):
return f"Hi I'm, {name}"
@shout
def order(main, side):
return f"I'd like a {main} and a side of {side}"
@shout
def bad_neigbor(name, pet, area):
return f"Hey {name}, please keep your {pet} out of my {area}"
print(greet("Jeff")) #HI I'M, JEFF
print(order("burger", "fries")) #I'D LIKE A BURGER AND A SIDE OF FRIES
print(bad_neigbor(name="Mom", pet="husband", area="bathroom")) #HEY MOM, PLEASE KEEP YOUR HUSBAND OUT OF MY BATHROOM
</code>
</pre>
<small>Some examples taken from <a href="https://www.udemy.com/course/the-modern-python3-bootcamp"
target="_blank"
rel="noopener noreferrer">Colt Steele's The Modern Python3 Bootcamp</a></small>
</p>
<p>In this example, all three functions (greet, order and bad_neighbor) use the same decorator function even
though they all have different argument signatures.</p>
</section>
<section class="main-section"
id="Preserving_the_Decorated_Function's_Metadata">
<header>
<h2>Preserving the Decorated Function's Metadata</h2>
</header>
Because of the way decorators work, whan a function is passed to the decorator, the decorated function's
meta-data is included. This includes __name__() and __docs__() methods. Because of this, a problem occurs when
trying to call the decorated function's meta-data methods, it will actually be in refernce to the decorator
function, not the decorated function. For example, calling __name__ for bad_neigbor() function above displays:
<pre class="code">
<code>
print(bad_neigbor.__name__) # wrapped</code>
</pre>
<p>The easiest way to fix this is using the functools module, and calling the 'wraps' decorator function. Then
decorate the 'wrapped' inner function with the @wraps decorator. However the decorated function must be passed
to the wraps decorator also. Then when calling the decorated function's meta-data the correct information will
be displayed.</p>
<pre class="code">
<code>
from functools import wraps
def shout(fn):
@wraps(fn) # Must pass fn to wraps
def wrapped(*args, **kwargs):
return fn(*args, **kwargs).upper()
return wrapped
print(bad_neighbor.__name__) #bad_neighbor</code>
</pre>
</section>
<section class="main-section"
id="Using_A_Decorator_With_Arguments">
<header>
<h2>Using A Decorator With Arguments</h2>
</header>
<p>
Sometimes an argument needs to be passed to the decorator, for example the @wraps(fn) decorator in the
previous section. Passing an argument to a decorator can also be done both as a function assignment or using
the @ symbol.
</p>
<p>As seen previously in the <a href="#Decorators_As_Functions">Decorators As Functions</a> section, decorating
a function without the @ symbol looks like
this:
<pre class="code">
<code>
def fn():
pass
fn = decorator(fn)</code>
</pre>
Since that's the case, then when passing an argument to the decorator as in this basic example:
<pre class="code">
<code>
@decorator(val)
def fn():
pass</code>
</pre>
will then be the same as
<pre class="code">
<code>
def fn():
pass
fn = decorator(val)(fn)</code>
</pre>
</p>
<p>
Adding the ability to pass an argument to a decorator is slightly more complicated and
requires an additional function layer in the decorator function that is between the decorator function
definition and the wrapper function definition.
<pre class="code">
<code>
def decorator(val):
def inner(fn):
def wrapper(*args, **kwargs):
# do something
return wrapper
return inner</code>
</pre>
</p>
</section>
<section class="main-section"
id="References">
<header>
<h2>References</h2>
</header>
<ul>
<li>CPython's
<a href="https://docs.python.org/3/glossary.html#term-decorator"
target="_blank"
rel="noopener noreferrer">decorator definition</a>
</li>
<li>CPython's
<a href="https://docs.python.org/3/whatsnew/2.4.html?highlight=PEP318#pep-318-decorators-for-functions-and-methods"
target="_blank"
rel="noopener noreferrer">PEP 318: Decorators for Function and Methods</a> documentation
</li>
<li>
<a href="https://www.udemy.com/course/the-modern-python3-bootcamp"
target="_blank"
rel="noopener noreferrer">Colt Steele's The Modern Python3 Bootcamp</a> section on decorators.
</li>
<li></li>
<li></li>
</ul>
</section>
</main>
<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
</body>
</html>