codehack.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # A subroutine for extracting a function name from a code object
  2. # (with cache)
  3. import sys
  4. from stat import *
  5. import string
  6. import os
  7. import linecache
  8. # XXX The functions getcodename() and getfuncname() are now obsolete
  9. # XXX as code and function objects now have a name attribute --
  10. # XXX co.co_name and f.func_name.
  11. # XXX getlineno() is now also obsolete because of the new attribute
  12. # XXX of code objects, co.co_firstlineno.
  13. # Extract the function or class name from a code object.
  14. # This is a bit of a hack, since a code object doesn't contain
  15. # the name directly. So what do we do:
  16. # - get the filename (which *is* in the code object)
  17. # - look in the code string to find the first SET_LINENO instruction
  18. # (this must be the first instruction)
  19. # - get the line from the file
  20. # - if the line starts with 'class' or 'def' (after possible whitespace),
  21. # extract the following identifier
  22. #
  23. # This breaks apart when the function was read from <stdin>
  24. # or constructed by exec(), when the file is not accessible,
  25. # and also when the file has been modified or when a line is
  26. # continued with a backslash before the function or class name.
  27. #
  28. # Because this is a pretty expensive hack, a cache is kept.
  29. SET_LINENO = 127 # The opcode (see "opcode.h" in the Python source)
  30. identchars = string.ascii_letters + string.digits + '_' # Identifier characters
  31. _namecache = {} # The cache
  32. def getcodename(co):
  33. try:
  34. return co.co_name
  35. except AttributeError:
  36. pass
  37. key = `co` # arbitrary but uniquely identifying string
  38. if _namecache.has_key(key): return _namecache[key]
  39. filename = co.co_filename
  40. code = co.co_code
  41. name = ''
  42. if ord(code[0]) == SET_LINENO:
  43. lineno = ord(code[1]) | ord(code[2]) << 8
  44. line = linecache.getline(filename, lineno)
  45. words = line.split()
  46. if len(words) >= 2 and words[0] in ('def', 'class'):
  47. name = words[1]
  48. for i in range(len(name)):
  49. if name[i] not in identchars:
  50. name = name[:i]
  51. break
  52. _namecache[key] = name
  53. return name
  54. # Use the above routine to find a function's name.
  55. def getfuncname(func):
  56. try:
  57. return func.func_name
  58. except AttributeError:
  59. pass
  60. return getcodename(func.func_code)
  61. # A part of the above code to extract just the line number from a code object.
  62. def getlineno(co):
  63. try:
  64. return co.co_firstlineno
  65. except AttributeError:
  66. pass
  67. code = co.co_code
  68. if ord(code[0]) == SET_LINENO:
  69. return ord(code[1]) | ord(code[2]) << 8
  70. else:
  71. return -1