Changeset 354
- Timestamp:
- 06/21/08 23:00:10 (4 years ago)
- Files:
-
- 1 modified
-
hodgestar/Talks/PythonObjects/util.py (modified) (6 diffs)
Legend:
- Unmodified
- Added
- Removed
-
hodgestar/Talks/PythonObjects/util.py
r343 r354 1 """Utility module for use with pyobjects talk.""" 2 1 3 import gc 2 4 import random … … 6 8 import sys 7 9 8 os.chdir('/home/simon/LocalProjects/PythonSpint/trunk') 10 # 11 # Old vs New Classes and Slots 12 # 9 13 10 14 class Old: 15 """A classic or old-style class.""" 11 16 pass 12 17 13 18 class New(object): 19 """A new-style class with a useful type.""" 14 20 pass 15 21 16 22 class FuBar(object): 23 """Illustrates the difference between __str__ and 24 __unicode__. __str__ has a slot (tp_str) while 25 __unicode__ does not. 26 """ 17 27 def __str__(self): 18 28 return "fubar" … … 21 31 22 32 class OldFu: 33 """Like FuBar, but showing it with classic classes.""" 23 34 def __str__(self): 24 35 return "fubar" … … 26 37 return unicode("fubar") 27 38 39 # 40 # Grabbing the interned string dictionary 41 # and a simple Python keyword game 42 # 43 44 PYTHON_TRUNK_CHECKOUT = '/home/simon/LocalProjects/PythonSpint/trunk' 45 28 46 def find_big_dict(x): 47 """Use gc to find the first dict with len greater than 1000 48 that references x. 49 """ 29 50 for obj in gc.get_referrers(x): 30 51 if type(obj) is dict and len(obj) > 1000: … … 33 54 34 55 def find_str_interns(): 56 """Find interned string dict by looking for a big dict that 57 refers to "a". 58 """ 35 59 return find_big_dict("a") 36 60 37 61 def keyword_quiz(): 62 """Looks up upper case keywords in the interned string dict 63 and asks users to guess which part of Python they come 64 from. Prints answers by grepping Python source. 65 """ 38 66 interned = find_big_dict("a") 39 67 keywords = [x for x in interned if x.isupper() and len(x) > 4] 40 68 question = random.choice(keywords) 41 69 42 egrep = subprocess.Popen(["egrep", "-R", "-l", "--exclude-dir", ".svn", 70 pwd = os.getcwd() 71 try: 72 os.chdir(PYTHON_TRUNK_CHECKOUT) 73 egrep = subprocess.Popen(["egrep", "-R", "-l", "--exclude-dir", ".svn", 43 74 "--include", "*.c", "--include", "*.h", "--include", "*.py", 44 75 '%s' % question, 45 76 "Modules", "Lib"], stdout=subprocess.PIPE) 46 answer, err = egrep.communicate() 77 answer, err = egrep.communicate() 78 finally: 79 os.chdir(pwd) 47 80 48 81 print ("Which module does the keyword " + question + " appear in?") … … 55 88 print (answer) 56 89 57 # From: 58 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222 59 # 90 # Recipe for measuring process memory usage, taken from 91 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222. 92 # According to http://aspn.activestate.com/ASPN/Python/Cookbook/ 93 # licensed under the Python license unless otherwise stated. 94 # I'm taking this to mean Python license 2.1 or newer which is 95 # GPL compatible. 60 96 61 97 _proc_status = '/proc/' + str(os.getpid()) + '/status'
