-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbasicmath.py
More file actions
104 lines (65 loc) · 1.61 KB
/
basicmath.py
File metadata and controls
104 lines (65 loc) · 1.61 KB
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
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
def add(a,b):
return a+b
# <codecell>
add(3,4)
# <markdowncell>
# What if we want to log when that function is called?
# <codecell>
def logged_add(a, b):
print '### %s(%r, %r)' % ('add', a, b)
result = add(a, b)
print '### %s(%r, %r) --> %r' % ('add', a, b, result)
return result
# <markdowncell>
# could change all calls to this -- blech!
#
# so instead write a wrapper:
# <codecell>
def logged(func):
def wrapper(a, b):
print '### %s(%r, %r)' % (func.func_name, a, b)
result = func(a, b)
print '### %s(%r, %r) --> %r' % (func.func_name, a, b, result)
return result
return wrapper
# <markdowncell>
# re-define add...
# <codecell>
add = logged(add)
# <codecell>
add(3,4)
# <markdowncell>
# And use it for other functions, too:
# <codecell>
def subtract(a, b):
"""subtract() subtracts two things"""
return a - b
subtract = logged(subtract)
# <codecell>
subtract(7,4)
# <markdowncell>
# Make it more general -- to take any number of arguments:
# <codecell>
def logged(func):
def wrapper(*args):
print '### %s(%s)' % (func.func_name, args)
result = func(*args)
print '### %s(%s) --> %r' % (func.func_name, args, result)
return result
return wrapper
# <markdowncell>
# A function with one argument:
# <codecell>
def even(a):
"""even() returns True if the value is even"""
return a % 2 == 0
even = logged(even)
# <codecell>
even(3)
# <codecell>
even(4)
# <markdowncell>
# Wouldn't it be nice to have a cleaner syntax that this???