Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/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 provides same attributes as functions.
[157] Fix | Delete
[158] Fix | Delete
See help(isfunction) for attributes listing."""
[159] Fix | Delete
return bool((isfunction(object) or ismethod(object)) and
[160] Fix | Delete
object.func_code.co_flags & CO_GENERATOR)
[161] Fix | Delete
[162] Fix | Delete
def isgenerator(object):
[163] Fix | Delete
"""Return true if the object is a generator.
[164] Fix | Delete
[165] Fix | Delete
Generator objects provide these attributes:
[166] Fix | Delete
__iter__ defined to support iteration over container
[167] Fix | Delete
close raises a new GeneratorExit exception inside the
[168] Fix | Delete
generator to terminate the iteration
[169] Fix | Delete
gi_code code object
[170] Fix | Delete
gi_frame frame object or possibly None once the generator has
[171] Fix | Delete
been exhausted
[172] Fix | Delete
gi_running set to 1 when generator is executing, 0 otherwise
[173] Fix | Delete
next return the next item from the container
[174] Fix | Delete
send resumes the generator and "sends" a value that becomes
[175] Fix | Delete
the result of the current yield-expression
[176] Fix | Delete
throw used to raise an exception inside the generator"""
[177] Fix | Delete
return isinstance(object, types.GeneratorType)
[178] Fix | Delete
[179] Fix | Delete
def istraceback(object):
[180] Fix | Delete
"""Return true if the object is a traceback.
[181] Fix | Delete
[182] Fix | Delete
Traceback objects provide these attributes:
[183] Fix | Delete
tb_frame frame object at this level
[184] Fix | Delete
tb_lasti index of last attempted instruction in bytecode
[185] Fix | Delete
tb_lineno current line number in Python source code
[186] Fix | Delete
tb_next next inner traceback object (called by this level)"""
[187] Fix | Delete
return isinstance(object, types.TracebackType)
[188] Fix | Delete
[189] Fix | Delete
def isframe(object):
[190] Fix | Delete
"""Return true if the object is a frame object.
[191] Fix | Delete
[192] Fix | Delete
Frame objects provide these attributes:
[193] Fix | Delete
f_back next outer frame object (this frame's caller)
[194] Fix | Delete
f_builtins built-in namespace seen by this frame
[195] Fix | Delete
f_code code object being executed in this frame
[196] Fix | Delete
f_exc_traceback traceback if raised in this frame, or None
[197] Fix | Delete
f_exc_type exception type if raised in this frame, or None
[198] Fix | Delete
f_exc_value exception value if raised in this frame, or None
[199] Fix | Delete
f_globals global namespace seen by this frame
[200] Fix | Delete
f_lasti index of last attempted instruction in bytecode
[201] Fix | Delete
f_lineno current line number in Python source code
[202] Fix | Delete
f_locals local namespace seen by this frame
[203] Fix | Delete
f_restricted 0 or 1 if frame is in restricted execution mode
[204] Fix | Delete
f_trace tracing function for this frame, or None"""
[205] Fix | Delete
return isinstance(object, types.FrameType)
[206] Fix | Delete
[207] Fix | Delete
def iscode(object):
[208] Fix | Delete
"""Return true if the object is a code object.
[209] Fix | Delete
[210] Fix | Delete
Code objects provide these attributes:
[211] Fix | Delete
co_argcount number of arguments (not including * or ** args)
[212] Fix | Delete
co_code string of raw compiled bytecode
[213] Fix | Delete
co_consts tuple of constants used in the bytecode
[214] Fix | Delete
co_filename name of file in which this code object was created
[215] Fix | Delete
co_firstlineno number of first line in Python source code
[216] Fix | Delete
co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
[217] Fix | Delete
co_lnotab encoded mapping of line numbers to bytecode indices
[218] Fix | Delete
co_name name with which this code object was defined
[219] Fix | Delete
co_names tuple of names of local variables
[220] Fix | Delete
co_nlocals number of local variables
[221] Fix | Delete
co_stacksize virtual machine stack space required
[222] Fix | Delete
co_varnames tuple of names of arguments and local variables"""
[223] Fix | Delete
return isinstance(object, types.CodeType)
[224] Fix | Delete
[225] Fix | Delete
def isbuiltin(object):
[226] Fix | Delete
"""Return true if the object is a built-in function or method.
[227] Fix | Delete
[228] Fix | Delete
Built-in functions and methods provide these attributes:
[229] Fix | Delete
__doc__ documentation string
[230] Fix | Delete
__name__ original name of this function or method
[231] Fix | Delete
__self__ instance to which a method is bound, or None"""
[232] Fix | Delete
return isinstance(object, types.BuiltinFunctionType)
[233] Fix | Delete
[234] Fix | Delete
def isroutine(object):
[235] Fix | Delete
"""Return true if the object is any kind of function or method."""
[236] Fix | Delete
return (isbuiltin(object)
[237] Fix | Delete
or isfunction(object)
[238] Fix | Delete
or ismethod(object)
[239] Fix | Delete
or ismethoddescriptor(object))
[240] Fix | Delete
[241] Fix | Delete
def isabstract(object):
[242] Fix | Delete
"""Return true if the object is an abstract base class (ABC)."""
[243] Fix | Delete
return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
[244] Fix | Delete
[245] Fix | Delete
def getmembers(object, predicate=None):
[246] Fix | Delete
"""Return all members of an object as (name, value) pairs sorted by name.
[247] Fix | Delete
Optionally, only return members that satisfy a given predicate."""
[248] Fix | Delete
results = []
[249] Fix | Delete
for key in dir(object):
[250] Fix | Delete
try:
[251] Fix | Delete
value = getattr(object, key)
[252] Fix | Delete
except AttributeError:
[253] Fix | Delete
continue
[254] Fix | Delete
if not predicate or predicate(value):
[255] Fix | Delete
results.append((key, value))
[256] Fix | Delete
results.sort()
[257] Fix | Delete
return results
[258] Fix | Delete
[259] Fix | Delete
Attribute = namedtuple('Attribute', 'name kind defining_class object')
[260] Fix | Delete
[261] Fix | Delete
def classify_class_attrs(cls):
[262] Fix | Delete
"""Return list of attribute-descriptor tuples.
[263] Fix | Delete
[264] Fix | Delete
For each name in dir(cls), the return list contains a 4-tuple
[265] Fix | Delete
with these elements:
[266] Fix | Delete
[267] Fix | Delete
0. The name (a string).
[268] Fix | Delete
[269] Fix | Delete
1. The kind of attribute this is, one of these strings:
[270] Fix | Delete
'class method' created via classmethod()
[271] Fix | Delete
'static method' created via staticmethod()
[272] Fix | Delete
'property' created via property()
[273] Fix | Delete
'method' any other flavor of method
[274] Fix | Delete
'data' not a method
[275] Fix | Delete
[276] Fix | Delete
2. The class which defined this attribute (a class).
[277] Fix | Delete
[278] Fix | Delete
3. The object as obtained directly from the defining class's
[279] Fix | Delete
__dict__, not via getattr. This is especially important for
[280] Fix | Delete
data attributes: C.data is just a data object, but
[281] Fix | Delete
C.__dict__['data'] may be a data descriptor with additional
[282] Fix | Delete
info, like a __doc__ string.
[283] Fix | Delete
"""
[284] Fix | Delete
[285] Fix | Delete
mro = getmro(cls)
[286] Fix | Delete
names = dir(cls)
[287] Fix | Delete
result = []
[288] Fix | Delete
for name in names:
[289] Fix | Delete
# Get the object associated with the name, and where it was defined.
[290] Fix | Delete
# Getting an obj from the __dict__ sometimes reveals more than
[291] Fix | Delete
# using getattr. Static and class methods are dramatic examples.
[292] Fix | Delete
# Furthermore, some objects may raise an Exception when fetched with
[293] Fix | Delete
# getattr(). This is the case with some descriptors (bug #1785).
[294] Fix | Delete
# Thus, we only use getattr() as a last resort.
[295] Fix | Delete
homecls = None
[296] Fix | Delete
for base in (cls,) + mro:
[297] Fix | Delete
if name in base.__dict__:
[298] Fix | Delete
obj = base.__dict__[name]
[299] Fix | Delete
homecls = base
[300] Fix | Delete
break
[301] Fix | Delete
else:
[302] Fix | Delete
obj = getattr(cls, name)
[303] Fix | Delete
homecls = getattr(obj, "__objclass__", homecls)
[304] Fix | Delete
[305] Fix | Delete
# Classify the object.
[306] Fix | Delete
if isinstance(obj, staticmethod):
[307] Fix | Delete
kind = "static method"
[308] Fix | Delete
elif isinstance(obj, classmethod):
[309] Fix | Delete
kind = "class method"
[310] Fix | Delete
elif isinstance(obj, property):
[311] Fix | Delete
kind = "property"
[312] Fix | Delete
elif ismethoddescriptor(obj):
[313] Fix | Delete
kind = "method"
[314] Fix | Delete
elif isdatadescriptor(obj):
[315] Fix | Delete
kind = "data"
[316] Fix | Delete
else:
[317] Fix | Delete
obj_via_getattr = getattr(cls, name)
[318] Fix | Delete
if (ismethod(obj_via_getattr) or
[319] Fix | Delete
ismethoddescriptor(obj_via_getattr)):
[320] Fix | Delete
kind = "method"
[321] Fix | Delete
else:
[322] Fix | Delete
kind = "data"
[323] Fix | Delete
obj = obj_via_getattr
[324] Fix | Delete
[325] Fix | Delete
result.append(Attribute(name, kind, homecls, obj))
[326] Fix | Delete
[327] Fix | Delete
return result
[328] Fix | Delete
[329] Fix | Delete
# ----------------------------------------------------------- class helpers
[330] Fix | Delete
def _searchbases(cls, accum):
[331] Fix | Delete
# Simulate the "classic class" search order.
[332] Fix | Delete
if cls in accum:
[333] Fix | Delete
return
[334] Fix | Delete
accum.append(cls)
[335] Fix | Delete
for base in cls.__bases__:
[336] Fix | Delete
_searchbases(base, accum)
[337] Fix | Delete
[338] Fix | Delete
def getmro(cls):
[339] Fix | Delete
"Return tuple of base classes (including cls) in method resolution order."
[340] Fix | Delete
if hasattr(cls, "__mro__"):
[341] Fix | Delete
return cls.__mro__
[342] Fix | Delete
else:
[343] Fix | Delete
result = []
[344] Fix | Delete
_searchbases(cls, result)
[345] Fix | Delete
return tuple(result)
[346] Fix | Delete
[347] Fix | Delete
# -------------------------------------------------- source code extraction
[348] Fix | Delete
def indentsize(line):
[349] Fix | Delete
"""Return the indent size, in spaces, at the start of a line of text."""
[350] Fix | Delete
expline = string.expandtabs(line)
[351] Fix | Delete
return len(expline) - len(string.lstrip(expline))
[352] Fix | Delete
[353] Fix | Delete
def getdoc(object):
[354] Fix | Delete
"""Get the documentation string for an object.
[355] Fix | Delete
[356] Fix | Delete
All tabs are expanded to spaces. To clean up docstrings that are
[357] Fix | Delete
indented to line up with blocks of code, any whitespace than can be
[358] Fix | Delete
uniformly removed from the second line onwards is removed."""
[359] Fix | Delete
try:
[360] Fix | Delete
doc = object.__doc__
[361] Fix | Delete
except AttributeError:
[362] Fix | Delete
return None
[363] Fix | Delete
if not isinstance(doc, types.StringTypes):
[364] Fix | Delete
return None
[365] Fix | Delete
return cleandoc(doc)
[366] Fix | Delete
[367] Fix | Delete
def cleandoc(doc):
[368] Fix | Delete
"""Clean up indentation from docstrings.
[369] Fix | Delete
[370] Fix | Delete
Any whitespace that can be uniformly removed from the second line
[371] Fix | Delete
onwards is removed."""
[372] Fix | Delete
try:
[373] Fix | Delete
lines = string.split(string.expandtabs(doc), '\n')
[374] Fix | Delete
except UnicodeError:
[375] Fix | Delete
return None
[376] Fix | Delete
else:
[377] Fix | Delete
# Find minimum indentation of any non-blank lines after first line.
[378] Fix | Delete
margin = sys.maxint
[379] Fix | Delete
for line in lines[1:]:
[380] Fix | Delete
content = len(string.lstrip(line))
[381] Fix | Delete
if content:
[382] Fix | Delete
indent = len(line) - content
[383] Fix | Delete
margin = min(margin, indent)
[384] Fix | Delete
# Remove indentation.
[385] Fix | Delete
if lines:
[386] Fix | Delete
lines[0] = lines[0].lstrip()
[387] Fix | Delete
if margin < sys.maxint:
[388] Fix | Delete
for i in range(1, len(lines)): lines[i] = lines[i][margin:]
[389] Fix | Delete
# Remove any trailing or leading blank lines.
[390] Fix | Delete
while lines and not lines[-1]:
[391] Fix | Delete
lines.pop()
[392] Fix | Delete
while lines and not lines[0]:
[393] Fix | Delete
lines.pop(0)
[394] Fix | Delete
return string.join(lines, '\n')
[395] Fix | Delete
[396] Fix | Delete
def getfile(object):
[397] Fix | Delete
"""Work out which source or compiled file an object was defined in."""
[398] Fix | Delete
if ismodule(object):
[399] Fix | Delete
if hasattr(object, '__file__'):
[400] Fix | Delete
return object.__file__
[401] Fix | Delete
raise TypeError('{!r} is a built-in module'.format(object))
[402] Fix | Delete
if isclass(object):
[403] Fix | Delete
object = sys.modules.get(object.__module__)
[404] Fix | Delete
if hasattr(object, '__file__'):
[405] Fix | Delete
return object.__file__
[406] Fix | Delete
raise TypeError('{!r} is a built-in class'.format(object))
[407] Fix | Delete
if ismethod(object):
[408] Fix | Delete
object = object.im_func
[409] Fix | Delete
if isfunction(object):
[410] Fix | Delete
object = object.func_code
[411] Fix | Delete
if istraceback(object):
[412] Fix | Delete
object = object.tb_frame
[413] Fix | Delete
if isframe(object):
[414] Fix | Delete
object = object.f_code
[415] Fix | Delete
if iscode(object):
[416] Fix | Delete
return object.co_filename
[417] Fix | Delete
raise TypeError('{!r} is not a module, class, method, '
[418] Fix | Delete
'function, traceback, frame, or code object'.format(object))
[419] Fix | Delete
[420] Fix | Delete
ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
[421] Fix | Delete
[422] Fix | Delete
def getmoduleinfo(path):
[423] Fix | Delete
"""Get the module name, suffix, mode, and module type for a given file."""
[424] Fix | Delete
filename = os.path.basename(path)
[425] Fix | Delete
suffixes = map(lambda info:
[426] Fix | Delete
(-len(info[0]), info[0], info[1], info[2]),
[427] Fix | Delete
imp.get_suffixes())
[428] Fix | Delete
suffixes.sort() # try longest suffixes first, in case they overlap
[429] Fix | Delete
for neglen, suffix, mode, mtype in suffixes:
[430] Fix | Delete
if filename[neglen:] == suffix:
[431] Fix | Delete
return ModuleInfo(filename[:neglen], suffix, mode, mtype)
[432] Fix | Delete
[433] Fix | Delete
def getmodulename(path):
[434] Fix | Delete
"""Return the module name for a given file, or None."""
[435] Fix | Delete
info = getmoduleinfo(path)
[436] Fix | Delete
if info: return info[0]
[437] Fix | Delete
[438] Fix | Delete
def getsourcefile(object):
[439] Fix | Delete
"""Return the filename that can be used to locate an object's source.
[440] Fix | Delete
Return None if no way can be identified to get the source.
[441] Fix | Delete
"""
[442] Fix | Delete
filename = getfile(object)
[443] Fix | Delete
if string.lower(filename[-4:]) in ('.pyc', '.pyo'):
[444] Fix | Delete
filename = filename[:-4] + '.py'
[445] Fix | Delete
for suffix, mode, kind in imp.get_suffixes():
[446] Fix | Delete
if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
[447] Fix | Delete
# Looks like a binary file. We want to only return a text file.
[448] Fix | Delete
return None
[449] Fix | Delete
if os.path.exists(filename):
[450] Fix | Delete
return filename
[451] Fix | Delete
# only return a non-existent filename if the module has a PEP 302 loader
[452] Fix | Delete
if hasattr(getmodule(object, filename), '__loader__'):
[453] Fix | Delete
return filename
[454] Fix | Delete
# or it is in the linecache
[455] Fix | Delete
if filename in linecache.cache:
[456] Fix | Delete
return filename
[457] Fix | Delete
[458] Fix | Delete
def getabsfile(object, _filename=None):
[459] Fix | Delete
"""Return an absolute path to the source or compiled file for an object.
[460] Fix | Delete
[461] Fix | Delete
The idea is for each object to have a unique origin, so this routine
[462] Fix | Delete
normalizes the result as much as possible."""
[463] Fix | Delete
if _filename is None:
[464] Fix | Delete
_filename = getsourcefile(object) or getfile(object)
[465] Fix | Delete
return os.path.normcase(os.path.abspath(_filename))
[466] Fix | Delete
[467] Fix | Delete
modulesbyfile = {}
[468] Fix | Delete
_filesbymodname = {}
[469] Fix | Delete
[470] Fix | Delete
def getmodule(object, _filename=None):
[471] Fix | Delete
"""Return the module an object was defined in, or None if not found."""
[472] Fix | Delete
if ismodule(object):
[473] Fix | Delete
return object
[474] Fix | Delete
if hasattr(object, '__module__'):
[475] Fix | Delete
return sys.modules.get(object.__module__)
[476] Fix | Delete
# Try the filename to modulename cache
[477] Fix | Delete
if _filename is not None and _filename in modulesbyfile:
[478] Fix | Delete
return sys.modules.get(modulesbyfile[_filename])
[479] Fix | Delete
# Try the cache again with the absolute file name
[480] Fix | Delete
try:
[481] Fix | Delete
file = getabsfile(object, _filename)
[482] Fix | Delete
except TypeError:
[483] Fix | Delete
return None
[484] Fix | Delete
if file in modulesbyfile:
[485] Fix | Delete
return sys.modules.get(modulesbyfile[file])
[486] Fix | Delete
# Update the filename to module name cache and check yet again
[487] Fix | Delete
# Copy sys.modules in order to cope with changes while iterating
[488] Fix | Delete
for modname, module in sys.modules.items():
[489] Fix | Delete
if ismodule(module) and hasattr(module, '__file__'):
[490] Fix | Delete
f = module.__file__
[491] Fix | Delete
if f == _filesbymodname.get(modname, None):
[492] Fix | Delete
# Have already mapped this module, so skip it
[493] Fix | Delete
continue
[494] Fix | Delete
_filesbymodname[modname] = f
[495] Fix | Delete
f = getabsfile(module)
[496] Fix | Delete
# Always map to the name the module knows itself by
[497] Fix | Delete
modulesbyfile[f] = modulesbyfile[
[498] Fix | Delete
os.path.realpath(f)] = module.__name__
[499] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function