summaryrefslogtreecommitdiff
path: root/advanced_python/15_decorators.tex
blob: b5bd61d1e927ae5b58caf46c6ce4b7230315d092 (plain)
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
\documentclass[14pt,compress,aspectratio=169]{beamer}

\usepackage{hyperref}
\input{macros.tex}


\title[Decorators]{Advanced Python}
\subtitle{Decorators}

\author[FOSSEE] {The FOSSEE Group}

\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay}
\date[] {Mumbai, India}

\begin{document}

\begin{frame}
  \titlepage
\end{frame}

\begin{frame}[fragile]
  \frametitle{Overview}
  Decorators:
  \begin{itemize}
  \item transform a function/method using a function
  \item are higher order functions
  \item provide a handy syntax
  \item are a powerful feature
  \item used by many libraries
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Trivial example}
\begin{lstlisting}
def deco(func):
    return func

@deco
def greet():
    print("Namaste!")

# @deco is equivalent to:
greet = deco(greet)
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Understanding a bit more}
\begin{lstlisting}
def deco(func):
    print("deco")  # <--
    return func

@deco
def greet():
    print("Namaste!")

greet = deco(greet)
\end{lstlisting}
\end{frame}

\begin{frame}
  \frametitle{Observations}
  \begin{itemize}
  \item Decorator is a convenient syntax
  \item Called when the function is defined
  \item Not called every time the decorated function is called
  \end{itemize}
\end{frame}

\begin{frame}[fragile, plain]
  \frametitle{Non-trivial example}
Modify the function to print ``Hello'' before the function is called
\begin{lstlisting}
def deco(func):
    def new_func(*args, **kw):
        print("Hello")
        return func(*args, **kw)
    return new_func
\end{lstlisting}
\pause
\begin{lstlisting}
@deco
def greet():
    '''Print greeting.'''
    print("Namaste!")

In []: greet()

\end{lstlisting}
\end{frame}

\begin{frame}
  \frametitle{Observations}
  \begin{itemize}
  \item Notice the use of the \py{*args, **kw}
  \item The target function may have any arguments
  \item We replace the original function with \py{new_func}
  \item So does this cause any problems?
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Issues}
  \begin{lstlisting}
    In []: greet.__name__
    Out[]: 'new_func'

    In []: greet?

    In []: greet.__doc__

    In []: greet.__module__
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Using \py{wraps}}
  \begin{itemize}
  \item Using \py{functools.wraps} prevents these problems
  \end{itemize}

  \begin{lstlisting}
from functools import wraps  # <--

def deco(func):
    @wraps(func)  # <--
    def new_func(*args, **kw):
        print("Hello")
        return func(*args, **kw)
    return new_func
\end{lstlisting}

Now try again.
\end{frame}


\begin{frame}[fragile]
  \frametitle{Decorators taking arguments}
  \begin{itemize}
  \item Sometimes you want to customize the decorator
  \item You wish to pass arguments to the decorator
  \end{itemize}
\pause
First attempt:
  \begin{lstlisting}
from functools import wraps

def deco(func, greet='Hello'):
    @wraps(func)
    def new_func(*args, **kw):
        print(greet)
        return func(*args, **kw)
    return new_func
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Let us try}
  \small
  \begin{lstlisting}
@deco
def f():
    print('Hi')

In []: f()
Hello
Hi
\end{lstlisting}
\pause
\begin{lstlisting}
@deco(greet='Namaste')
def f():
    print('Hi')

TypeError: deco() got an unexpected keyword argument 'greet'
  \end{lstlisting}
\end{frame}

\begin{frame}
  \frametitle{Fixing the problem}
  \begin{itemize}
  \item \py{deco(greet='Namaste')} is not passed the function!
  \item So \py{deco(greet='Namaste')} should return a decorator
    \vspace*{0.2in}
  \end{itemize}
\pause
  \begin{block}{Solution}
    \begin{itemize}
    \item Must return a decorator when called without a function
    \item When passed a function just call the decorator
    \end{itemize}
  \end{block}
\end{frame}

\begin{frame}[fragile, plain]
  \frametitle{Fixing the problems}
  \small
  \begin{lstlisting}
def deco(func=None, greet='Hello'):
    def wrapper(func):  # <-- a decorator
        @wraps(func)
        def new_func(*args, **kw):
            print(greet)
            return func(*args, **kw)
        return new_func

    if func is None:
        return wrapper
    else:
        return wrapper(func)

  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Let us try}
  \small
  \begin{lstlisting}
@deco
def f():
    print('Hi')

In []: f()
Hello
Hi
\end{lstlisting}
\pause
\begin{lstlisting}
@deco(greet='Namaste')
def f():
    print('Hi')

In []: f()
Namaste
Hi

  \end{lstlisting}
\end{frame}

\begin{frame}
  \frametitle{Summary}
  \begin{itemize}
  \item Creating simple decorators
  \item Using \py{functools.wraps}
  \item Decorators taking arguments
  \end{itemize}
\end{frame}

\begin{frame}[plain, fragile]
  \frametitle{Exercise: simplest decorator}
  \begin{block}{}
    Write a decorator called \py{greet} that prints \py{'Hello'} before
    the function is called.
  \end{block}
  \begin{lstlisting}
    @greet
    def f(x):
        print(x)

    In []: f(1)
    Hello
    1
\end{lstlisting}
\end{frame}


\begin{frame}[plain, fragile]
  \frametitle{Solution}
\begin{lstlisting}
def greet(func):
    def new_func(*args, **kw):
        print("Hello")
        return func(*args, **kw)
    return new_func
\end{lstlisting}
\end{frame}

\begin{frame}[plain, fragile]
  \frametitle{Exercise: add goodbye}
  \begin{block}{}
    Modify decorator \py{greet} to print ``goodbye'' after executing the
    function.
  \end{block}
  \begin{lstlisting}
from functools import wraps
def greet(func):
    @wraps(func)
    def new_func(*args, **kw):
        print("Hello")
        return func(*args, **kw)
    return new_func
\end{lstlisting}

\end{frame}

\begin{frame}[fragile]
  \frametitle{Solution}
\begin{lstlisting}
def greet(func):
    @wraps(func)
    def new_func(*args, **kw):
        print("Hello")
        result = func(*args, **kw)
        print("goodbye")
        return result
    return new_func
\end{lstlisting}
\end{frame}

\begin{frame}[plain, fragile]
  \frametitle{Exercise: print function name}
  \begin{block}{}
    Write a decorator called \py{debug()} that prints the name of the function
    before it is called.  \textbf{Hint:} Recall \py{__name__}
  \end{block}

\begin{lstlisting}
    @debug
    def my_func(x):
        print(x)

    In []: my_func(1)
    my_func
    1
\end{lstlisting}
\end{frame}


\begin{frame}[plain, fragile]
  \frametitle{Solution}
\begin{lstlisting}
from functools import wraps

def debug(func):
    @wraps(func)
    def new_func(*args, **kw):
        print(func.__name__)
        return func(*args, **kw)
    return new_func
\end{lstlisting}
\end{frame}


\begin{frame}[plain, fragile]
  \frametitle{Exercise: print function name with optional message}
  \begin{block}{}
    Write a decorator called \py{debug(f, message='')} that prints the name of
    the function before it is called along with an optional message.
  \end{block}

\begin{lstlisting}
    @debug(message='DEBUG: ')
    def my_func(x):
        print(x)

    In []: my_func(1)
    DEBUG: my_func
    1
\end{lstlisting}
\end{frame}


\begin{frame}[plain, fragile]
  \frametitle{Solution}
  \vspace*{-0.1in}
  \small
\begin{lstlisting}
from functools import wraps

def debug(func=None, message=''):
    def wrapper(func)
        @wraps(func)
        def new_func(*args, **kw):
            if message:
                print(message, func.__name__)
            else:
                print(func.__name__)
            return func(*args, **kw)
        return new_func
    if func:
        return wrapper(func)
    else:
        return wrapper
\end{lstlisting}
\end{frame}


\begin{frame}[plain, fragile]
  \frametitle{Exercise: track number of calls}
  \begin{block}{}
    Write a decorator called \py{counter()} that keeps track of the number of
    times a decorated function is called.  Write another function called
    \py{show_counts()} which lists all the called functions.
  \end{block}

  \small
\begin{lstlisting}
@counter
def sq(x): return x*x

@counter
def g(x): return x+2

In []: for i in range(10): g(sq(i))
In []: show_counts()
sq : 10
g : 10

\end{lstlisting}
\end{frame}


\begin{frame}[plain, fragile]
  \frametitle{Solution}
\begin{lstlisting}
_counter_data = {}

def counter(func):
    @wraps(func)
    def new_func(*args, **kw):
        if func in _counter_data:
            _counter_data[func] += 1
        else:
            _counter_data[func] = 1
        return func(*args, **kw)
    return new_func
\end{lstlisting}
\end{frame}

\begin{frame}[plain, fragile]
  \frametitle{Solution}
\begin{lstlisting}
def show_counts():
    for f, c in _counter_data.items():
        print(f.__name__, ':', c)
\end{lstlisting}
\end{frame}

\begin{frame}
  \frametitle{Homework}
  \begin{block}{}
    Convert the above into a class so that the global \py{_counter_data} and
    the decorator is encapsulated into the class.\\

    Hints:
    \begin{itemize}
    \item A decorator can be any callable, even a method
    \item You can override the \py{__call__} special method to make the object callable
    \end{itemize}

  \end{block}
\end{frame}


\end{document}