annotate Lib/inspect.py @ 54294:dba767bc3155 legacy-trunk

remove mention of old ctypes version
author Benjamin Peterson <benjamin@python.org>
date Sat, 23 May 2009 20:59:09 +0000
parents 347e59ea1a71
children b71eeb907093
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
24537
28a5c8afa056 Add encoding declaration.
Martin v. Löwis <martin@v.loewis.de>
parents: 23634
diff changeset
1 # -*- coding: iso-8859-1 -*-
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
2 """Get useful information from live Python objects.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
3
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
4 This module encapsulates the interface provided by the internal special
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
5 attributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
6 It also provides some help for examining source code and class layout.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
7
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
8 Here are some of the useful functions provided by this module:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
9
45386
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
10 ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
11 isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
12 isroutine() - check object types
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
13 getmembers() - get members of an object that satisfy a given condition
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
14
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
15 getfile(), getsourcefile(), getsource() - find an object's source code
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
16 getdoc(), getcomments() - get documentation on an object
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
17 getmodule() - determine the module that an object came from
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
18 getclasstree() - arrange classes so as to represent their hierarchy
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
19
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
20 getargspec(), getargvalues() - get info about function arguments
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
21 formatargspec(), formatargvalues() - format an argument spec
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
22 getouterframes(), getinnerframes() - get info about frames
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
23 currentframe() - get the current stack frame
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
24 stack(), trace() - get info about frames on the stack or in a traceback
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
25 """
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
26
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
27 # This module is in the public domain. No warranties.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
28
16898
dcea09388332 Add __author__ variable.
Ka-Ping Yee <ping@zesty.ca>
parents: 16887
diff changeset
29 __author__ = 'Ka-Ping Yee <ping@lfw.org>'
dcea09388332 Add __author__ variable.
Ka-Ping Yee <ping@zesty.ca>
parents: 16887
diff changeset
30 __date__ = '1 Jan 2001'
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
31
45386
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
32 import sys
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
33 import os
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
34 import types
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
35 import string
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
36 import re
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
37 import dis
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
38 import imp
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
39 import tokenize
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
40 import linecache
34734
d355da1d7c8f Apply itemgetter() instead of lambda.
Raymond Hettinger <python@rcn.com>
parents: 34545
diff changeset
41 from operator import attrgetter
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
42 from collections import namedtuple
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
43
48121
1140774f69a5 Silence (Syntax|Deprecation)Warning for 'inspect'. Had to remove tuple
Brett Cannon <bcannon@gmail.com>
parents: 47506
diff changeset
44 # These constants are from Include/code.h.
1140774f69a5 Silence (Syntax|Deprecation)Warning for 'inspect'. Had to remove tuple
Brett Cannon <bcannon@gmail.com>
parents: 47506
diff changeset
45 CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 0x1, 0x2, 0x4, 0x8
1140774f69a5 Silence (Syntax|Deprecation)Warning for 'inspect'. Had to remove tuple
Brett Cannon <bcannon@gmail.com>
parents: 47506
diff changeset
46 CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
45634
6282dfd5dc49 Since abc._Abstract was replaces by a new type flags the regression test suite fails. I've added a new function inspect.isabstract(). Is the mmethod fine or should I check if object is a instance of type or subclass of object, too?
Christian Heimes <christian@cheimes.de>
parents: 45386
diff changeset
47 # See Include/object.h
6282dfd5dc49 Since abc._Abstract was replaces by a new type flags the regression test suite fails. I've added a new function inspect.isabstract(). Is the mmethod fine or should I check if object is a instance of type or subclass of object, too?
Christian Heimes <christian@cheimes.de>
parents: 45386
diff changeset
48 TPFLAGS_IS_ABSTRACT = 1 << 20
6282dfd5dc49 Since abc._Abstract was replaces by a new type flags the regression test suite fails. I've added a new function inspect.isabstract(). Is the mmethod fine or should I check if object is a instance of type or subclass of object, too?
Christian Heimes <christian@cheimes.de>
parents: 45386
diff changeset
49
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
50 # ----------------------------------------------------------- type-checking
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
51 def ismodule(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
52 """Return true if the object is a module.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
53
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
54 Module objects provide these attributes:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
55 __doc__ documentation string
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
56 __file__ filename (missing for built-in modules)"""
19930
36c07a1718e9 In a world with a growing number of subclassable types, replace
Tim Peters <tim.peters@gmail.com>
parents: 19694
diff changeset
57 return isinstance(object, types.ModuleType)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
58
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
59 def isclass(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
60 """Return true if the object is a class.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
61
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
62 Class objects provide these attributes:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
63 __doc__ documentation string
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
64 __module__ name of module in which this class was defined"""
50834
35bf8f7a8edc fix inspect.isclass() on instances with a custom __getattr__ #1225107
Benjamin Peterson <benjamin@python.org>
parents: 50818
diff changeset
65 return isinstance(object, (type, types.ClassType))
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
66
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
67 def ismethod(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
68 """Return true if the object is an instance method.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
69
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
70 Instance method objects provide these attributes:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
71 __doc__ documentation string
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
72 __name__ name with which this method was defined
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
73 im_class class object in which this method belongs
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
74 im_func function object containing implementation of method
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
75 im_self instance to which this method is bound, or None"""
19930
36c07a1718e9 In a world with a growing number of subclassable types, replace
Tim Peters <tim.peters@gmail.com>
parents: 19694
diff changeset
76 return isinstance(object, types.MethodType)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
77
19989
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
78 def ismethoddescriptor(object):
19992
9d7ca5914d1c Ensure that isfunction(obj) and (the new) ismethoddescriptor(obj) never
Tim Peters <tim.peters@gmail.com>
parents: 19989
diff changeset
79 """Return true if the object is a method descriptor.
9d7ca5914d1c Ensure that isfunction(obj) and (the new) ismethoddescriptor(obj) never
Tim Peters <tim.peters@gmail.com>
parents: 19989
diff changeset
80
9d7ca5914d1c Ensure that isfunction(obj) and (the new) ismethoddescriptor(obj) never
Tim Peters <tim.peters@gmail.com>
parents: 19989
diff changeset
81 But not if ismethod() or isclass() or isfunction() are true.
19989
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
82
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
83 This is new in Python 2.2, and, for example, is true of int.__add__.
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
84 An object passing this test has a __get__ attribute but not a __set__
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
85 attribute, but beyond that the set of attributes varies. __name__ is
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
86 usually sensible, and __doc__ often is.
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
87
19992
9d7ca5914d1c Ensure that isfunction(obj) and (the new) ismethoddescriptor(obj) never
Tim Peters <tim.peters@gmail.com>
parents: 19989
diff changeset
88 Methods implemented via descriptors that also pass one of the other
9d7ca5914d1c Ensure that isfunction(obj) and (the new) ismethoddescriptor(obj) never
Tim Peters <tim.peters@gmail.com>
parents: 19989
diff changeset
89 tests return false from the ismethoddescriptor() test, simply because
9d7ca5914d1c Ensure that isfunction(obj) and (the new) ismethoddescriptor(obj) never
Tim Peters <tim.peters@gmail.com>
parents: 19989
diff changeset
90 the other tests promise more -- you can, e.g., count on having the
9d7ca5914d1c Ensure that isfunction(obj) and (the new) ismethoddescriptor(obj) never
Tim Peters <tim.peters@gmail.com>
parents: 19989
diff changeset
91 im_func attribute (etc) when an object passes ismethod()."""
19989
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
92 return (hasattr(object, "__get__")
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
93 and not hasattr(object, "__set__") # else it's a data descriptor
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
94 and not ismethod(object) # mutual exclusion
19992
9d7ca5914d1c Ensure that isfunction(obj) and (the new) ismethoddescriptor(obj) never
Tim Peters <tim.peters@gmail.com>
parents: 19989
diff changeset
95 and not isfunction(object)
19989
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
96 and not isclass(object))
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
97
28948
33598e8e49b2 Patch #711902: Cause pydoc to show data descriptor __doc__ strings.
Martin v. Löwis <martin@v.loewis.de>
parents: 28419
diff changeset
98 def isdatadescriptor(object):
33598e8e49b2 Patch #711902: Cause pydoc to show data descriptor __doc__ strings.
Martin v. Löwis <martin@v.loewis.de>
parents: 28419
diff changeset
99 """Return true if the object is a data descriptor.
33598e8e49b2 Patch #711902: Cause pydoc to show data descriptor __doc__ strings.
Martin v. Löwis <martin@v.loewis.de>
parents: 28419
diff changeset
100
33598e8e49b2 Patch #711902: Cause pydoc to show data descriptor __doc__ strings.
Martin v. Löwis <martin@v.loewis.de>
parents: 28419
diff changeset
101 Data descriptors have both a __get__ and a __set__ attribute. Examples are
33598e8e49b2 Patch #711902: Cause pydoc to show data descriptor __doc__ strings.
Martin v. Löwis <martin@v.loewis.de>
parents: 28419
diff changeset
102 properties (defined in Python) and getsets and members (defined in C).
33598e8e49b2 Patch #711902: Cause pydoc to show data descriptor __doc__ strings.
Martin v. Löwis <martin@v.loewis.de>
parents: 28419
diff changeset
103 Typically, data descriptors will also have __name__ and __doc__ attributes
33598e8e49b2 Patch #711902: Cause pydoc to show data descriptor __doc__ strings.
Martin v. Löwis <martin@v.loewis.de>
parents: 28419
diff changeset
104 (properties, getsets, and members have both of these attributes), but this
33598e8e49b2 Patch #711902: Cause pydoc to show data descriptor __doc__ strings.
Martin v. Löwis <martin@v.loewis.de>
parents: 28419
diff changeset
105 is not guaranteed."""
33598e8e49b2 Patch #711902: Cause pydoc to show data descriptor __doc__ strings.
Martin v. Löwis <martin@v.loewis.de>
parents: 28419
diff changeset
106 return (hasattr(object, "__set__") and hasattr(object, "__get__"))
33598e8e49b2 Patch #711902: Cause pydoc to show data descriptor __doc__ strings.
Martin v. Löwis <martin@v.loewis.de>
parents: 28419
diff changeset
107
39226
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
108 if hasattr(types, 'MemberDescriptorType'):
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
109 # CPython and equivalent
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
110 def ismemberdescriptor(object):
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
111 """Return true if the object is a member descriptor.
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
112
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
113 Member descriptors are specialized descriptors defined in extension
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
114 modules."""
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
115 return isinstance(object, types.MemberDescriptorType)
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
116 else:
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
117 # Other implementations
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
118 def ismemberdescriptor(object):
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
119 """Return true if the object is a member descriptor.
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
120
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
121 Member descriptors are specialized descriptors defined in extension
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
122 modules."""
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
123 return False
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
124
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
125 if hasattr(types, 'GetSetDescriptorType'):
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
126 # CPython and equivalent
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
127 def isgetsetdescriptor(object):
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
128 """Return true if the object is a getset descriptor.
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
129
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
130 getset descriptors are specialized descriptors defined in extension
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
131 modules."""
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
132 return isinstance(object, types.GetSetDescriptorType)
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
133 else:
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
134 # Other implementations
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
135 def isgetsetdescriptor(object):
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
136 """Return true if the object is a getset descriptor.
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
137
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
138 getset descriptors are specialized descriptors defined in extension
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
139 modules."""
28cdd43e0569 Patch #1520294: Support for getset and member descriptors in types.py,
Barry Warsaw <barry@python.org>
parents: 39121
diff changeset
140 return False
39228
0b3fd04cdfb4 Whitespace normalization.
Tim Peters <tim.peters@gmail.com>
parents: 39226
diff changeset
141
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
142 def isfunction(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
143 """Return true if the object is a user-defined function.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
144
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
145 Function objects provide these attributes:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
146 __doc__ documentation string
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
147 __name__ name with which this function was defined
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
148 func_code code object containing compiled function bytecode
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
149 func_defaults tuple of any default values for arguments
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
150 func_doc (same as __doc__)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
151 func_globals global namespace in which this function was defined
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
152 func_name (same as __name__)"""
19930
36c07a1718e9 In a world with a growing number of subclassable types, replace
Tim Peters <tim.peters@gmail.com>
parents: 19694
diff changeset
153 return isinstance(object, types.FunctionType)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
154
45386
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
155 def isgeneratorfunction(object):
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
156 """Return true if the object is a user-defined generator function.
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
157
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
158 Generator function objects provides same attributes as functions.
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
159
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
160 See isfunction.__doc__ for attributes listing."""
50405
92ad96544252 simplfy code
Benjamin Peterson <benjamin@python.org>
parents: 50402
diff changeset
161 return bool((isfunction(object) or ismethod(object)) and
92ad96544252 simplfy code
Benjamin Peterson <benjamin@python.org>
parents: 50402
diff changeset
162 object.func_code.co_flags & CO_GENERATOR)
45386
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
163
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
164 def isgenerator(object):
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
165 """Return true if the object is a generator.
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
166
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
167 Generator objects provide these attributes:
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
168 __iter__ defined to support interation over container
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
169 close raises a new GeneratorExit exception inside the
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
170 generator to terminate the iteration
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
171 gi_code code object
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
172 gi_frame frame object or possibly None once the generator has
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
173 been exhausted
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
174 gi_running set to 1 when generator is executing, 0 otherwise
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
175 next return the next item from the container
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
176 send resumes the generator and "sends" a value that becomes
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
177 the result of the current yield-expression
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
178 throw used to raise an exception inside the generator"""
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
179 return isinstance(object, types.GeneratorType)
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
180
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
181 def istraceback(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
182 """Return true if the object is a traceback.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
183
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
184 Traceback objects provide these attributes:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
185 tb_frame frame object at this level
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
186 tb_lasti index of last attempted instruction in bytecode
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
187 tb_lineno current line number in Python source code
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
188 tb_next next inner traceback object (called by this level)"""
19930
36c07a1718e9 In a world with a growing number of subclassable types, replace
Tim Peters <tim.peters@gmail.com>
parents: 19694
diff changeset
189 return isinstance(object, types.TracebackType)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
190
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
191 def isframe(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
192 """Return true if the object is a frame object.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
193
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
194 Frame objects provide these attributes:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
195 f_back next outer frame object (this frame's caller)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
196 f_builtins built-in namespace seen by this frame
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
197 f_code code object being executed in this frame
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
198 f_exc_traceback traceback if raised in this frame, or None
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
199 f_exc_type exception type if raised in this frame, or None
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
200 f_exc_value exception value if raised in this frame, or None
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
201 f_globals global namespace seen by this frame
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
202 f_lasti index of last attempted instruction in bytecode
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
203 f_lineno current line number in Python source code
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
204 f_locals local namespace seen by this frame
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
205 f_restricted 0 or 1 if frame is in restricted execution mode
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
206 f_trace tracing function for this frame, or None"""
19930
36c07a1718e9 In a world with a growing number of subclassable types, replace
Tim Peters <tim.peters@gmail.com>
parents: 19694
diff changeset
207 return isinstance(object, types.FrameType)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
208
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
209 def iscode(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
210 """Return true if the object is a code object.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
211
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
212 Code objects provide these attributes:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
213 co_argcount number of arguments (not including * or ** args)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
214 co_code string of raw compiled bytecode
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
215 co_consts tuple of constants used in the bytecode
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
216 co_filename name of file in which this code object was created
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
217 co_firstlineno number of first line in Python source code
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
218 co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
219 co_lnotab encoded mapping of line numbers to bytecode indices
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
220 co_name name with which this code object was defined
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
221 co_names tuple of names of local variables
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
222 co_nlocals number of local variables
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
223 co_stacksize virtual machine stack space required
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
224 co_varnames tuple of names of arguments and local variables"""
19930
36c07a1718e9 In a world with a growing number of subclassable types, replace
Tim Peters <tim.peters@gmail.com>
parents: 19694
diff changeset
225 return isinstance(object, types.CodeType)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
226
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
227 def isbuiltin(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
228 """Return true if the object is a built-in function or method.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
229
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
230 Built-in functions and methods provide these attributes:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
231 __doc__ documentation string
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
232 __name__ original name of this function or method
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
233 __self__ instance to which a method is bound, or None"""
19930
36c07a1718e9 In a world with a growing number of subclassable types, replace
Tim Peters <tim.peters@gmail.com>
parents: 19694
diff changeset
234 return isinstance(object, types.BuiltinFunctionType)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
235
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
236 def isroutine(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
237 """Return true if the object is any kind of function or method."""
19989
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
238 return (isbuiltin(object)
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
239 or isfunction(object)
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
240 or ismethod(object)
cec9e25af121 After much thrashing, I believe this is a truly minimal patch to teach
Tim Peters <tim.peters@gmail.com>
parents: 19930
diff changeset
241 or ismethoddescriptor(object))
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
242
45386
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
243 def isgenerator(object):
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
244 """Return true if the object is a generator object."""
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
245 return isinstance(object, types.GeneratorType)
1bc923a107d9 Issue #1916. Added isgenerator() and isgeneratorfunction() to
Facundo Batista <facundobatista@gmail.com>
parents: 44632
diff changeset
246
45634
6282dfd5dc49 Since abc._Abstract was replaces by a new type flags the regression test suite fails. I've added a new function inspect.isabstract(). Is the mmethod fine or should I check if object is a instance of type or subclass of object, too?
Christian Heimes <christian@cheimes.de>
parents: 45386
diff changeset
247 def isabstract(object):
6282dfd5dc49 Since abc._Abstract was replaces by a new type flags the regression test suite fails. I've added a new function inspect.isabstract(). Is the mmethod fine or should I check if object is a instance of type or subclass of object, too?
Christian Heimes <christian@cheimes.de>
parents: 45386
diff changeset
248 """Return true if the object is an abstract base class (ABC)."""
46359
8543f8c81da0 Prevent an error when inspect.isabstract() is called with something else than a new-style class.
Amaury Forgeot d'Arc <amauryfa@gmail.com>
parents: 45634
diff changeset
249 return isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT
45634
6282dfd5dc49 Since abc._Abstract was replaces by a new type flags the regression test suite fails. I've added a new function inspect.isabstract(). Is the mmethod fine or should I check if object is a instance of type or subclass of object, too?
Christian Heimes <christian@cheimes.de>
parents: 45386
diff changeset
250
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
251 def getmembers(object, predicate=None):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
252 """Return all members of an object as (name, value) pairs sorted by name.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
253 Optionally, only return members that satisfy a given predicate."""
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
254 results = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
255 for key in dir(object):
50784
65c1938fb9ff #1162154: inspect.getmembers() now skips attributes that raise AttributeError,
Amaury Forgeot d'Arc <amauryfa@gmail.com>
parents: 50405
diff changeset
256 try:
65c1938fb9ff #1162154: inspect.getmembers() now skips attributes that raise AttributeError,
Amaury Forgeot d'Arc <amauryfa@gmail.com>
parents: 50405
diff changeset
257 value = getattr(object, key)
65c1938fb9ff #1162154: inspect.getmembers() now skips attributes that raise AttributeError,
Amaury Forgeot d'Arc <amauryfa@gmail.com>
parents: 50405
diff changeset
258 except AttributeError:
65c1938fb9ff #1162154: inspect.getmembers() now skips attributes that raise AttributeError,
Amaury Forgeot d'Arc <amauryfa@gmail.com>
parents: 50405
diff changeset
259 continue
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
260 if not predicate or predicate(value):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
261 results.append((key, value))
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
262 results.sort()
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
263 return results
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
264
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
265 Attribute = namedtuple('Attribute', 'name kind defining_class object')
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
266
20040
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
267 def classify_class_attrs(cls):
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
268 """Return list of attribute-descriptor tuples.
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
269
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
270 For each name in dir(cls), the return list contains a 4-tuple
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
271 with these elements:
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
272
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
273 0. The name (a string).
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
274
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
275 1. The kind of attribute this is, one of these strings:
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
276 'class method' created via classmethod()
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
277 'static method' created via staticmethod()
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
278 'property' created via property()
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
279 'method' any other flavor of method
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
280 'data' not a method
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
281
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
282 2. The class which defined this attribute (a class).
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
283
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
284 3. The object as obtained directly from the defining class's
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
285 __dict__, not via getattr. This is especially important for
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
286 data attributes: C.data is just a data object, but
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
287 C.__dict__['data'] may be a data descriptor with additional
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
288 info, like a __doc__ string.
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
289 """
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
290
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
291 mro = getmro(cls)
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
292 names = dir(cls)
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
293 result = []
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
294 for name in names:
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
295 # Get the object associated with the name.
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
296 # Getting an obj from the __dict__ sometimes reveals more than
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
297 # using getattr. Static and class methods are dramatic examples.
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
298 if name in cls.__dict__:
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
299 obj = cls.__dict__[name]
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
300 else:
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
301 obj = getattr(cls, name)
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
302
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
303 # Figure out where it was defined.
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
304 homecls = getattr(obj, "__objclass__", None)
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
305 if homecls is None:
20445
27ab0327b2fc Get rid of __defined__ and tp_defined -- there's no need to
Guido van Rossum <guido@python.org>
parents: 20040
diff changeset
306 # search the dicts.
20040
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
307 for base in mro:
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
308 if name in base.__dict__:
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
309 homecls = base
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
310 break
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
311
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
312 # Get the object again, in order to get it from the defining
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
313 # __dict__ instead of via getattr (if possible).
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
314 if homecls is not None and name in homecls.__dict__:
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
315 obj = homecls.__dict__[name]
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
316
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
317 # Also get the object via getattr.
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
318 obj_via_getattr = getattr(cls, name)
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
319
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
320 # Classify the object.
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
321 if isinstance(obj, staticmethod):
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
322 kind = "static method"
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
323 elif isinstance(obj, classmethod):
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
324 kind = "class method"
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
325 elif isinstance(obj, property):
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
326 kind = "property"
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
327 elif (ismethod(obj_via_getattr) or
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
328 ismethoddescriptor(obj_via_getattr)):
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
329 kind = "method"
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
330 else:
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
331 kind = "data"
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
332
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
333 result.append(Attribute(name, kind, homecls, obj))
20040
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
334
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
335 return result
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
336
20036
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
337 # ----------------------------------------------------------- class helpers
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
338 def _searchbases(cls, accum):
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
339 # Simulate the "classic class" search order.
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
340 if cls in accum:
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
341 return
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
342 accum.append(cls)
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
343 for base in cls.__bases__:
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
344 _searchbases(base, accum)
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
345
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
346 def getmro(cls):
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
347 "Return tuple of base classes (including cls) in method resolution order."
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
348 if hasattr(cls, "__mro__"):
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
349 return cls.__mro__
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
350 else:
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
351 result = []
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
352 _searchbases(cls, result)
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
353 return tuple(result)
ab62d147ba90 Add a function to compute a class's method resolution order. This is
Tim Peters <tim.peters@gmail.com>
parents: 19992
diff changeset
354
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
355 # -------------------------------------------------- source code extraction
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
356 def indentsize(line):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
357 """Return the indent size, in spaces, at the start of a line of text."""
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
358 expline = string.expandtabs(line)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
359 return len(expline) - len(string.lstrip(expline))
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
360
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
361 def getdoc(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
362 """Get the documentation string for an object.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
363
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
364 All tabs are expanded to spaces. To clean up docstrings that are
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
365 indented to line up with blocks of code, any whitespace than can be
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
366 uniformly removed from the second line onwards is removed."""
22348
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
367 try:
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
368 doc = object.__doc__
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
369 except AttributeError:
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
370 return None
23486
bb5790c6cdaa Use types.StringTypes instead of explicit (str, unicode) list
Michael W. Hudson <mwh@python.net>
parents: 23281
diff changeset
371 if not isinstance(doc, types.StringTypes):
22348
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
372 return None
47506
ebf6f639e117 Factor out docstring dedenting from inspect.getdoc() into inspect.cleandoc()
Georg Brandl <georg@python.org>
parents: 46359
diff changeset
373 return cleandoc(doc)
ebf6f639e117 Factor out docstring dedenting from inspect.getdoc() into inspect.cleandoc()
Georg Brandl <georg@python.org>
parents: 46359
diff changeset
374
ebf6f639e117 Factor out docstring dedenting from inspect.getdoc() into inspect.cleandoc()
Georg Brandl <georg@python.org>
parents: 46359
diff changeset
375 def cleandoc(doc):
ebf6f639e117 Factor out docstring dedenting from inspect.getdoc() into inspect.cleandoc()
Georg Brandl <georg@python.org>
parents: 46359
diff changeset
376 """Clean up indentation from docstrings.
ebf6f639e117 Factor out docstring dedenting from inspect.getdoc() into inspect.cleandoc()
Georg Brandl <georg@python.org>
parents: 46359
diff changeset
377
ebf6f639e117 Factor out docstring dedenting from inspect.getdoc() into inspect.cleandoc()
Georg Brandl <georg@python.org>
parents: 46359
diff changeset
378 Any whitespace that can be uniformly removed from the second line
ebf6f639e117 Factor out docstring dedenting from inspect.getdoc() into inspect.cleandoc()
Georg Brandl <georg@python.org>
parents: 46359
diff changeset
379 onwards is removed."""
22348
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
380 try:
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
381 lines = string.split(string.expandtabs(doc), '\n')
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
382 except UnicodeError:
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
383 return None
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
384 else:
26467
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
385 # Find minimum indentation of any non-blank lines after first line.
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
386 margin = sys.maxint
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
387 for line in lines[1:]:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
388 content = len(string.lstrip(line))
26467
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
389 if content:
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
390 indent = len(line) - content
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
391 margin = min(margin, indent)
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
392 # Remove indentation.
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
393 if lines:
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
394 lines[0] = lines[0].lstrip()
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
395 if margin < sys.maxint:
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
396 for i in range(1, len(lines)): lines[i] = lines[i][margin:]
26467
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
397 # Remove any trailing or leading blank lines.
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
398 while lines and not lines[-1]:
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
399 lines.pop()
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
400 while lines and not lines[0]:
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
401 lines.pop(0)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
402 return string.join(lines, '\n')
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
403
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
404 def getfile(object):
16927
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
405 """Work out which source or compiled file an object was defined in."""
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
406 if ismodule(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
407 if hasattr(object, '__file__'):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
408 return object.__file__
29617
badcd158d81c A bit o' reformatting and removal of non-_getframe currentframe().
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29613
diff changeset
409 raise TypeError('arg is a built-in module')
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
410 if isclass(object):
17473
339a93b0084c Robustify getfile() against classes that lie about their __module__s
Ka-Ping Yee <ping@zesty.ca>
parents: 17469
diff changeset
411 object = sys.modules.get(object.__module__)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
412 if hasattr(object, '__file__'):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
413 return object.__file__
29617
badcd158d81c A bit o' reformatting and removal of non-_getframe currentframe().
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29613
diff changeset
414 raise TypeError('arg is a built-in class')
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
415 if ismethod(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
416 object = object.im_func
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
417 if isfunction(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
418 object = object.func_code
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
419 if istraceback(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
420 object = object.tb_frame
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
421 if isframe(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
422 object = object.f_code
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
423 if iscode(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
424 return object.co_filename
29668
36a17904a3ed Whitespace normalization.
Tim Peters <tim.peters@gmail.com>
parents: 29617
diff changeset
425 raise TypeError('arg is not a module, class, method, '
29617
badcd158d81c A bit o' reformatting and removal of non-_getframe currentframe().
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29613
diff changeset
426 'function, traceback, frame, or code object')
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
427
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
428 ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
429
17370
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
430 def getmoduleinfo(path):
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
431 """Get the module name, suffix, mode, and module type for a given file."""
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
432 filename = os.path.basename(path)
48121
1140774f69a5 Silence (Syntax|Deprecation)Warning for 'inspect'. Had to remove tuple
Brett Cannon <bcannon@gmail.com>
parents: 47506
diff changeset
433 suffixes = map(lambda info:
1140774f69a5 Silence (Syntax|Deprecation)Warning for 'inspect'. Had to remove tuple
Brett Cannon <bcannon@gmail.com>
parents: 47506
diff changeset
434 (-len(info[0]), info[0], info[1], info[2]),
1140774f69a5 Silence (Syntax|Deprecation)Warning for 'inspect'. Had to remove tuple
Brett Cannon <bcannon@gmail.com>
parents: 47506
diff changeset
435 imp.get_suffixes())
17370
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
436 suffixes.sort() # try longest suffixes first, in case they overlap
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
437 for neglen, suffix, mode, mtype in suffixes:
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
438 if filename[neglen:] == suffix:
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
439 return ModuleInfo(filename[:neglen], suffix, mode, mtype)
17370
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
440
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
441 def getmodulename(path):
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
442 """Return the module name for a given file, or None."""
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
443 info = getmoduleinfo(path)
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
444 if info: return info[0]
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
445
16927
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
446 def getsourcefile(object):
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
447 """Return the Python source file an object was defined in, if it exists."""
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
448 filename = getfile(object)
34545
9d66fba78444 Replace list of constants with tuples of constants.
Raymond Hettinger <python@rcn.com>
parents: 34152
diff changeset
449 if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
16927
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
450 filename = filename[:-4] + '.py'
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
451 for suffix, mode, kind in imp.get_suffixes():
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
452 if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
453 # Looks like a binary file. We want to only return a text file.
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
454 return None
38056
69f0457c17bb Fix infinite regress when inspecting <string> or <stdin> frames.
Phillip J. Eby <pje@telecommunity.com>
parents: 37593
diff changeset
455 if os.path.exists(filename):
69f0457c17bb Fix infinite regress when inspecting <string> or <stdin> frames.
Phillip J. Eby <pje@telecommunity.com>
parents: 37593
diff changeset
456 return filename
39053
b978afe7cab6 Fix SF#1516184 and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 38057
diff changeset
457 # only return a non-existent filename if the module has a PEP 302 loader
b978afe7cab6 Fix SF#1516184 and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 38057
diff changeset
458 if hasattr(getmodule(object, filename), '__loader__'):
16927
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
459 return filename
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
460
39053
b978afe7cab6 Fix SF#1516184 and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 38057
diff changeset
461 def getabsfile(object, _filename=None):
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
462 """Return an absolute path to the source or compiled file for an object.
16927
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
463
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
464 The idea is for each object to have a unique origin, so this routine
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
465 normalizes the result as much as possible."""
39121
5c903f650719 Fix SF#1516184 (again) and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 39053
diff changeset
466 if _filename is None:
5c903f650719 Fix SF#1516184 (again) and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 39053
diff changeset
467 _filename = getsourcefile(object) or getfile(object)
5c903f650719 Fix SF#1516184 (again) and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 39053
diff changeset
468 return os.path.normcase(os.path.abspath(_filename))
16927
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
469
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
470 modulesbyfile = {}
39796
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
471 _filesbymodname = {}
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
472
39053
b978afe7cab6 Fix SF#1516184 and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 38057
diff changeset
473 def getmodule(object, _filename=None):
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
474 """Return the module an object was defined in, or None if not found."""
17469
926b64fba5e7 Remove duplicate type objects from isroutine() and isbuiltin().
Ka-Ping Yee <ping@zesty.ca>
parents: 17446
diff changeset
475 if ismodule(object):
926b64fba5e7 Remove duplicate type objects from isroutine() and isbuiltin().
Ka-Ping Yee <ping@zesty.ca>
parents: 17446
diff changeset
476 return object
33455
9e3c52ca3a04 Use __module__ attribute when available instead of using isclass() predicate
Johannes Gijsbers <jlg@dds.nl>
parents: 33172
diff changeset
477 if hasattr(object, '__module__'):
16898
dcea09388332 Add __author__ variable.
Ka-Ping Yee <ping@zesty.ca>
parents: 16887
diff changeset
478 return sys.modules.get(object.__module__)
39796
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
479 # Try the filename to modulename cache
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
480 if _filename is not None and _filename in modulesbyfile:
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
481 return sys.modules.get(modulesbyfile[_filename])
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
482 # Try the cache again with the absolute file name
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
483 try:
39053
b978afe7cab6 Fix SF#1516184 and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 38057
diff changeset
484 file = getabsfile(object, _filename)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
485 except TypeError:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
486 return None
23620
a1de0bab5475 SF 563203. Replaced 'has_key()' with 'in'.
Raymond Hettinger <python@rcn.com>
parents: 23613
diff changeset
487 if file in modulesbyfile:
28419
a9351270385a Make module lookup a little more robust (certain kinds of fiddling to
Ka-Ping Yee <ping@zesty.ca>
parents: 27297
diff changeset
488 return sys.modules.get(modulesbyfile[file])
39796
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
489 # Update the filename to module name cache and check yet again
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
490 # Copy sys.modules in order to cope with changes while iterating
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
491 for modname, module in sys.modules.items():
37576
d11366f7e1e7 Updated the warnings, linecache, inspect, traceback, site, and doctest modules
Phillip J. Eby <pje@telecommunity.com>
parents: 35640
diff changeset
492 if ismodule(module) and hasattr(module, '__file__'):
39796
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
493 f = module.__file__
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
494 if f == _filesbymodname.get(modname, None):
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
495 # Have already mapped this module, so skip it
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
496 continue
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
497 _filesbymodname[modname] = f
39053
b978afe7cab6 Fix SF#1516184 and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 38057
diff changeset
498 f = getabsfile(module)
39796
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
499 # Always map to the name the module knows itself by
39053
b978afe7cab6 Fix SF#1516184 and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 38057
diff changeset
500 modulesbyfile[f] = modulesbyfile[
b978afe7cab6 Fix SF#1516184 and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 38057
diff changeset
501 os.path.realpath(f)] = module.__name__
23620
a1de0bab5475 SF 563203. Replaced 'has_key()' with 'in'.
Raymond Hettinger <python@rcn.com>
parents: 23613
diff changeset
502 if file in modulesbyfile:
28419
a9351270385a Make module lookup a little more robust (certain kinds of fiddling to
Ka-Ping Yee <ping@zesty.ca>
parents: 27297
diff changeset
503 return sys.modules.get(modulesbyfile[file])
39796
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
504 # Check the main module
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
505 main = sys.modules['__main__']
29484
3133b50e99f3 Return None to signal that the module the object was defined in was not found when object has no __name__ attr but is needed to figure out location of object.
Brett Cannon <bcannon@gmail.com>
parents: 28948
diff changeset
506 if not hasattr(object, '__name__'):
3133b50e99f3 Return None to signal that the module the object was defined in was not found when object has no __name__ attr but is needed to figure out location of object.
Brett Cannon <bcannon@gmail.com>
parents: 28948
diff changeset
507 return None
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
508 if hasattr(main, object.__name__):
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
509 mainobject = getattr(main, object.__name__)
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
510 if mainobject is object:
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
511 return main
39796
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
512 # Check builtins
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
513 builtin = sys.modules['__builtin__']
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
514 if hasattr(builtin, object.__name__):
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
515 builtinobject = getattr(builtin, object.__name__)
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
516 if builtinobject is object:
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
517 return builtin
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
518
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
519 def findsource(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
520 """Return the entire source file and starting line number for an object.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
521
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
522 The argument may be a module, class, method, function, traceback, frame,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
523 or code object. The source code is returned as a list of all the lines
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
524 in the file and the line number indexes a line in that list. An IOError
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
525 is raised if the source code cannot be retrieved."""
54041
347e59ea1a71 Issue #4050: inspect.findsource/getsource now raise an IOError if the 'source'
R. David Murray <rdmurray@bitdance.com>
parents: 50834
diff changeset
526 file = getsourcefile(object)
347e59ea1a71 Issue #4050: inspect.findsource/getsource now raise an IOError if the 'source'
R. David Murray <rdmurray@bitdance.com>
parents: 50834
diff changeset
527 if not file:
347e59ea1a71 Issue #4050: inspect.findsource/getsource now raise an IOError if the 'source'
R. David Murray <rdmurray@bitdance.com>
parents: 50834
diff changeset
528 raise IOError('source code not available')
39796
38ba9524783a Fix the speed regression in inspect.py by adding another cache to speed up getmodule(). Patch #1553314
Nick Coghlan <ncoghlan@gmail.com>
parents: 39228
diff changeset
529 module = getmodule(object, file)
38057
8f7abc2ba7d0 Fix another problem in inspect: if the module for an object cannot be found, don't try to give its __dict__ to linecache.
Georg Brandl <georg@python.org>
parents: 38056
diff changeset
530 if module:
8f7abc2ba7d0 Fix another problem in inspect: if the module for an object cannot be found, don't try to give its __dict__ to linecache.
Georg Brandl <georg@python.org>
parents: 38056
diff changeset
531 lines = linecache.getlines(file, module.__dict__)
8f7abc2ba7d0 Fix another problem in inspect: if the module for an object cannot be found, don't try to give its __dict__ to linecache.
Georg Brandl <georg@python.org>
parents: 38056
diff changeset
532 else:
8f7abc2ba7d0 Fix another problem in inspect: if the module for an object cannot be found, don't try to give its __dict__ to linecache.
Georg Brandl <georg@python.org>
parents: 38056
diff changeset
533 lines = linecache.getlines(file)
22486
8ecd1bad2408 Use linecache for loading source code. Closes SF patch 490374.
Neil Schemenauer <nascheme@enme.ucalgary.ca>
parents: 22348
diff changeset
534 if not lines:
29617
badcd158d81c A bit o' reformatting and removal of non-_getframe currentframe().
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29613
diff changeset
535 raise IOError('could not get source code')
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
536
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
537 if ismodule(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
538 return lines, 0
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
539
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
540 if isclass(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
541 name = object.__name__
40097
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
542 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
543 # make some effort to find the best matching class definition:
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
544 # use the one with the least indentation, which is the one
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
545 # that's most probably not inside a function definition.
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
546 candidates = []
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
547 for i in range(len(lines)):
40097
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
548 match = pat.match(lines[i])
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
549 if match:
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
550 # if it's at toplevel, it's already the best one
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
551 if lines[i][0] == 'c':
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
552 return lines, i
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
553 # else add whitespace to candidate list
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
554 candidates.append((match.group(1), i))
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
555 if candidates:
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
556 # this will sort by whitespace, and by line number,
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
557 # less whitespace first
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
558 candidates.sort()
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
559 return lines, candidates[0][1]
29617
badcd158d81c A bit o' reformatting and removal of non-_getframe currentframe().
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29613
diff changeset
560 else:
badcd158d81c A bit o' reformatting and removal of non-_getframe currentframe().
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29613
diff changeset
561 raise IOError('could not find class definition')
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
562
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
563 if ismethod(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
564 object = object.im_func
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
565 if isfunction(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
566 object = object.func_code
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
567 if istraceback(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
568 object = object.tb_frame
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
569 if isframe(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
570 object = object.f_code
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
571 if iscode(object):
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
572 if not hasattr(object, 'co_firstlineno'):
29617
badcd158d81c A bit o' reformatting and removal of non-_getframe currentframe().
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29613
diff changeset
573 raise IOError('could not find function definition')
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
574 lnum = object.co_firstlineno - 1
34152
bbdaacc44f6f Patch #1011890: fix inspect.getsource breaking with line-continuation &
Johannes Gijsbers <jlg@dds.nl>
parents: 33528
diff changeset
575 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
576 while lnum > 0:
17020
953c50f12184 Fix findsource() to work for derived classes.
Ka-Ping Yee <ping@zesty.ca>
parents: 16938
diff changeset
577 if pat.match(lines[lnum]): break
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
578 lnum = lnum - 1
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
579 return lines, lnum
29617
badcd158d81c A bit o' reformatting and removal of non-_getframe currentframe().
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29613
diff changeset
580 raise IOError('could not find code object')
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
581
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
582 def getcomments(object):
22639
9c2ca37bdeec Fix getcomments() so that it doesn't fail with TypeErrors.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 22563
diff changeset
583 """Get lines of comments immediately preceding an object's source code.
9c2ca37bdeec Fix getcomments() so that it doesn't fail with TypeErrors.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 22563
diff changeset
584
9c2ca37bdeec Fix getcomments() so that it doesn't fail with TypeErrors.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 22563
diff changeset
585 Returns None when source can't be found.
9c2ca37bdeec Fix getcomments() so that it doesn't fail with TypeErrors.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 22563
diff changeset
586 """
9c2ca37bdeec Fix getcomments() so that it doesn't fail with TypeErrors.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 22563
diff changeset
587 try:
9c2ca37bdeec Fix getcomments() so that it doesn't fail with TypeErrors.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 22563
diff changeset
588 lines, lnum = findsource(object)
9c2ca37bdeec Fix getcomments() so that it doesn't fail with TypeErrors.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 22563
diff changeset
589 except (IOError, TypeError):
9c2ca37bdeec Fix getcomments() so that it doesn't fail with TypeErrors.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 22563
diff changeset
590 return None
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
591
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
592 if ismodule(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
593 # Look for a comment block at the top of the file.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
594 start = 0
17446
0184c50a8751 Robustify getcomments() so it doesn't crash on empty files.
Ka-Ping Yee <ping@zesty.ca>
parents: 17370
diff changeset
595 if lines and lines[0][:2] == '#!': start = 1
34545
9d66fba78444 Replace list of constants with tuples of constants.
Raymond Hettinger <python@rcn.com>
parents: 34152
diff changeset
596 while start < len(lines) and string.strip(lines[start]) in ('', '#'):
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
597 start = start + 1
17446
0184c50a8751 Robustify getcomments() so it doesn't crash on empty files.
Ka-Ping Yee <ping@zesty.ca>
parents: 17370
diff changeset
598 if start < len(lines) and lines[start][:1] == '#':
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
599 comments = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
600 end = start
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
601 while end < len(lines) and lines[end][:1] == '#':
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
602 comments.append(string.expandtabs(lines[end]))
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
603 end = end + 1
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
604 return string.join(comments, '')
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
605
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
606 # Look for a preceding block of comments at the same indentation.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
607 elif lnum > 0:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
608 indent = indentsize(lines[lnum])
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
609 end = lnum - 1
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
610 if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
611 indentsize(lines[end]) == indent:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
612 comments = [string.lstrip(string.expandtabs(lines[end]))]
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
613 if end > 0:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
614 end = end - 1
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
615 comment = string.lstrip(string.expandtabs(lines[end]))
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
616 while comment[:1] == '#' and indentsize(lines[end]) == indent:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
617 comments[:0] = [comment]
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
618 end = end - 1
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
619 if end < 0: break
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
620 comment = string.lstrip(string.expandtabs(lines[end]))
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
621 while comments and string.strip(comments[0]) == '#':
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
622 comments[:1] = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
623 while comments and string.strip(comments[-1]) == '#':
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
624 comments[-1:] = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
625 return string.join(comments, '')
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
626
18351
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
627 class EndOfBlock(Exception): pass
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
628
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
629 class BlockFinder:
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
630 """Provide a tokeneater() method to detect the end of a code block."""
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
631 def __init__(self):
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
632 self.indent = 0
34740
3bb759498767 Patch #1159931/bug #1143895: inspect.getsource failed when functions,
Johannes Gijsbers <jlg@dds.nl>
parents: 34734
diff changeset
633 self.islambda = False
34152
bbdaacc44f6f Patch #1011890: fix inspect.getsource breaking with line-continuation &
Johannes Gijsbers <jlg@dds.nl>
parents: 33528
diff changeset
634 self.started = False
bbdaacc44f6f Patch #1011890: fix inspect.getsource breaking with line-continuation &
Johannes Gijsbers <jlg@dds.nl>
parents: 33528
diff changeset
635 self.passline = False
35640
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
636 self.last = 1
18351
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
637
48121
1140774f69a5 Silence (Syntax|Deprecation)Warning for 'inspect'. Had to remove tuple
Brett Cannon <bcannon@gmail.com>
parents: 47506
diff changeset
638 def tokeneater(self, type, token, srow_scol, erow_ecol, line):
1140774f69a5 Silence (Syntax|Deprecation)Warning for 'inspect'. Had to remove tuple
Brett Cannon <bcannon@gmail.com>
parents: 47506
diff changeset
639 srow, scol = srow_scol
1140774f69a5 Silence (Syntax|Deprecation)Warning for 'inspect'. Had to remove tuple
Brett Cannon <bcannon@gmail.com>
parents: 47506
diff changeset
640 erow, ecol = erow_ecol
18351
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
641 if not self.started:
35640
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
642 # look for the first "def", "class" or "lambda"
34152
bbdaacc44f6f Patch #1011890: fix inspect.getsource breaking with line-continuation &
Johannes Gijsbers <jlg@dds.nl>
parents: 33528
diff changeset
643 if token in ("def", "class", "lambda"):
34740
3bb759498767 Patch #1159931/bug #1143895: inspect.getsource failed when functions,
Johannes Gijsbers <jlg@dds.nl>
parents: 34734
diff changeset
644 if token == "lambda":
3bb759498767 Patch #1159931/bug #1143895: inspect.getsource failed when functions,
Johannes Gijsbers <jlg@dds.nl>
parents: 34734
diff changeset
645 self.islambda = True
34152
bbdaacc44f6f Patch #1011890: fix inspect.getsource breaking with line-continuation &
Johannes Gijsbers <jlg@dds.nl>
parents: 33528
diff changeset
646 self.started = True
35640
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
647 self.passline = True # skip to the end of the line
18351
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
648 elif type == tokenize.NEWLINE:
35640
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
649 self.passline = False # stop skipping when a NEWLINE is seen
18351
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
650 self.last = srow
35640
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
651 if self.islambda: # lambdas always end at the first NEWLINE
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
652 raise EndOfBlock
34152
bbdaacc44f6f Patch #1011890: fix inspect.getsource breaking with line-continuation &
Johannes Gijsbers <jlg@dds.nl>
parents: 33528
diff changeset
653 elif self.passline:
bbdaacc44f6f Patch #1011890: fix inspect.getsource breaking with line-continuation &
Johannes Gijsbers <jlg@dds.nl>
parents: 33528
diff changeset
654 pass
18351
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
655 elif type == tokenize.INDENT:
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
656 self.indent = self.indent + 1
34152
bbdaacc44f6f Patch #1011890: fix inspect.getsource breaking with line-continuation &
Johannes Gijsbers <jlg@dds.nl>
parents: 33528
diff changeset
657 self.passline = True
18351
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
658 elif type == tokenize.DEDENT:
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
659 self.indent = self.indent - 1
35640
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
660 # the end of matching indent/dedent pairs end a block
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
661 # (note that this only works for "def"/"class" blocks,
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
662 # not e.g. for "if: else:" or "try: finally:" blocks)
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
663 if self.indent <= 0:
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
664 raise EndOfBlock
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
665 elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
666 # any other token on the same indentation level end the previous
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
667 # block as well, except the pseudo-tokens COMMENT and NL.
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
668 raise EndOfBlock
18351
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
669
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
670 def getblock(lines):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
671 """Extract the block of code at the top of the given list of lines."""
35640
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
672 blockfinder = BlockFinder()
18351
44a87c300f2b Turns out Neil didn't intend for *all* of his gen-branch work to get
Tim Peters <tim.peters@gmail.com>
parents: 18148
diff changeset
673 try:
35640
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
674 tokenize.tokenize(iter(lines).next, blockfinder.tokeneater)
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
675 except (EndOfBlock, IndentationError):
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
676 pass
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
677 return lines[:blockfinder.last]
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
678
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
679 def getsourcelines(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
680 """Return a list of source lines and starting line number for an object.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
681
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
682 The argument may be a module, class, method, function, traceback, frame,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
683 or code object. The source code is returned as a list of the lines
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
684 corresponding to the object and the line number indicates where in the
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
685 original source file the first line of code was found. An IOError is
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
686 raised if the source code cannot be retrieved."""
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
687 lines, lnum = findsource(object)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
688
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
689 if ismodule(object): return lines, 0
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
690 else: return getblock(lines[lnum:]), lnum + 1
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
691
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
692 def getsource(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
693 """Return the text of the source code for an object.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
694
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
695 The argument may be a module, class, method, function, traceback, frame,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
696 or code object. The source code is returned as a single string. An
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
697 IOError is raised if the source code cannot be retrieved."""
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
698 lines, lnum = getsourcelines(object)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
699 return string.join(lines, '')
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
700
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
701 # --------------------------------------------------- class tree extraction
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
702 def walktree(classes, children, parent):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
703 """Recursive helper function for getclasstree()."""
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
704 results = []
34734
d355da1d7c8f Apply itemgetter() instead of lambda.
Raymond Hettinger <python@rcn.com>
parents: 34545
diff changeset
705 classes.sort(key=attrgetter('__module__', '__name__'))
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
706 for c in classes:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
707 results.append((c, c.__bases__))
23620
a1de0bab5475 SF 563203. Replaced 'has_key()' with 'in'.
Raymond Hettinger <python@rcn.com>
parents: 23613
diff changeset
708 if c in children:
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
709 results.append(walktree(children[c], children, c))
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
710 return results
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
711
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
712 def getclasstree(classes, unique=0):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
713 """Arrange the given list of classes into a hierarchy of nested lists.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
714
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
715 Where a nested list appears, it contains classes derived from the class
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
716 whose entry immediately precedes the list. Each entry is a 2-tuple
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
717 containing a class and a tuple of its base classes. If the 'unique'
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
718 argument is true, exactly one entry appears in the returned structure
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
719 for each class in the given list. Otherwise, classes using multiple
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
720 inheritance and their descendants will appear multiple times."""
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
721 children = {}
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
722 roots = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
723 for c in classes:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
724 if c.__bases__:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
725 for parent in c.__bases__:
23620
a1de0bab5475 SF 563203. Replaced 'has_key()' with 'in'.
Raymond Hettinger <python@rcn.com>
parents: 23613
diff changeset
726 if not parent in children:
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
727 children[parent] = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
728 children[parent].append(c)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
729 if unique and parent in classes: break
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
730 elif c not in roots:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
731 roots.append(c)
23634
dbee2f628a90 Replaced .keys() with dictionary iterators
Raymond Hettinger <python@rcn.com>
parents: 23620
diff changeset
732 for parent in children:
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
733 if parent not in classes:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
734 roots.append(parent)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
735 return walktree(roots, children, None)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
736
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
737 # ------------------------------------------------ argument list extraction
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
738 Arguments = namedtuple('Arguments', 'args varargs keywords')
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
739
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
740 def getargs(co):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
741 """Get information about the arguments accepted by a code object.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
742
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
743 Three things are returned: (args, varargs, varkw), where 'args' is
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
744 a list of argument names (possibly containing nested lists), and
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
745 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
29613
0bdb4aced6e2 Fix for SF bug 620190: getargspec() doesn't work with methods.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29484
diff changeset
746
0bdb4aced6e2 Fix for SF bug 620190: getargspec() doesn't work with methods.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29484
diff changeset
747 if not iscode(co):
0bdb4aced6e2 Fix for SF bug 620190: getargspec() doesn't work with methods.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29484
diff changeset
748 raise TypeError('arg is not a code object')
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
749
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
750 nargs = co.co_argcount
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
751 names = co.co_varnames
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
752 args = list(names[:nargs])
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
753 step = 0
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
754
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
755 # The following acrobatics are for anonymous (tuple) arguments.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
756 for i in range(nargs):
34545
9d66fba78444 Replace list of constants with tuples of constants.
Raymond Hettinger <python@rcn.com>
parents: 34152
diff changeset
757 if args[i][:1] in ('', '.'):
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
758 stack, remain, count = [], [], []
42214
6319adb0041d Patch #1739696: use code.co_code only if really necessary
Georg Brandl <georg@python.org>
parents: 40097
diff changeset
759 while step < len(co.co_code):
6319adb0041d Patch #1739696: use code.co_code only if really necessary
Georg Brandl <georg@python.org>
parents: 40097
diff changeset
760 op = ord(co.co_code[step])
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
761 step = step + 1
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
762 if op >= dis.HAVE_ARGUMENT:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
763 opname = dis.opname[op]
42214
6319adb0041d Patch #1739696: use code.co_code only if really necessary
Georg Brandl <georg@python.org>
parents: 40097
diff changeset
764 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
765 step = step + 2
34545
9d66fba78444 Replace list of constants with tuples of constants.
Raymond Hettinger <python@rcn.com>
parents: 34152
diff changeset
766 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
767 remain.append(value)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
768 count.append(value)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
769 elif opname == 'STORE_FAST':
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
770 stack.append(names[value])
33137
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
771
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
772 # Special case for sublists of length 1: def foo((bar))
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
773 # doesn't generate the UNPACK_TUPLE bytecode, so if
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
774 # `remain` is empty here, we have such a sublist.
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
775 if not remain:
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
776 stack[0] = [stack[0]]
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
777 break
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
778 else:
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
779 remain[-1] = remain[-1] - 1
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
780 while remain[-1] == 0:
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
781 remain.pop()
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
782 size = count.pop()
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
783 stack[-size:] = [stack[-size:]]
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
784 if not remain: break
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
785 remain[-1] = remain[-1] - 1
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
786 if not remain: break
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
787 args[i] = stack[0]
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
788
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
789 varargs = None
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
790 if co.co_flags & CO_VARARGS:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
791 varargs = co.co_varnames[nargs]
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
792 nargs = nargs + 1
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
793 varkw = None
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
794 if co.co_flags & CO_VARKEYWORDS:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
795 varkw = co.co_varnames[nargs]
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
796 return Arguments(args, varargs, varkw)
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
797
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
798 ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
799
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
800 def getargspec(func):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
801 """Get the names and default values of a function's arguments.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
802
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
803 A tuple of four things is returned: (args, varargs, varkw, defaults).
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
804 'args' is a list of the argument names (it may contain nested lists).
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
805 'varargs' and 'varkw' are the names of the * and ** arguments or None.
29613
0bdb4aced6e2 Fix for SF bug 620190: getargspec() doesn't work with methods.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29484
diff changeset
806 'defaults' is an n-tuple of the default values of the last n arguments.
0bdb4aced6e2 Fix for SF bug 620190: getargspec() doesn't work with methods.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29484
diff changeset
807 """
0bdb4aced6e2 Fix for SF bug 620190: getargspec() doesn't work with methods.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29484
diff changeset
808
0bdb4aced6e2 Fix for SF bug 620190: getargspec() doesn't work with methods.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29484
diff changeset
809 if ismethod(func):
0bdb4aced6e2 Fix for SF bug 620190: getargspec() doesn't work with methods.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29484
diff changeset
810 func = func.im_func
0bdb4aced6e2 Fix for SF bug 620190: getargspec() doesn't work with methods.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29484
diff changeset
811 if not isfunction(func):
0bdb4aced6e2 Fix for SF bug 620190: getargspec() doesn't work with methods.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29484
diff changeset
812 raise TypeError('arg is not a Python function')
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
813 args, varargs, varkw = getargs(func.func_code)
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
814 return ArgSpec(args, varargs, varkw, func.func_defaults)
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
815
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
816 ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
817
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
818 def getargvalues(frame):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
819 """Get information about arguments passed into a particular frame.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
820
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
821 A tuple of four things is returned: (args, varargs, varkw, locals).
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
822 'args' is a list of the argument names (it may contain nested lists).
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
823 'varargs' and 'varkw' are the names of the * and ** arguments or None.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
824 'locals' is the locals dictionary of the given frame."""
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
825 args, varargs, varkw = getargs(frame.f_code)
49568
df7422460660 Merged revisions 66995-66996 via svnmerge from
Benjamin Peterson <benjamin@python.org>
parents: 48277
diff changeset
826 return ArgInfo(args, varargs, varkw, frame.f_locals)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
827
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
828 def joinseq(seq):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
829 if len(seq) == 1:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
830 return '(' + seq[0] + ',)'
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
831 else:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
832 return '(' + string.join(seq, ', ') + ')'
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
833
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
834 def strseq(object, convert, join=joinseq):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
835 """Recursively walk a sequence, stringifying each element."""
34545
9d66fba78444 Replace list of constants with tuples of constants.
Raymond Hettinger <python@rcn.com>
parents: 34152
diff changeset
836 if type(object) in (list, tuple):
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
837 return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
838 else:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
839 return convert(object)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
840
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
841 def formatargspec(args, varargs=None, varkw=None, defaults=None,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
842 formatarg=str,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
843 formatvarargs=lambda name: '*' + name,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
844 formatvarkw=lambda name: '**' + name,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
845 formatvalue=lambda value: '=' + repr(value),
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
846 join=joinseq):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
847 """Format an argument spec from the 4 values returned by getargspec.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
848
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
849 The first four arguments are (args, varargs, varkw, defaults). The
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
850 other four arguments are the corresponding optional formatting functions
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
851 that are called to turn names and values into strings. The ninth
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
852 argument is an optional function to format the sequence of arguments."""
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
853 specs = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
854 if defaults:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
855 firstdefault = len(args) - len(defaults)
50818
cb290482a1a7 use enumerate
Benjamin Peterson <benjamin@python.org>
parents: 50784
diff changeset
856 for i, arg in enumerate(args):
cb290482a1a7 use enumerate
Benjamin Peterson <benjamin@python.org>
parents: 50784
diff changeset
857 spec = strseq(arg, formatarg, join)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
858 if defaults and i >= firstdefault:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
859 spec = spec + formatvalue(defaults[i - firstdefault])
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
860 specs.append(spec)
23613
4a1f5bd486ff Replaced boolean test with is None
Raymond Hettinger <python@rcn.com>
parents: 23486
diff changeset
861 if varargs is not None:
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
862 specs.append(formatvarargs(varargs))
23613
4a1f5bd486ff Replaced boolean test with is None
Raymond Hettinger <python@rcn.com>
parents: 23486
diff changeset
863 if varkw is not None:
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
864 specs.append(formatvarkw(varkw))
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
865 return '(' + string.join(specs, ', ') + ')'
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
866
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
867 def formatargvalues(args, varargs, varkw, locals,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
868 formatarg=str,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
869 formatvarargs=lambda name: '*' + name,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
870 formatvarkw=lambda name: '**' + name,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
871 formatvalue=lambda value: '=' + repr(value),
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
872 join=joinseq):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
873 """Format an argument spec from the 4 values returned by getargvalues.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
874
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
875 The first four arguments are (args, varargs, varkw, locals). The
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
876 next four arguments are the corresponding optional formatting functions
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
877 that are called to turn names and values into strings. The ninth
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
878 argument is an optional function to format the sequence of arguments."""
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
879 def convert(name, locals=locals,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
880 formatarg=formatarg, formatvalue=formatvalue):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
881 return formatarg(name) + formatvalue(locals[name])
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
882 specs = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
883 for i in range(len(args)):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
884 specs.append(strseq(args[i], convert, join))
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
885 if varargs:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
886 specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
887 if varkw:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
888 specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
889 return '(' + string.join(specs, ', ') + ')'
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
890
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
891 # -------------------------------------------------- stack frame extraction
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
892
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
893 Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
894
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
895 def getframeinfo(frame, context=1):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
896 """Get information about a frame or traceback object.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
897
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
898 A tuple of five things is returned: the filename, the line number of
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
899 the current line, the function name, a list of lines of context from
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
900 the source code, and the index of the current line within that list.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
901 The optional second argument specifies the number of lines of context
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
902 to return, which are centered around the current line."""
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
903 if istraceback(frame):
32253
ec6f9a190831 [Bug #954364] inspect.getframeinfo() sometimes produces incorrect traceback line #s; fix is to look at tb.tb_lineno, not tb.frame.f_lineno. Patch from Robin Becker and me.
Andrew M. Kuchling <amk@amk.ca>
parents: 31054
diff changeset
904 lineno = frame.tb_lineno
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
905 frame = frame.tb_frame
32253
ec6f9a190831 [Bug #954364] inspect.getframeinfo() sometimes produces incorrect traceback line #s; fix is to look at tb.tb_lineno, not tb.frame.f_lineno. Patch from Robin Becker and me.
Andrew M. Kuchling <amk@amk.ca>
parents: 31054
diff changeset
906 else:
ec6f9a190831 [Bug #954364] inspect.getframeinfo() sometimes produces incorrect traceback line #s; fix is to look at tb.tb_lineno, not tb.frame.f_lineno. Patch from Robin Becker and me.
Andrew M. Kuchling <amk@amk.ca>
parents: 31054
diff changeset
907 lineno = frame.f_lineno
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
908 if not isframe(frame):
29617
badcd158d81c A bit o' reformatting and removal of non-_getframe currentframe().
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29613
diff changeset
909 raise TypeError('arg is not a frame or traceback object')
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
910
22486
8ecd1bad2408 Use linecache for loading source code. Closes SF patch 490374.
Neil Schemenauer <nascheme@enme.ucalgary.ca>
parents: 22348
diff changeset
911 filename = getsourcefile(frame) or getfile(frame)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
912 if context > 0:
19694
3716b116fb31 The first batch of changes recommended by the fixdiv tool. These are
Guido van Rossum <guido@python.org>
parents: 18609
diff changeset
913 start = lineno - 1 - context//2
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
914 try:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
915 lines, lnum = findsource(frame)
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
916 except IOError:
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
917 lines = index = None
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
918 else:
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
919 start = max(start, 1)
32352
348db77a07e9 SF bug #973092: inspect.getframeinfo bug if 'context' is to big
Raymond Hettinger <python@rcn.com>
parents: 32253
diff changeset
920 start = max(0, min(start, len(lines) - context))
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
921 lines = lines[start:start+context]
16887
14dbde1ecdea Add getlineno() routine to account for LINENO optimization.
Ka-Ping Yee <ping@zesty.ca>
parents: 16833
diff changeset
922 index = lineno - 1 - start
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
923 else:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
924 lines = index = None
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
925
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
926 return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
16887
14dbde1ecdea Add getlineno() routine to account for LINENO optimization.
Ka-Ping Yee <ping@zesty.ca>
parents: 16833
diff changeset
927
14dbde1ecdea Add getlineno() routine to account for LINENO optimization.
Ka-Ping Yee <ping@zesty.ca>
parents: 16833
diff changeset
928 def getlineno(frame):
14dbde1ecdea Add getlineno() routine to account for LINENO optimization.
Ka-Ping Yee <ping@zesty.ca>
parents: 16833
diff changeset
929 """Get the line number from a frame object, allowing for optimization."""
24844
cf5928fab108 This is my patch
Michael W. Hudson <mwh@python.net>
parents: 24537
diff changeset
930 # FrameType.f_lineno is now a descriptor that grovels co_lnotab
cf5928fab108 This is my patch
Michael W. Hudson <mwh@python.net>
parents: 24537
diff changeset
931 return frame.f_lineno
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
932
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
933 def getouterframes(frame, context=1):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
934 """Get a list of records for a frame and all higher (calling) frames.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
935
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
936 Each record contains a frame object, filename, line number, function
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
937 name, a list of lines of context, and index within the context."""
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
938 framelist = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
939 while frame:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
940 framelist.append((frame,) + getframeinfo(frame, context))
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
941 frame = frame.f_back
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
942 return framelist
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
943
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
944 def getinnerframes(tb, context=1):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
945 """Get a list of records for a traceback's frame and all lower frames.
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
946
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
947 Each record contains a frame object, filename, line number, function
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
948 name, a list of lines of context, and index within the context."""
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
949 framelist = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
950 while tb:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
951 framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
952 tb = tb.tb_next
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
953 return framelist
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
954
29617
badcd158d81c A bit o' reformatting and removal of non-_getframe currentframe().
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29613
diff changeset
955 currentframe = sys._getframe
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
956
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
957 def stack(context=1):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
958 """Return a list of records for the stack above the caller's frame."""
29617
badcd158d81c A bit o' reformatting and removal of non-_getframe currentframe().
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29613
diff changeset
959 return getouterframes(sys._getframe(1), context)
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
960
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
961 def trace(context=1):
16833
bbdeb6d4dea1 Whitespace normalization.
Tim Peters <tim.peters@gmail.com>
parents: 16790
diff changeset
962 """Return a list of records for the stack below the current exception."""
23281
f5fd7e295897 Clean up uses of some deprecated features.
Fred Drake <fdrake@acm.org>
parents: 22639
diff changeset
963 return getinnerframes(sys.exc_info()[2], context)