| prev | Draft Version 462 (Mon Dec 5 17:01:54 2005) | next |
def makeRect(x0, y0, x1, y1):
'''Construct a rectangle 'object'.'''
return {'x0' : x0,
'y0' : y0,
'x1' : x1,
'y1' : y1,
'area' : rectArea,
'contains' : rectContains,
'str' : rectStr
}
def rectArea(obj):
'''Calculate area of rectangle.'''
return (obj['x1'] - obj['x0']) * (obj['y1'] - obj['y0'])
def rectContains(obj, x, y):
'''See if a rectangle contains an XY point.'''
return (obj['x0'] <= x <= obj['x1']) and \
(obj['y0'] <= y <= obj['y1'])
def rectStr(obj):
'''Show as string.'''
return '[%(x0)d,%(y0)d X %(x1)d,%(y1)d]' % obj
def run(obj, meth, *args, **kwargs):
'''Run a method for an 'object', passing in arbitrary arguments.'''
func = obj[meth]
return func(obj, *args, **kwargs)
# Create a rectangle. block = makeRect(0, 0, 2, 2) print run(block, 'str') # Calculate its area. print 'area is', run(block, 'area') # See if it contains a couple of points. print 'contains (1, 1)?', run(block, 'contains', 1, 1) print 'contains (10, 10)?', run(block, 'contains', 10, 10)
run(obj, 'method', …) with obj.method(…)obj.meth(args) is obj.class[methodname](args)
hasattr(obj, attrName) reports whether an object has an attribute with a particular namegetattr(obj, attrName) gets the value of an object's attributesetattr(obj, attrName, newValue) set an attribute's valuedir(obj) lists all the attribute of an objectimport statement is evaluated at runtime as well#include or Java's import, which are evaluated by the compilerimport sys
if (len(sys.argv) > 1) and (sys.argv[1] == '-d'):
import testLib as lib
else:
import realLib as lib
print lib.ackermann(3, 2)
func that takes a list of strings as input, and produces another list of strings as outputdef func(lines):
result = []
for i in range(1, len(lines), 2):
result.append(lines[i])
return result
__import__ functionimport statement does, but takes a string as an argument.pyimport sys
filters = []
for moduleName in sys.argv[1:]:
moduleName = moduleName[:-3] # strip off '.py'
module = __import__(moduleName)
func = getattr(module, 'func')
filters.append(func)
print filters
lines = sys.stdin.readlines()
for f in filters:
lines = f(lines)
for l in lines:
print l,
coverage tool does four things:
coverage -x yourprogram.py …args… runs your program to collect coverage data.coverage so that you can collect information over several runs of your programimport sys
def foo(x, y):
for i in x:
y += 1
print 'result:', y
def bar(z):
if z < 0:
print "shouldn't happen"
elif z == 0:
print "shouldn't happen either"
else:
foo('abc', z)
if __name__ == '__main__':
for i in range(1, int(sys.argv[1])):
bar(i)
python coverage.py -x c.py 3
result: 4 result: 5
python coverage.py -r -m c.py
Name Stmts Exec Cover Missing ------------------------------------- c 14 12 85% 10, 12
python coverage.py -a
> import sys
> def foo(x, y):
> for i in x:
> y += 1
> print 'result:', y
> def bar(z):
> if z < 0:
! print "shouldn't happen"
> elif z == 0:
! print "shouldn't happen either"
> else:
> foo('abc', z)
> if __name__ == '__main__':
> for i in range(1, int(sys.argv[1])):
> bar(i)
hotshot module measures execution timehotshot.Profile with the name of a log file as an argumentruncall method to profile a single run of a functionhotshot.stats
import sys
def builtin(str, substr):
return str.find(substr)
def handwritten(str, substr):
for i in range(0, len(str)-len(substr)):
match = True
for j in range(len(substr)):
if substr[j] != str[i+j]:
match = False
break
if match:
return i
return -1
def tests(num):
Tests = [
['a', ''],
['a', 'abc'],
['abc', 'a'],
['pqrstuvwxyz', 'stuv'],
['pqrstuvwxyz', 'stuw']
]
for i in range(num):
for (str, substr) in Tests:
expected = builtin(str, substr)
assert expected == handwritten(str, substr)
if __name__ == '__main__':
import hotshot, hotshot.stats
Filename = 'substr.prof'
num = int(sys.argv[1])
prof = hotshot.Profile(Filename)
prof.runcall(tests, num)
prof.close()
stats = hotshot.stats.load(Filename)
stats.strip_dirs()
stats.sort_stats('time', 'calls')
stats.print_stats()
10001 function calls in 0.292 CPU seconds
Ordered by: internal time, call count
ncalls tottime percall cumtime percall filename:lineno(function)
5000 0.165 0.000 0.165 0.000 substr.py:6(handwritten)
1 0.081 0.081 0.292 0.292 substr.py:17(tests)
5000 0.045 0.000 0.045 0.000 substr.py:3(builtin)
0 0.000 0.000 profile:0(profiler)
def builtin(str, substr):
return 0
def handwritten(str, substr):
return 0
10001 function calls in 0.166 CPU seconds
Ordered by: internal time, call count
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.098 0.098 0.166 0.166 empty.py:11(tests)
5000 0.034 0.000 0.034 0.000 empty.py:7(handwritten)
5000 0.034 0.000 0.034 0.000 empty.py:4(builtin)
0 0.000 0.000 profile:0(profiler)
Exercise 16.1:
What percentage of your code is tests? Is tested?
Exercise 16.2:
Can you honestly say that you write tests before code? Find out how many tests currently pass or fail with a single command? Identify the tests associated with a bug? Tell if your code meets the team's standards?
Exercise 16.3:
Can you find out which functions use the most CPU time? How long threads spend blocked on I/O? Who allocates memory, where, for what? How accurate these numbers are? How today's profile differs from last month's? How the profile differs across machines?
| prev | Copyright © 2005, Python Software Foundation. See License for details. | next |