Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ExeBy/smexe_ro.../lib64/python2....
File: inspect.py
# -*- coding: iso-8859-1 -*-
[0] Fix | Delete
"""Get useful information from live Python objects.
[1] Fix | Delete
[2] Fix | Delete
This module encapsulates the interface provided by the internal special
[3] Fix | Delete
attributes (func_*, co_*, im_*, tb_*, etc.) in a friendlier fashion.
[4] Fix | Delete
It also provides some help for examining source code and class layout.
[5] Fix | Delete
[6] Fix | Delete
Here are some of the useful functions provided by this module:
[7] Fix | Delete
[8] Fix | Delete
ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
[9] Fix | Delete
isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
[10] Fix | Delete
isroutine() - check object types
[11] Fix | Delete
getmembers() - get members of an object that satisfy a given condition
[12] Fix | Delete
[13] Fix | Delete
getfile(), getsourcefile(), getsource() - find an object's source code
[14] Fix | Delete
getdoc(), getcomments() - get documentation on an object
[15] Fix | Delete
getmodule() - determine the module that an object came from
[16] Fix | Delete
getclasstree() - arrange classes so as to represent their hierarchy
[17] Fix | Delete
[18] Fix | Delete
getargspec(), getargvalues(), getcallargs() - get info about function arguments
[19] Fix | Delete
formatargspec(), formatargvalues() - format an argument spec
[20] Fix | Delete
getouterframes(), getinnerframes() - get info about frames
[21] Fix | Delete
currentframe() - get the current stack frame
[22] Fix | Delete
stack(), trace() - get info about frames on the stack or in a traceback
[23] Fix | Delete
"""
[24] Fix | Delete
[25] Fix | Delete
# This module is in the public domain. No warranties.
[26] Fix | Delete
[27] Fix | Delete
__author__ = 'Ka-Ping Yee <ping@lfw.org>'
[28] Fix | Delete
__date__ = '1 Jan 2001'
[29] Fix | Delete
[30] Fix | Delete
import sys
[31] Fix | Delete
import os
[32] Fix | Delete
import types
[33] Fix | Delete
import string
[34] Fix | Delete
import re
[35] Fix | Delete
import dis
[36] Fix | Delete
import imp
[37] Fix | Delete
import tokenize
[38] Fix | Delete
import linecache
[39] Fix | Delete
from operator import attrgetter
[40] Fix | Delete
from collections import namedtuple
[41] Fix | Delete
[42] Fix | Delete
# These constants are from Include/code.h.
[43] Fix | Delete
CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 0x1, 0x2, 0x4, 0x8
[44] Fix | Delete
CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40
[45] Fix | Delete
# See Include/object.h
[46] Fix | Delete
TPFLAGS_IS_ABSTRACT = 1 << 20
[47] Fix | Delete
[48] Fix | Delete
# ----------------------------------------------------------- type-checking
[49] Fix | Delete
def ismodule(object):
[50] Fix | Delete
"""Return true if the object is a module.
[51] Fix | Delete
[52] Fix | Delete
Module objects provide these attributes:
[53] Fix | Delete
__doc__ documentation string
[54] Fix | Delete
__file__ filename (missing for built-in modules)"""
[55] Fix | Delete
return isinstance(object, types.ModuleType)
[56] Fix | Delete
[57] Fix | Delete
def isclass(object):
[58] Fix | Delete
"""Return true if the object is a class.
[59] Fix | Delete
[60] Fix | Delete
Class objects provide these attributes:
[61] Fix | Delete
__doc__ documentation string
[62] Fix | Delete
__module__ name of module in which this class was defined"""
[63] Fix | Delete
return isinstance(object, (type, types.ClassType))
[64] Fix | Delete
[65] Fix | Delete
def ismethod(object):
[66] Fix | Delete
"""Return true if the object is an instance method.
[67] Fix | Delete
[68] Fix | Delete
Instance method objects provide these attributes:
[69] Fix | Delete
__doc__ documentation string
[70] Fix | Delete
__name__ name with which this method was defined
[71] Fix | Delete
im_class class object in which this method belongs
[72] Fix | Delete
im_func function object containing implementation of method
[73] Fix | Delete
im_self instance to which this method is bound, or None"""
[74] Fix | Delete
return isinstance(object, types.MethodType)
[75] Fix | Delete
[76] Fix | Delete
def ismethoddescriptor(object):
[77] Fix | Delete
"""Return true if the object is a method descriptor.
[78] Fix | Delete
[79] Fix | Delete
But not if ismethod() or isclass() or isfunction() are true.
[80] Fix | Delete
[81] Fix | Delete
This is new in Python 2.2, and, for example, is true of int.__add__.
[82] Fix | Delete
An object passing this test has a __get__ attribute but not a __set__
[83] Fix | Delete
attribute, but beyond that the set of attributes varies. __name__ is
[84] Fix | Delete
usually sensible, and __doc__ often is.
[85] Fix | Delete
[86] Fix | Delete
Methods implemented via descriptors that also pass one of the other
[87] Fix | Delete
tests return false from the ismethoddescriptor() test, simply because
[88] Fix | Delete
the other tests promise more -- you can, e.g., count on having the
[89] Fix | Delete
im_func attribute (etc) when an object passes ismethod()."""
[90] Fix | Delete
return (hasattr(object, "__get__")
[91] Fix | Delete
and not hasattr(object, "__set__") # else it's a data descriptor
[92] Fix | Delete
and not ismethod(object) # mutual exclusion
[93] Fix | Delete
and not isfunction(object)
[94] Fix | Delete
and not isclass(object))
[95] Fix | Delete
[96] Fix | Delete
def isdatadescriptor(object):
[97] Fix | Delete
"""Return true if the object is a data descriptor.
[98] Fix | Delete
[99] Fix | Delete
Data descriptors have both a __get__ and a __set__ attribute. Examples are
[100] Fix | Delete
properties (defined in Python) and getsets and members (defined in C).
[101] Fix | Delete
Typically, data descriptors will also have __name__ and __doc__ attributes
[102] Fix | Delete
(properties, getsets, and members have both of these attributes), but this
[103] Fix | Delete
is not guaranteed."""
[104] Fix | Delete
return (hasattr(object, "__set__") and hasattr(object, "__get__"))
[105] Fix | Delete
[106] Fix | Delete
if hasattr(types, 'MemberDescriptorType'):
[107] Fix | Delete
# CPython and equivalent
[108] Fix | Delete
def ismemberdescriptor(object):
[109] Fix | Delete
"""Return true if the object is a member descriptor.
[110] Fix | Delete
[111] Fix | Delete
Member descriptors are specialized descriptors defined in extension
[112] Fix | Delete
modules."""
[113] Fix | Delete
return isinstance(object, types.MemberDescriptorType)
[114] Fix | Delete
else:
[115] Fix | Delete
# Other implementations
[116] Fix | Delete
def ismemberdescriptor(object):
[117] Fix | Delete
"""Return true if the object is a member descriptor.
[118] Fix | Delete
[119] Fix | Delete
Member descriptors are specialized descriptors defined in extension
[120] Fix | Delete
modules."""
[121] Fix | Delete
return False
[122] Fix | Delete
[123] Fix | Delete
if hasattr(types, 'GetSetDescriptorType'):
[124] Fix | Delete
# CPython and equivalent
[125] Fix | Delete
def isgetsetdescriptor(object):
[126] Fix | Delete
"""Return true if the object is a getset descriptor.
[127] Fix | Delete
[128] Fix | Delete
getset descriptors are specialized descriptors defined in extension
[129] Fix | Delete
modules."""
[130] Fix | Delete
return isinstance(object, types.GetSetDescriptorType)
[131] Fix | Delete
else:
[132] Fix | Delete
# Other implementations
[133] Fix | Delete
def isgetsetdescriptor(object):
[134] Fix | Delete
"""Return true if the object is a getset descriptor.
[135] Fix | Delete
[136] Fix | Delete
getset descriptors are specialized descriptors defined in extension
[137] Fix | Delete
modules."""
[138] Fix | Delete
return False
[139] Fix | Delete
[140] Fix | Delete
def isfunction(object):
[141] Fix | Delete
"""Return true if the object is a user-defined function.
[142] Fix | Delete
[143] Fix | Delete
Function objects provide these attributes:
[144] Fix | Delete
__doc__ documentation string
[145] Fix | Delete
__name__ name with which this function was defined
[146] Fix | Delete
func_code code object containing compiled function bytecode
[147] Fix | Delete
func_defaults tuple of any default values for arguments
[148] Fix | Delete
func_doc (same as __doc__)
[149] Fix | Delete
func_globals global namespace in which this function was defined
[150] Fix | Delete
func_name (same as __name__)"""
[151] Fix | Delete
return isinstance(object, types.FunctionType)
[152] Fix | Delete
[153] Fix | Delete
def isgeneratorfunction(object):
[154] Fix | Delete
"""Return true if the object is a user-defined generator function.
[155] Fix | Delete
[156] Fix | Delete
Generator function objects provide the same attributes as functions.
[157] Fix | Delete
See help(isfunction) for a list of attributes."""
[158] Fix | Delete
return bool((isfunction(object) or ismethod(object)) and
[159] Fix | Delete
object.func_code.co_flags & CO_GENERATOR)
[160] Fix | Delete
[161] Fix | Delete
def isgenerator(object):
[162] Fix | Delete
"""Return true if the object is a generator.
[163] Fix | Delete
[164] Fix | Delete
Generator objects provide these attributes:
[165] Fix | Delete
__iter__ defined to support iteration over container
[166] Fix | Delete
close raises a new GeneratorExit exception inside the
[167] Fix | Delete
generator to terminate the iteration
[168] Fix | Delete
gi_code code object
[169] Fix | Delete
gi_frame frame object or possibly None once the generator has
[170] Fix | Delete
been exhausted
[171] Fix | Delete
gi_running set to 1 when generator is executing, 0 otherwise
[172] Fix | Delete
next return the next item from the container
[173] Fix | Delete
send resumes the generator and "sends" a value that becomes
[174] Fix | Delete
the result of the current yield-expression
[175] Fix | Delete
throw used to raise an exception inside the generator"""
[176] Fix | Delete
return isinstance(object, types.GeneratorType)
[177] Fix | Delete
[178] Fix | Delete
def istraceback(object):
[179] Fix | Delete
"""Return true if the object is a traceback.
[180] Fix | Delete
[181] Fix | Delete
Traceback objects provide these attributes:
[182] Fix | Delete
tb_frame frame object at this level
[183] Fix | Delete
tb_lasti index of last attempted instruction in bytecode
[184] Fix | Delete
tb_lineno current line number in Python source code
[185] Fix | Delete
tb_next next inner traceback object (called by this level)"""
[186] Fix | Delete
return isinstance(object, types.TracebackType)
[187] Fix | Delete
[188] Fix | Delete
def isframe(object):
[189] Fix | Delete
"""Return true if the object is a frame object.
[190] Fix | Delete
[191] Fix | Delete
Frame objects provide these attributes:
[192] Fix | Delete
f_back next outer frame object (this frame's caller)
[193] Fix | Delete
f_builtins built-in namespace seen by this frame
[194] Fix | Delete
f_code code object being executed in this frame
[195] Fix | Delete
f_exc_traceback traceback if raised in this frame, or None
[196] Fix | Delete
f_exc_type exception type if raised in this frame, or None
[197] Fix | Delete
f_exc_value exception value if raised in this frame, or None
[198] Fix | Delete
f_globals global namespace seen by this frame
[199] Fix | Delete
f_lasti index of last attempted instruction in bytecode
[200] Fix | Delete
f_lineno current line number in Python source code
[201] Fix | Delete
f_locals local namespace seen by this frame
[202] Fix | Delete
f_restricted 0 or 1 if frame is in restricted execution mode
[203] Fix | Delete
f_trace tracing function for this frame, or None"""
[204] Fix | Delete
return isinstance(object, types.FrameType)
[205] Fix | Delete
[206] Fix | Delete
def iscode(object):
[207] Fix | Delete
"""Return true if the object is a code object.
[208] Fix | Delete
[209] Fix | Delete
Code objects provide these attributes:
[210] Fix | Delete
co_argcount number of arguments (not including * or ** args)
[211] Fix | Delete
co_code string of raw compiled bytecode
[212] Fix | Delete
co_consts tuple of constants used in the bytecode
[213] Fix | Delete
co_filename name of file in which this code object was created
[214] Fix | Delete
co_firstlineno number of first line in Python source code
[215] Fix | Delete
co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
[216] Fix | Delete
co_lnotab encoded mapping of line numbers to bytecode indices
[217] Fix | Delete
co_name name with which this code object was defined
[218] Fix | Delete
co_names tuple of names of local variables
[219] Fix | Delete
co_nlocals number of local variables
[220] Fix | Delete
co_stacksize virtual machine stack space required
[221] Fix | Delete
co_varnames tuple of names of arguments and local variables"""
[222] Fix | Delete
return isinstance(object, types.CodeType)
[223] Fix | Delete
[224] Fix | Delete
def isbuiltin(object):
[225] Fix | Delete
"""Return true if the object is a built-in function or method.
[226] Fix | Delete
[227] Fix | Delete
Built-in functions and methods provide these attributes:
[228] Fix | Delete
__doc__ documentation string
[229] Fix | Delete
__name__ original name of this function or method
[230] Fix | Delete
__self__ instance to which a method is bound, or None"""
[231] Fix | Delete
return isinstance(object, types.BuiltinFunctionType)
[232] Fix | Delete
[233] Fix | Delete
def isroutine(object):
[234] Fix | Delete
"""Return true if the object is any kind of function or method."""
[235] Fix | Delete
return (isbuiltin(object)
[236] Fix | Delete
or isfunction(object)
[237] Fix | Delete
or ismethod(object)
[238] Fix | Delete
or ismethoddescriptor(object))
[239] Fix | Delete
[240] Fix | Delete
def isabstract(object):
[241] Fix | Delete
"""Return true if the object is an abstract base class (ABC)."""
[242] Fix | Delete
return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
[243] Fix | Delete
[244] Fix | Delete
def getmembers(object, predicate=None):
[245] Fix | Delete
"""Return all members of an object as (name, value) pairs sorted by name.
[246] Fix | Delete
Optionally, only return members that satisfy a given predicate."""
[247] Fix | Delete
results = []
[248] Fix | Delete
for key in dir(object):
[249] Fix | Delete
try:
[250] Fix | Delete
value = getattr(object, key)
[251] Fix | Delete
except AttributeError:
[252] Fix | Delete
continue
[253] Fix | Delete
if not predicate or predicate(value):
[254] Fix | Delete
results.append((key, value))
[255] Fix | Delete
results.sort()
[256] Fix | Delete
return results
[257] Fix | Delete
[258] Fix | Delete
Attribute = namedtuple('Attribute', 'name kind defining_class object')
[259] Fix | Delete
[260] Fix | Delete
def classify_class_attrs(cls):
[261] Fix | Delete
"""Return list of attribute-descriptor tuples.
[262] Fix | Delete
[263] Fix | Delete
For each name in dir(cls), the return list contains a 4-tuple
[264] Fix | Delete
with these elements:
[265] Fix | Delete
[266] Fix | Delete
0. The name (a string).
[267] Fix | Delete
[268] Fix | Delete
1. The kind of attribute this is, one of these strings:
[269] Fix | Delete
'class method' created via classmethod()
[270] Fix | Delete
'static method' created via staticmethod()
[271] Fix | Delete
'property' created via property()
[272] Fix | Delete
'method' any other flavor of method
[273] Fix | Delete
'data' not a method
[274] Fix | Delete
[275] Fix | Delete
2. The class which defined this attribute (a class).
[276] Fix | Delete
[277] Fix | Delete
3. The object as obtained directly from the defining class's
[278] Fix | Delete
__dict__, not via getattr. This is especially important for
[279] Fix | Delete
data attributes: C.data is just a data object, but
[280] Fix | Delete
C.__dict__['data'] may be a data descriptor with additional
[281] Fix | Delete
info, like a __doc__ string.
[282] Fix | Delete
"""
[283] Fix | Delete
[284] Fix | Delete
mro = getmro(cls)
[285] Fix | Delete
names = dir(cls)
[286] Fix | Delete
result = []
[287] Fix | Delete
for name in names:
[288] Fix | Delete
# Get the object associated with the name, and where it was defined.
[289] Fix | Delete
# Getting an obj from the __dict__ sometimes reveals more than
[290] Fix | Delete
# using getattr. Static and class methods are dramatic examples.
[291] Fix | Delete
# Furthermore, some objects may raise an Exception when fetched with
[292] Fix | Delete
# getattr(). This is the case with some descriptors (bug #1785).
[293] Fix | Delete
# Thus, we only use getattr() as a last resort.
[294] Fix | Delete
homecls = None
[295] Fix | Delete
for base in (cls,) + mro:
[296] Fix | Delete
if name in base.__dict__:
[297] Fix | Delete
obj = base.__dict__[name]
[298] Fix | Delete
homecls = base
[299] Fix | Delete
break
[300] Fix | Delete
else:
[301] Fix | Delete
obj = getattr(cls, name)
[302] Fix | Delete
homecls = getattr(obj, "__objclass__", homecls)
[303] Fix | Delete
[304] Fix | Delete
# Classify the object.
[305] Fix | Delete
if isinstance(obj, staticmethod):
[306] Fix | Delete
kind = "static method"
[307] Fix | Delete
elif isinstance(obj, classmethod):
[308] Fix | Delete
kind = "class method"
[309] Fix | Delete
elif isinstance(obj, property):
[310] Fix | Delete
kind = "property"
[311] Fix | Delete
elif ismethoddescriptor(obj):
[312] Fix | Delete
kind = "method"
[313] Fix | Delete
elif isdatadescriptor(obj):
[314] Fix | Delete
kind = "data"
[315] Fix | Delete
else:
[316] Fix | Delete
obj_via_getattr = getattr(cls, name)
[317] Fix | Delete
if (ismethod(obj_via_getattr) or
[318] Fix | Delete
ismethoddescriptor(obj_via_getattr)):
[319] Fix | Delete
kind = "method"
[320] Fix | Delete
else:
[321] Fix | Delete
kind = "data"
[322] Fix | Delete
obj = obj_via_getattr
[323] Fix | Delete
[324] Fix | Delete
result.append(Attribute(name, kind, homecls, obj))
[325] Fix | Delete
[326] Fix | Delete
return result
[327] Fix | Delete
[328] Fix | Delete
# ----------------------------------------------------------- class helpers
[329] Fix | Delete
def _searchbases(cls, accum):
[330] Fix | Delete
# Simulate the "classic class" search order.
[331] Fix | Delete
if cls in accum:
[332] Fix | Delete
return
[333] Fix | Delete
accum.append(cls)
[334] Fix | Delete
for base in cls.__bases__:
[335] Fix | Delete
_searchbases(base, accum)
[336] Fix | Delete
[337] Fix | Delete
def getmro(cls):
[338] Fix | Delete
"Return tuple of base classes (including cls) in method resolution order."
[339] Fix | Delete
if hasattr(cls, "__mro__"):
[340] Fix | Delete
return cls.__mro__
[341] Fix | Delete
else:
[342] Fix | Delete
result = []
[343] Fix | Delete
_searchbases(cls, result)
[344] Fix | Delete
return tuple(result)
[345] Fix | Delete
[346] Fix | Delete
# -------------------------------------------------- source code extraction
[347] Fix | Delete
def indentsize(line):
[348] Fix | Delete
"""Return the indent size, in spaces, at the start of a line of text."""
[349] Fix | Delete
expline = string.expandtabs(line)
[350] Fix | Delete
return len(expline) - len(string.lstrip(expline))
[351] Fix | Delete
[352] Fix | Delete
def getdoc(object):
[353] Fix | Delete
"""Get the documentation string for an object.
[354] Fix | Delete
[355] Fix | Delete
All tabs are expanded to spaces. To clean up docstrings that are
[356] Fix | Delete
indented to line up with blocks of code, any whitespace than can be
[357] Fix | Delete
uniformly removed from the second line onwards is removed."""
[358] Fix | Delete
try:
[359] Fix | Delete
doc = object.__doc__
[360] Fix | Delete
except AttributeError:
[361] Fix | Delete
return None
[362] Fix | Delete
if not isinstance(doc, types.StringTypes):
[363] Fix | Delete
return None
[364] Fix | Delete
return cleandoc(doc)
[365] Fix | Delete
[366] Fix | Delete
def cleandoc(doc):
[367] Fix | Delete
"""Clean up indentation from docstrings.
[368] Fix | Delete
[369] Fix | Delete
Any whitespace that can be uniformly removed from the second line
[370] Fix | Delete
onwards is removed."""
[371] Fix | Delete
try:
[372] Fix | Delete
lines = string.split(string.expandtabs(doc), '\n')
[373] Fix | Delete
except UnicodeError:
[374] Fix | Delete
return None
[375] Fix | Delete
else:
[376] Fix | Delete
# Find minimum indentation of any non-blank lines after first line.
[377] Fix | Delete
margin = sys.maxint
[378] Fix | Delete
for line in lines[1:]:
[379] Fix | Delete
content = len(string.lstrip(line))
[380] Fix | Delete
if content:
[381] Fix | Delete
indent = len(line) - content
[382] Fix | Delete
margin = min(margin, indent)
[383] Fix | Delete
# Remove indentation.
[384] Fix | Delete
if lines:
[385] Fix | Delete
lines[0] = lines[0].lstrip()
[386] Fix | Delete
if margin < sys.maxint:
[387] Fix | Delete
for i in range(1, len(lines)): lines[i] = lines[i][margin:]
[388] Fix | Delete
# Remove any trailing or leading blank lines.
[389] Fix | Delete
while lines and not lines[-1]:
[390] Fix | Delete
lines.pop()
[391] Fix | Delete
while lines and not lines[0]:
[392] Fix | Delete
lines.pop(0)
[393] Fix | Delete
return string.join(lines, '\n')
[394] Fix | Delete
[395] Fix | Delete
def getfile(object):
[396] Fix | Delete
"""Work out which source or compiled file an object was defined in."""
[397] Fix | Delete
if ismodule(object):
[398] Fix | Delete
if hasattr(object, '__file__'):
[399] Fix | Delete
return object.__file__
[400] Fix | Delete
raise TypeError('{!r} is a built-in module'.format(object))
[401] Fix | Delete
if isclass(object):
[402] Fix | Delete
object = sys.modules.get(object.__module__)
[403] Fix | Delete
if hasattr(object, '__file__'):
[404] Fix | Delete
return object.__file__
[405] Fix | Delete
raise TypeError('{!r} is a built-in class'.format(object))
[406] Fix | Delete
if ismethod(object):
[407] Fix | Delete
object = object.im_func
[408] Fix | Delete
if isfunction(object):
[409] Fix | Delete
object = object.func_code
[410] Fix | Delete
if istraceback(object):
[411] Fix | Delete
object = object.tb_frame
[412] Fix | Delete
if isframe(object):
[413] Fix | Delete
object = object.f_code
[414] Fix | Delete
if iscode(object):
[415] Fix | Delete
return object.co_filename
[416] Fix | Delete
raise TypeError('{!r} is not a module, class, method, '
[417] Fix | Delete
'function, traceback, frame, or code object'.format(object))
[418] Fix | Delete
[419] Fix | Delete
ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
[420] Fix | Delete
[421] Fix | Delete
def getmoduleinfo(path):
[422] Fix | Delete
"""Get the module name, suffix, mode, and module type for a given file."""
[423] Fix | Delete
filename = os.path.basename(path)
[424] Fix | Delete
suffixes = map(lambda info:
[425] Fix | Delete
(-len(info[0]), info[0], info[1], info[2]),
[426] Fix | Delete
imp.get_suffixes())
[427] Fix | Delete
suffixes.sort() # try longest suffixes first, in case they overlap
[428] Fix | Delete
for neglen, suffix, mode, mtype in suffixes:
[429] Fix | Delete
if filename[neglen:] == suffix:
[430] Fix | Delete
return ModuleInfo(filename[:neglen], suffix, mode, mtype)
[431] Fix | Delete
[432] Fix | Delete
def getmodulename(path):
[433] Fix | Delete
"""Return the module name for a given file, or None."""
[434] Fix | Delete
info = getmoduleinfo(path)
[435] Fix | Delete
if info: return info[0]
[436] Fix | Delete
[437] Fix | Delete
def getsourcefile(object):
[438] Fix | Delete
"""Return the filename that can be used to locate an object's source.
[439] Fix | Delete
Return None if no way can be identified to get the source.
[440] Fix | Delete
"""
[441] Fix | Delete
filename = getfile(object)
[442] Fix | Delete
if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
[443] Fix | Delete
filename = filename[:-4] + '.py'
[444] Fix | Delete
for suffix, mode, kind in imp.get_suffixes():
[445] Fix | Delete
if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
[446] Fix | Delete
# Looks like a binary file. We want to only return a text file.
[447] Fix | Delete
return None
[448] Fix | Delete
if os.path.exists(filename):
[449] Fix | Delete
return filename
[450] Fix | Delete
# only return a non-existent filename if the module has a PEP 302 loader
[451] Fix | Delete
if hasattr(getmodule(object, filename), '__loader__'):
[452] Fix | Delete
return filename
[453] Fix | Delete
# or it is in the linecache
[454] Fix | Delete
if filename in linecache.cache:
[455] Fix | Delete
return filename
[456] Fix | Delete
[457] Fix | Delete
def getabsfile(object, _filename=None):
[458] Fix | Delete
"""Return an absolute path to the source or compiled file for an object.
[459] Fix | Delete
[460] Fix | Delete
The idea is for each object to have a unique origin, so this routine
[461] Fix | Delete
normalizes the result as much as possible."""
[462] Fix | Delete
if _filename is None:
[463] Fix | Delete
_filename = getsourcefile(object) or getfile(object)
[464] Fix | Delete
return os.path.normcase(os.path.abspath(_filename))
[465] Fix | Delete
[466] Fix | Delete
modulesbyfile = {}
[467] Fix | Delete
_filesbymodname = {}
[468] Fix | Delete
[469] Fix | Delete
def getmodule(object, _filename=None):
[470] Fix | Delete
"""Return the module an object was defined in, or None if not found."""
[471] Fix | Delete
if ismodule(object):
[472] Fix | Delete
return object
[473] Fix | Delete
if hasattr(object, '__module__'):
[474] Fix | Delete
return sys.modules.get(object.__module__)
[475] Fix | Delete
# Try the filename to modulename cache
[476] Fix | Delete
if _filename is not None and _filename in modulesbyfile:
[477] Fix | Delete
return sys.modules.get(modulesbyfile[_filename])
[478] Fix | Delete
# Try the cache again with the absolute file name
[479] Fix | Delete
try:
[480] Fix | Delete
file = getabsfile(object, _filename)
[481] Fix | Delete
except TypeError:
[482] Fix | Delete
return None
[483] Fix | Delete
if file in modulesbyfile:
[484] Fix | Delete
return sys.modules.get(modulesbyfile[file])
[485] Fix | Delete
# Update the filename to module name cache and check yet again
[486] Fix | Delete
# Copy sys.modules in order to cope with changes while iterating
[487] Fix | Delete
for modname, module in sys.modules.items():
[488] Fix | Delete
if ismodule(module) and hasattr(module, '__file__'):
[489] Fix | Delete
f = module.__file__
[490] Fix | Delete
if f == _filesbymodname.get(modname, None):
[491] Fix | Delete
# Have already mapped this module, so skip it
[492] Fix | Delete
continue
[493] Fix | Delete
_filesbymodname[modname] = f
[494] Fix | Delete
f = getabsfile(module)
[495] Fix | Delete
# Always map to the name the module knows itself by
[496] Fix | Delete
modulesbyfile[f] = modulesbyfile[
[497] Fix | Delete
os.path.realpath(f)] = module.__name__
[498] Fix | Delete
if file in modulesbyfile:
[499] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function