annotate Lib/inspect.py @ 80661:94de77bd0b4b 2.7

Issue #16194: document imp.load_dynamic problems when read several extension modules from the same binary object file.
author Andrew Svetlov <andrew.svetlov@gmail.com>
date Thu, 29 Nov 2012 19:51:28 +0200
parents f824744557ba
children bc73223e4c10
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
60080
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
20 getargspec(), getargvalues(), getcallargs() - get info about function arguments
16790
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
64078
756f8b398230 Merged revisions 84106 via svnmerge from
Alexander Belopolsky <alexander.belopolsky@gmail.com>
parents: 62369
diff changeset
160 See help(isfunction) for attributes listing."""
50424
df3923c36ec5 Merged revisions 67952-67953,67955,67957-67958,67960-67961,67963,67965,67967,67970-67971,67973,67982,67988,67990,67995,68014,68016,68030,68057,68061,68112,68115-68118,68120-68121,68123-68128 via svnmerge from
Georg Brandl <georg@python.org>
parents: 49568
diff changeset
161 return bool((isfunction(object) or ismethod(object)) and
df3923c36ec5 Merged revisions 67952-67953,67955,67957-67958,67960-67961,67963,67965,67967,67970-67971,67973,67982,67988,67990,67995,68014,68016,68030,68057,68061,68112,68115-68118,68120-68121,68123-68128 via svnmerge from
Georg Brandl <georg@python.org>
parents: 49568
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
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
243 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
244 """Return true if the object is an abstract base class (ABC)."""
56538
983eefbf6649 make inspect.isabstract() always return a boolean; add a test for it, too #7069
Benjamin Peterson <benjamin@python.org>
parents: 56072
diff changeset
245 return bool(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
246
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
247 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
248 """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
249 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
250 results = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
251 for key in dir(object):
74501
f824744557ba Revert part of 13f56cd8dec1 (issue #1785) to avoid breaking getmembers() with unbound methods.
Antoine Pitrou <solipsis@pitrou.net>
parents: 74106
diff changeset
252 try:
f824744557ba Revert part of 13f56cd8dec1 (issue #1785) to avoid breaking getmembers() with unbound methods.
Antoine Pitrou <solipsis@pitrou.net>
parents: 74106
diff changeset
253 value = getattr(object, key)
f824744557ba Revert part of 13f56cd8dec1 (issue #1785) to avoid breaking getmembers() with unbound methods.
Antoine Pitrou <solipsis@pitrou.net>
parents: 74106
diff changeset
254 except AttributeError:
f824744557ba Revert part of 13f56cd8dec1 (issue #1785) to avoid breaking getmembers() with unbound methods.
Antoine Pitrou <solipsis@pitrou.net>
parents: 74106
diff changeset
255 continue
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
256 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
257 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
258 results.sort()
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
259 return results
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
260
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
261 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
262
20040
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
263 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
264 """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
265
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
266 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
267 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
268
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
269 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
270
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
271 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
272 '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
273 '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
274 '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
275 '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
276 '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
277
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
278 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
279
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
280 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
281 __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
282 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
283 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
284 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
285 """
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
286
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
287 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
288 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
289 result = []
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
290 for name in names:
74106
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
291 # Get the object associated with the name, and where it was defined.
20040
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
292 # 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
293 # using getattr. Static and class methods are dramatic examples.
74106
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
294 # Furthermore, some objects may raise an Exception when fetched with
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
295 # getattr(). This is the case with some descriptors (bug #1785).
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
296 # Thus, we only use getattr() as a last resort.
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
297 homecls = None
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
298 for base in (cls,) + mro:
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
299 if name in base.__dict__:
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
300 obj = base.__dict__[name]
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
301 homecls = base
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
302 break
20040
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
303 else:
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
304 obj = getattr(cls, name)
74106
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
305 homecls = getattr(obj, "__objclass__", homecls)
20040
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
306
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
307 # 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
308 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
309 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
310 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
311 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
312 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
313 kind = "property"
74106
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
314 elif ismethoddescriptor(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
315 kind = "method"
74106
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
316 elif isdatadescriptor(obj):
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
317 kind = "data"
20040
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
318 else:
74106
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
319 obj_via_getattr = getattr(cls, name)
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
320 if (ismethod(obj_via_getattr) or
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
321 ismethoddescriptor(obj_via_getattr)):
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
322 kind = "method"
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
323 else:
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
324 kind = "data"
13f56cd8dec1 Issue #1785: Fix inspect and pydoc with misbehaving descriptors.
Antoine Pitrou <solipsis@pitrou.net>
parents: 70798
diff changeset
325 obj = obj_via_getattr
20040
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
326
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
327 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
328
59882e7aab89 New function classify_class_attrs(). As a number of SF bug reports
Tim Peters <tim.peters@gmail.com>
parents: 20036
diff changeset
329 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
330
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
331 # ----------------------------------------------------------- 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
332 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
333 # 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
334 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
335 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
336 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
337 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
338 _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
339
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 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
341 "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
342 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
343 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
344 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
345 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
346 _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
347 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
348
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
349 # -------------------------------------------------- source code extraction
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
350 def indentsize(line):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
351 """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
352 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
353 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
354
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
355 def getdoc(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
356 """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
357
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
358 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
359 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
360 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
361 try:
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
362 doc = object.__doc__
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
363 except AttributeError:
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
364 return None
23486
bb5790c6cdaa Use types.StringTypes instead of explicit (str, unicode) list
Michael W. Hudson <mwh@python.net>
parents: 23281
diff changeset
365 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
366 return None
47506
ebf6f639e117 Factor out docstring dedenting from inspect.getdoc() into inspect.cleandoc()
Georg Brandl <georg@python.org>
parents: 46359
diff changeset
367 return cleandoc(doc)
ebf6f639e117 Factor out docstring dedenting from inspect.getdoc() into inspect.cleandoc()
Georg Brandl <georg@python.org>
parents: 46359
diff changeset
368
ebf6f639e117 Factor out docstring dedenting from inspect.getdoc() into inspect.cleandoc()
Georg Brandl <georg@python.org>
parents: 46359
diff changeset
369 def cleandoc(doc):
ebf6f639e117 Factor out docstring dedenting from inspect.getdoc() into inspect.cleandoc()
Georg Brandl <georg@python.org>
parents: 46359
diff changeset
370 """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
371
ebf6f639e117 Factor out docstring dedenting from inspect.getdoc() into inspect.cleandoc()
Georg Brandl <georg@python.org>
parents: 46359
diff changeset
372 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
373 onwards is removed."""
22348
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
374 try:
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
375 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
376 except UnicodeError:
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
377 return None
51aa9eb24d81 SF patch 530070: pydoc regression, from Martin and Guido.
Tim Peters <tim.peters@gmail.com>
parents: 22264
diff changeset
378 else:
26467
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
379 # Find minimum indentation of any non-blank lines after first line.
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
380 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
381 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
382 content = len(string.lstrip(line))
26467
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
383 if content:
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
384 indent = len(line) - content
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
385 margin = min(margin, indent)
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
386 # Remove indentation.
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
387 if lines:
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
388 lines[0] = lines[0].lstrip()
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
389 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
390 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
391 # Remove any trailing or leading blank lines.
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
392 while lines and not lines[-1]:
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
393 lines.pop()
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
394 while lines and not lines[0]:
a573af5db807 getdoc():
Ka-Ping Yee <ping@zesty.ca>
parents: 24844
diff changeset
395 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
396 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
397
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
398 def getfile(object):
16927
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
399 """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
400 if ismodule(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
401 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
402 return object.__file__
56072
b35dd1b6248e Use str.format() to fix beginner's mistake with %-style string formatting.
Georg Brandl <georg@python.org>
parents: 56065
diff changeset
403 raise TypeError('{!r} is a built-in module'.format(object))
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
404 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
405 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
406 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
407 return object.__file__
56072
b35dd1b6248e Use str.format() to fix beginner's mistake with %-style string formatting.
Georg Brandl <georg@python.org>
parents: 56065
diff changeset
408 raise TypeError('{!r} is a built-in class'.format(object))
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
409 if ismethod(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
410 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
411 if isfunction(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
412 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
413 if istraceback(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
414 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
415 if isframe(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.f_code
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
417 if iscode(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
418 return object.co_filename
56072
b35dd1b6248e Use str.format() to fix beginner's mistake with %-style string formatting.
Georg Brandl <georg@python.org>
parents: 56065
diff changeset
419 raise TypeError('{!r} is not a module, class, method, '
b35dd1b6248e Use str.format() to fix beginner's mistake with %-style string formatting.
Georg Brandl <georg@python.org>
parents: 56065
diff changeset
420 'function, traceback, frame, or code object'.format(object))
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
421
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
422 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
423
17370
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
424 def getmoduleinfo(path):
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
425 """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
426 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
427 suffixes = map(lambda info:
1140774f69a5 Silence (Syntax|Deprecation)Warning for 'inspect'. Had to remove tuple
Brett Cannon <bcannon@gmail.com>
parents: 47506
diff changeset
428 (-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
429 imp.get_suffixes())
17370
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
430 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
431 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
432 if filename[neglen:] == suffix:
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
433 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
434
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
435 def getmodulename(path):
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
436 """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
437 info = getmoduleinfo(path)
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
438 if info: return info[0]
65f363236ecf Add getmodulename() and getmoduleinfo() routines to inspect filenames.
Ka-Ping Yee <ping@zesty.ca>
parents: 17190
diff changeset
439
16927
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
440 def getsourcefile(object):
62369
017e60ae605f #8720: fix inspect regression by teaching getsourcefile about linecache.
R. David Murray <rdmurray@bitdance.com>
parents: 60080
diff changeset
441 """Return the filename that can be used to locate an object's source.
017e60ae605f #8720: fix inspect regression by teaching getsourcefile about linecache.
R. David Murray <rdmurray@bitdance.com>
parents: 60080
diff changeset
442 Return None if no way can be identified to get the source.
017e60ae605f #8720: fix inspect regression by teaching getsourcefile about linecache.
R. David Murray <rdmurray@bitdance.com>
parents: 60080
diff changeset
443 """
16927
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
444 filename = getfile(object)
34545
9d66fba78444 Replace list of constants with tuples of constants.
Raymond Hettinger <python@rcn.com>
parents: 34152
diff changeset
445 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
446 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
447 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
448 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
449 # 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
450 return None
38056
69f0457c17bb Fix infinite regress when inspecting <string> or <stdin> frames.
Phillip J. Eby <pje@telecommunity.com>
parents: 37593
diff changeset
451 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
452 return filename
39053
b978afe7cab6 Fix SF#1516184 and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 38057
diff changeset
453 # 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
454 if hasattr(getmodule(object, filename), '__loader__'):
16927
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
455 return filename
62369
017e60ae605f #8720: fix inspect regression by teaching getsourcefile about linecache.
R. David Murray <rdmurray@bitdance.com>
parents: 60080
diff changeset
456 # or it is in the linecache
017e60ae605f #8720: fix inspect regression by teaching getsourcefile about linecache.
R. David Murray <rdmurray@bitdance.com>
parents: 60080
diff changeset
457 if filename in linecache.cache:
017e60ae605f #8720: fix inspect regression by teaching getsourcefile about linecache.
R. David Murray <rdmurray@bitdance.com>
parents: 60080
diff changeset
458 return filename
16927
2548d1a70180 Clarify the purpose of getsourcefile().
Ka-Ping Yee <ping@zesty.ca>
parents: 16924
diff changeset
459
39053
b978afe7cab6 Fix SF#1516184 and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 38057
diff changeset
460 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
461 """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
462
16938
5d7e0ea31818 Make getsourcefile() succeed even if the filename doesn't end in '.py' --
Ka-Ping Yee <ping@zesty.ca>
parents: 16927
diff changeset
463 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
464 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
465 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
466 _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
467 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
468
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
469 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
470 _filesbymodname = {}
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
471
39053
b978afe7cab6 Fix SF#1516184 and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 38057
diff changeset
472 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
473 """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
474 if ismodule(object):
926b64fba5e7 Remove duplicate type objects from isroutine() and isbuiltin().
Ka-Ping Yee <ping@zesty.ca>
parents: 17446
diff changeset
475 return object
33455
9e3c52ca3a04 Use __module__ attribute when available instead of using isclass() predicate
Johannes Gijsbers <jlg@dds.nl>
parents: 33172
diff changeset
476 if hasattr(object, '__module__'):
16898
dcea09388332 Add __author__ variable.
Ka-Ping Yee <ping@zesty.ca>
parents: 16887
diff changeset
477 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
478 # 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
479 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
480 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
481 # 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
482 try:
39053
b978afe7cab6 Fix SF#1516184 and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 38057
diff changeset
483 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
484 except TypeError:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
485 return None
23620
a1de0bab5475 SF 563203. Replaced 'has_key()' with 'in'.
Raymond Hettinger <python@rcn.com>
parents: 23613
diff changeset
486 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
487 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
488 # 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
489 # 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
490 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
491 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
492 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
493 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
494 # 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
495 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
496 _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
497 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
498 # 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
499 modulesbyfile[f] = modulesbyfile[
b978afe7cab6 Fix SF#1516184 and add a test to prevent regression.
Phillip J. Eby <pje@telecommunity.com>
parents: 38057
diff changeset
500 os.path.realpath(f)] = module.__name__
23620
a1de0bab5475 SF 563203. Replaced 'has_key()' with 'in'.
Raymond Hettinger <python@rcn.com>
parents: 23613
diff changeset
501 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
502 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
503 # 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
504 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
505 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
506 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
507 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
508 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
509 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
510 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
511 # Check builtins
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
512 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
513 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
514 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
515 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
516 return builtin
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
517
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
518 def findsource(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
519 """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
520
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
521 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
522 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
523 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
524 is raised if the source code cannot be retrieved."""
70798
527c40add91d allow "fake" filenames in findsource (closes #9284)
Benjamin Peterson <benjamin@python.org>
parents: 69032
diff changeset
525
527c40add91d allow "fake" filenames in findsource (closes #9284)
Benjamin Peterson <benjamin@python.org>
parents: 69032
diff changeset
526 file = getfile(object)
527c40add91d allow "fake" filenames in findsource (closes #9284)
Benjamin Peterson <benjamin@python.org>
parents: 69032
diff changeset
527 sourcefile = getsourcefile(object)
527c40add91d allow "fake" filenames in findsource (closes #9284)
Benjamin Peterson <benjamin@python.org>
parents: 69032
diff changeset
528 if not sourcefile and file[0] + file[-1] != '<>':
54041
347e59ea1a71 Issue #4050: inspect.findsource/getsource now raise an IOError if the 'source'
R. David Murray <rdmurray@bitdance.com>
parents: 50834
diff changeset
529 raise IOError('source code not available')
70798
527c40add91d allow "fake" filenames in findsource (closes #9284)
Benjamin Peterson <benjamin@python.org>
parents: 69032
diff changeset
530 file = sourcefile if sourcefile else file
527c40add91d allow "fake" filenames in findsource (closes #9284)
Benjamin Peterson <benjamin@python.org>
parents: 69032
diff changeset
531
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
532 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
533 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
534 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
535 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
536 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
537 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
538 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
539
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
540 if ismodule(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
541 return lines, 0
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
542
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
543 if isclass(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
544 name = object.__name__
40097
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
545 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
546 # 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
547 # 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
548 # 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
549 candidates = []
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
550 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
551 match = pat.match(lines[i])
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
552 if match:
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
553 # 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
554 if lines[i][0] == 'c':
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
555 return lines, i
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
556 # 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
557 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
558 if candidates:
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
559 # 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
560 # less whitespace first
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
561 candidates.sort()
c0208195a558 Bug #1550524: better heuristics to find correct class definition
Georg Brandl <georg@python.org>
parents: 39796
diff changeset
562 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
563 else:
badcd158d81c A bit o' reformatting and removal of non-_getframe currentframe().
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29613
diff changeset
564 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
565
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
566 if ismethod(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
567 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
568 if isfunction(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
569 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
570 if istraceback(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
571 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
572 if isframe(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
573 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
574 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
575 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
576 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
577 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
578 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
579 while lnum > 0:
17020
953c50f12184 Fix findsource() to work for derived classes.
Ka-Ping Yee <ping@zesty.ca>
parents: 16938
diff changeset
580 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
581 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
582 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
583 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
584
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
585 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
586 """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
587
9c2ca37bdeec Fix getcomments() so that it doesn't fail with TypeErrors.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 22563
diff changeset
588 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
589 """
9c2ca37bdeec Fix getcomments() so that it doesn't fail with TypeErrors.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 22563
diff changeset
590 try:
9c2ca37bdeec Fix getcomments() so that it doesn't fail with TypeErrors.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 22563
diff changeset
591 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
592 except (IOError, TypeError):
9c2ca37bdeec Fix getcomments() so that it doesn't fail with TypeErrors.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 22563
diff changeset
593 return None
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
594
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
595 if ismodule(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
596 # 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
597 start = 0
17446
0184c50a8751 Robustify getcomments() so it doesn't crash on empty files.
Ka-Ping Yee <ping@zesty.ca>
parents: 17370
diff changeset
598 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
599 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
600 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
601 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
602 comments = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
603 end = start
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
604 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
605 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
606 end = end + 1
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
607 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
608
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
609 # 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
610 elif lnum > 0:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
611 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
612 end = lnum - 1
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 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
614 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
615 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
616 if end > 0:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
617 end = end - 1
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
618 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
619 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
620 comments[:0] = [comment]
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
621 end = end - 1
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
622 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
623 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
624 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
625 comments[:1] = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
626 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
627 comments[-1:] = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
628 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
629
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
630 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
631
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 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
633 """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
634 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
635 self.indent = 0
34740
3bb759498767 Patch #1159931/bug #1143895: inspect.getsource failed when functions,
Johannes Gijsbers <jlg@dds.nl>
parents: 34734
diff changeset
636 self.islambda = False
34152
bbdaacc44f6f Patch #1011890: fix inspect.getsource breaking with line-continuation &
Johannes Gijsbers <jlg@dds.nl>
parents: 33528
diff changeset
637 self.started = False
bbdaacc44f6f Patch #1011890: fix inspect.getsource breaking with line-continuation &
Johannes Gijsbers <jlg@dds.nl>
parents: 33528
diff changeset
638 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
639 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
640
48121
1140774f69a5 Silence (Syntax|Deprecation)Warning for 'inspect'. Had to remove tuple
Brett Cannon <bcannon@gmail.com>
parents: 47506
diff changeset
641 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
642 srow, scol = srow_scol
1140774f69a5 Silence (Syntax|Deprecation)Warning for 'inspect'. Had to remove tuple
Brett Cannon <bcannon@gmail.com>
parents: 47506
diff changeset
643 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
644 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
645 # 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
646 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
647 if token == "lambda":
3bb759498767 Patch #1159931/bug #1143895: inspect.getsource failed when functions,
Johannes Gijsbers <jlg@dds.nl>
parents: 34734
diff changeset
648 self.islambda = True
34152
bbdaacc44f6f Patch #1011890: fix inspect.getsource breaking with line-continuation &
Johannes Gijsbers <jlg@dds.nl>
parents: 33528
diff changeset
649 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
650 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
651 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
652 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
653 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
654 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
655 raise EndOfBlock
34152
bbdaacc44f6f Patch #1011890: fix inspect.getsource breaking with line-continuation &
Johannes Gijsbers <jlg@dds.nl>
parents: 33528
diff changeset
656 elif self.passline:
bbdaacc44f6f Patch #1011890: fix inspect.getsource breaking with line-continuation &
Johannes Gijsbers <jlg@dds.nl>
parents: 33528
diff changeset
657 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
658 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
659 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
660 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
661 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
662 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
663 # 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
664 # (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
665 # 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
666 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
667 raise EndOfBlock
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
668 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
669 # 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
670 # 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
671 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
672
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
673 def getblock(lines):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
674 """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
675 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
676 try:
35640
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
677 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
678 except (EndOfBlock, IndentationError):
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
679 pass
1e7b755194a4 some more fixes and tests for inspect.getsource(), triggered by crashes
Armin Rigo <arigo@tunes.org>
parents: 34740
diff changeset
680 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
681
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
682 def getsourcelines(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
683 """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
684
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
685 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
686 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
687 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
688 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
689 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
690 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
691
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
692 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
693 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
694
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
695 def getsource(object):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
696 """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
697
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
698 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
699 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
700 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
701 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
702 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
703
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
704 # --------------------------------------------------- class tree extraction
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
705 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
706 """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
707 results = []
34734
d355da1d7c8f Apply itemgetter() instead of lambda.
Raymond Hettinger <python@rcn.com>
parents: 34545
diff changeset
708 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
709 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
710 results.append((c, c.__bases__))
23620
a1de0bab5475 SF 563203. Replaced 'has_key()' with 'in'.
Raymond Hettinger <python@rcn.com>
parents: 23613
diff changeset
711 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
712 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
713 return results
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 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
716 """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
717
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
718 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
719 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
720 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
721 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
722 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
723 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
724 children = {}
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
725 roots = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
726 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
727 if c.__bases__:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
728 for parent in c.__bases__:
23620
a1de0bab5475 SF 563203. Replaced 'has_key()' with 'in'.
Raymond Hettinger <python@rcn.com>
parents: 23613
diff changeset
729 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
730 children[parent] = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
731 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
732 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
733 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
734 roots.append(c)
23634
dbee2f628a90 Replaced .keys() with dictionary iterators
Raymond Hettinger <python@rcn.com>
parents: 23620
diff changeset
735 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
736 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
737 roots.append(parent)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
738 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
739
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
740 # ------------------------------------------------ argument list extraction
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
741 Arguments = namedtuple('Arguments', 'args varargs keywords')
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
742
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
743 def getargs(co):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
744 """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
745
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
746 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
747 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
748 '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
749
0bdb4aced6e2 Fix for SF bug 620190: getargspec() doesn't work with methods.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29484
diff changeset
750 if not iscode(co):
56072
b35dd1b6248e Use str.format() to fix beginner's mistake with %-style string formatting.
Georg Brandl <georg@python.org>
parents: 56065
diff changeset
751 raise TypeError('{!r} is not a code object'.format(co))
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
752
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
753 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
754 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
755 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
756 step = 0
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
757
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
758 # 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
759 for i in range(nargs):
34545
9d66fba78444 Replace list of constants with tuples of constants.
Raymond Hettinger <python@rcn.com>
parents: 34152
diff changeset
760 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
761 stack, remain, count = [], [], []
42214
6319adb0041d Patch #1739696: use code.co_code only if really necessary
Georg Brandl <georg@python.org>
parents: 40097
diff changeset
762 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
763 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
764 step = step + 1
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
765 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
766 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
767 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
768 step = step + 2
34545
9d66fba78444 Replace list of constants with tuples of constants.
Raymond Hettinger <python@rcn.com>
parents: 34152
diff changeset
769 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
770 remain.append(value)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
771 count.append(value)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
772 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
773 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
774
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
775 # 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
776 # 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
777 # `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
778 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
779 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
780 break
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
781 else:
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
782 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
783 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
784 remain.pop()
ad268a8408f4 - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).
Matthias Klose <doko@ubuntu.com>
parents: 33119
diff changeset
785 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
786 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
787 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
788 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
789 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
790 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
791
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
792 varargs = None
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
793 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
794 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
795 nargs = nargs + 1
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
796 varkw = None
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
797 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
798 varkw = co.co_varnames[nargs]
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
799 return Arguments(args, varargs, varkw)
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
800
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
801 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
802
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
803 def getargspec(func):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
804 """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
805
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
806 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
807 '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
808 '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
809 '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
810 """
0bdb4aced6e2 Fix for SF bug 620190: getargspec() doesn't work with methods.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29484
diff changeset
811
0bdb4aced6e2 Fix for SF bug 620190: getargspec() doesn't work with methods.
Jeremy Hylton <jeremy@alum.mit.edu>
parents: 29484
diff changeset
812 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
813 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
814 if not isfunction(func):
56072
b35dd1b6248e Use str.format() to fix beginner's mistake with %-style string formatting.
Georg Brandl <georg@python.org>
parents: 56065
diff changeset
815 raise TypeError('{!r} is not a Python function'.format(func))
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
816 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
817 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
818
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
819 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
820
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
821 def getargvalues(frame):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
822 """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
823
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
824 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
825 '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
826 '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
827 '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
828 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
829 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
830
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
831 def joinseq(seq):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
832 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
833 return '(' + seq[0] + ',)'
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
834 else:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
835 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
836
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
837 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
838 """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
839 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
840 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
841 else:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
842 return convert(object)
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
843
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
844 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
845 formatarg=str,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
846 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
847 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
848 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
849 join=joinseq):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
850 """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
851
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
852 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
853 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
854 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
855 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
856 specs = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
857 if defaults:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
858 firstdefault = len(args) - len(defaults)
50818
cb290482a1a7 use enumerate
Benjamin Peterson <benjamin@python.org>
parents: 50784
diff changeset
859 for i, arg in enumerate(args):
cb290482a1a7 use enumerate
Benjamin Peterson <benjamin@python.org>
parents: 50784
diff changeset
860 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
861 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
862 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
863 specs.append(spec)
23613
4a1f5bd486ff Replaced boolean test with is None
Raymond Hettinger <python@rcn.com>
parents: 23486
diff changeset
864 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
865 specs.append(formatvarargs(varargs))
23613
4a1f5bd486ff Replaced boolean test with is None
Raymond Hettinger <python@rcn.com>
parents: 23486
diff changeset
866 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
867 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
868 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
869
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
870 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
871 formatarg=str,
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
872 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
873 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
874 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
875 join=joinseq):
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
876 """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
877
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
878 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
879 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
880 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
881 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
882 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
883 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
884 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
885 specs = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
886 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
887 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
888 if varargs:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
889 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
890 if varkw:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
891 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
892 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
893
60080
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
894 def getcallargs(func, *positional, **named):
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
895 """Get the mapping of arguments to values.
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
896
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
897 A dict is returned, with keys the function argument names (including the
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
898 names of the * and ** arguments, if any), and values the respective bound
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
899 values from 'positional' and 'named'."""
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
900 args, varargs, varkw, defaults = getargspec(func)
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
901 f_name = func.__name__
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
902 arg2value = {}
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
903
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
904 # The following closures are basically because of tuple parameter unpacking.
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
905 assigned_tuple_params = []
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
906 def assign(arg, value):
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
907 if isinstance(arg, str):
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
908 arg2value[arg] = value
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
909 else:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
910 assigned_tuple_params.append(arg)
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
911 value = iter(value)
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
912 for i, subarg in enumerate(arg):
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
913 try:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
914 subvalue = next(value)
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
915 except StopIteration:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
916 raise ValueError('need more than %d %s to unpack' %
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
917 (i, 'values' if i > 1 else 'value'))
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
918 assign(subarg,subvalue)
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
919 try:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
920 next(value)
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
921 except StopIteration:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
922 pass
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
923 else:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
924 raise ValueError('too many values to unpack')
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
925 def is_assigned(arg):
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
926 if isinstance(arg,str):
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
927 return arg in arg2value
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
928 return arg in assigned_tuple_params
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
929 if ismethod(func) and func.im_self is not None:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
930 # implicit 'self' (or 'cls' for classmethods) argument
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
931 positional = (func.im_self,) + positional
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
932 num_pos = len(positional)
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
933 num_total = num_pos + len(named)
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
934 num_args = len(args)
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
935 num_defaults = len(defaults) if defaults else 0
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
936 for arg, value in zip(args, positional):
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
937 assign(arg, value)
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
938 if varargs:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
939 if num_pos > num_args:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
940 assign(varargs, positional[-(num_pos-num_args):])
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
941 else:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
942 assign(varargs, ())
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
943 elif 0 < num_args < num_pos:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
944 raise TypeError('%s() takes %s %d %s (%d given)' % (
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
945 f_name, 'at most' if defaults else 'exactly', num_args,
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
946 'arguments' if num_args > 1 else 'argument', num_total))
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
947 elif num_args == 0 and num_total:
69032
b19d76d9d2a7 Correct handling of functions with only kwarg args in getcallargs (closes #11256)
Benjamin Peterson <benjamin@python.org>
parents: 68256
diff changeset
948 if varkw:
b19d76d9d2a7 Correct handling of functions with only kwarg args in getcallargs (closes #11256)
Benjamin Peterson <benjamin@python.org>
parents: 68256
diff changeset
949 if num_pos:
b19d76d9d2a7 Correct handling of functions with only kwarg args in getcallargs (closes #11256)
Benjamin Peterson <benjamin@python.org>
parents: 68256
diff changeset
950 # XXX: We should use num_pos, but Python also uses num_total:
b19d76d9d2a7 Correct handling of functions with only kwarg args in getcallargs (closes #11256)
Benjamin Peterson <benjamin@python.org>
parents: 68256
diff changeset
951 raise TypeError('%s() takes exactly 0 arguments '
b19d76d9d2a7 Correct handling of functions with only kwarg args in getcallargs (closes #11256)
Benjamin Peterson <benjamin@python.org>
parents: 68256
diff changeset
952 '(%d given)' % (f_name, num_total))
b19d76d9d2a7 Correct handling of functions with only kwarg args in getcallargs (closes #11256)
Benjamin Peterson <benjamin@python.org>
parents: 68256
diff changeset
953 else:
b19d76d9d2a7 Correct handling of functions with only kwarg args in getcallargs (closes #11256)
Benjamin Peterson <benjamin@python.org>
parents: 68256
diff changeset
954 raise TypeError('%s() takes no arguments (%d given)' %
b19d76d9d2a7 Correct handling of functions with only kwarg args in getcallargs (closes #11256)
Benjamin Peterson <benjamin@python.org>
parents: 68256
diff changeset
955 (f_name, num_total))
60080
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
956 for arg in args:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
957 if isinstance(arg, str) and arg in named:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
958 if is_assigned(arg):
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
959 raise TypeError("%s() got multiple values for keyword "
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
960 "argument '%s'" % (f_name, arg))
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
961 else:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
962 assign(arg, named.pop(arg))
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
963 if defaults: # fill in any missing values with the defaults
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
964 for arg, value in zip(args[-num_defaults:], defaults):
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
965 if not is_assigned(arg):
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
966 assign(arg, value)
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
967 if varkw:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
968 assign(varkw, named)
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
969 elif named:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
970 unexpected = next(iter(named))
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
971 if isinstance(unexpected, unicode):
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
972 unexpected = unexpected.encode(sys.getdefaultencoding(), 'replace')
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
973 raise TypeError("%s() got an unexpected keyword argument '%s'" %
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
974 (f_name, unexpected))
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
975 unassigned = num_args - len([arg for arg in args if is_assigned(arg)])
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
976 if unassigned:
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
977 num_required = num_args - num_defaults
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
978 raise TypeError('%s() takes %s %d %s (%d given)' % (
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
979 f_name, 'at least' if defaults else 'exactly', num_required,
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
980 'arguments' if num_required > 1 else 'argument', num_total))
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
981 return arg2value
a14a205ab1fb add inspect.getcallargs, which binds function arguments like a normal call #3135
Benjamin Peterson <benjamin@python.org>
parents: 56538
diff changeset
982
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
983 # -------------------------------------------------- stack frame extraction
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
984
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
985 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
986
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
987 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
988 """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
989
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
990 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
991 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
992 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
993 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
994 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
995 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
996 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
997 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
998 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
999 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
1000 if not isframe(frame):
56072
b35dd1b6248e Use str.format() to fix beginner's mistake with %-style string formatting.
Georg Brandl <georg@python.org>
parents: 56065
diff changeset
1001 raise TypeError('{!r} is not a frame or traceback object'.format(frame))
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1002
22486
8ecd1bad2408 Use linecache for loading source code. Closes SF patch 490374.
Neil Schemenauer <nascheme@enme.ucalgary.ca>
parents: 22348
diff changeset
1003 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
1004 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
1005 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
1006 try:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1007 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
1008 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
1009 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
1010 else:
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1011 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
1012 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
1013 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
1014 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
1015 else:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1016 lines = index = None
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1017
44632
785237fa5f40 Let most inspect functions return named tuples
Raymond Hettinger <python@rcn.com>
parents: 42214
diff changeset
1018 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
1019
14dbde1ecdea Add getlineno() routine to account for LINENO optimization.
Ka-Ping Yee <ping@zesty.ca>
parents: 16833
diff changeset
1020 def getlineno(frame):
14dbde1ecdea Add getlineno() routine to account for LINENO optimization.
Ka-Ping Yee <ping@zesty.ca>
parents: 16833
diff changeset
1021 """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
1022 # 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
1023 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
1024
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1025 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
1026 """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
1027
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1028 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
1029 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
1030 framelist = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1031 while frame:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1032 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
1033 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
1034 return framelist
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1035
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1036 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
1037 """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
1038
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1039 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
1040 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
1041 framelist = []
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1042 while tb:
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1043 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
1044 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
1045 return framelist
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1046
55455
c10773bbafa0 Issue 6581. Michael Foord
Michael Foord <fuzzyman@voidspace.org.uk>
parents: 50424
diff changeset
1047 if hasattr(sys, '_getframe'):
c10773bbafa0 Issue 6581. Michael Foord
Michael Foord <fuzzyman@voidspace.org.uk>
parents: 50424
diff changeset
1048 currentframe = sys._getframe
c10773bbafa0 Issue 6581. Michael Foord
Michael Foord <fuzzyman@voidspace.org.uk>
parents: 50424
diff changeset
1049 else:
c10773bbafa0 Issue 6581. Michael Foord
Michael Foord <fuzzyman@voidspace.org.uk>
parents: 50424
diff changeset
1050 currentframe = lambda _=None: None
16790
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1051
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1052 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
1053 """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
1054 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
1055
67bad9f20b29 inspect: a module for getting information out of live Python objects
Ka-Ping Yee <ping@zesty.ca>
parents:
diff changeset
1056 def trace(context=1):
16833
bbdeb6d4dea1 Whitespace normalization.
Tim Peters <tim.peters@gmail.com>
parents: 16790
diff changeset
1057 """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
1058 return getinnerframes(sys.exc_info()[2], context)