def desc(self): # TODO -- consolidate this to a class that extends str that will try doc # and then move to comments if doc fails, that will greatly simplify # this method hashbang_regex = re.compile(r"^#!.*") desc = inspect.getdoc(self.callback) if not desc: desc = inspect.getcomments(self.callback) if desc: desc = hashbang_regex.sub("", desc).strip() if not desc: cb_method = self.callable if is_py2: desc = inspect.getdoc(cb_method) if not desc: desc = inspect.getcomments(cb_method) if desc: desc = hashbang_regex.sub("", desc).strip() else: # avoid method doc inheritance in py >=3.5 desc = cb_method.__doc__ if not desc: desc = '' return desc
def fetch_item_content(self, key, item): is_method = inspect.ismethod(item) is_function = inspect.isfunction(item) if is_method or is_function: # Get source code try: source = inspect.getsource(item) except IOError: source = "" self.add_source_for_key(key, source) self.output_data.append("%s:doc" % key, inspect.getdoc(item)) self.output_data.append("%s:comments" % key, inspect.getcomments(item)) else: # not a function or a method try: # If this can be JSON-serialized, leave it alone... json.dumps(item) self.add_source_for_key(key, item) except TypeError: # ... if it can't, convert it to a string to avoid problems. self.add_source_for_key(key, str(item)) except UnicodeDecodeError: print "skipping", item
def getdoc(obj): """Return text documentation generated by pydoc.TextDoc.docroutine""" doc = inspect.getdoc(obj) or inspect.getcomments(obj) or '' if isinstance(obj, collections.Callable): try: name = obj.__name__ except AttributeError: return doc if inspect.ismethod(obj): imclass = obj.__self__.__class__ if obj.__self__ is not None: note = '\n Method of %s instance' \ % obj.__self__.__class__.__name__ else: note = '\n Unbound %s method' % imclass.__name__ obj = obj.__func__ elif hasattr(obj, '__module__'): note = '\n Function of %s module' % obj.__module__ else: note = '\n Function' title = obj.__name__ if inspect.isfunction(obj): args, varargs, varkw, defaults = inspect.getargspec(obj) argspec = inspect.formatargspec(args, varargs, varkw, defaults, formatvalue=lambda o:'='+repr(o)) if name == '<lambda>': title = name + ' lambda ' argspec = argspec[1:-1] # remove parentheses else: argspec = '(...)' doc = '%s\n\n%s\n' % (title+argspec+note, doc) return doc
def __check_text( self, obj): self.__check_text_impl( obj, inspect.getdoc( obj ), 'documentation string' ) try: if self.getsourcefile( obj ): self.__check_text_impl( obj, inspect.getcomments( obj ), 'comment' ) except TypeError: pass
def testinspect(): import inspect print GREEN+"[Position1] inspect.getcomments\n", inspect.getcomments(testinspect) print GREEN+"\n[Position2] inspect.getsource\n", inspect.getsource(testinspect) lines,no = inspect.getsourcelines(testinspect) print GREEN+"\n[Position3] inspect.getsourcelines\n", no for l in lines: print l, print GREEN+"\n[Position4] getargvalues/formatargvalues\n", no def f0(a,b,c,*args,**kws): args, varargs, keywords, locals = inspect.getargvalues(inspect.currentframe()) print inspect.formatargvalues(args, varargs, keywords, locals) f0(1,2,3,'a','b','c', x=10,y=20,z=30) print GREEN+"\n[Position5] inspect.stack()\n", no def f1(): def f2(): def f3(): print "\n\n".join([ "%d:\n"%-i + "\n".join(["\t"+str(item) for item in s]) for i,s in enumerate(inspect.stack()) ]) f3() f2() f1() print GREEN+"\n[Position6] inspect.currentframe()\n", no ff=inspect.currentframe() print dir(ff) for x in ff.f_locals: print x
def append_item_content(self, key, item): self.log_debug("appending content for %s" % key) try: source = inspect.getsource(item) self.output_data.append("%s:source" % key, source) except (TypeError, IOError, sqlite3.ProgrammingError): pass try: doc = inspect.getdoc(item) self.output_data.append("%s:doc" % key, doc) except (TypeError, IOError, sqlite3.ProgrammingError): pass try: comment = inspect.getcomments(item) self.output_data.append("%s:comments" % key, comment) except (TypeError, IOError, sqlite3.ProgrammingError): pass try: value = json.dumps(item) self.output_data.append("%s:value" % key, value) except TypeError: pass
def dump_object(name, tmp_obj): print ">>>>>>>>>>>>>>>>>>>>>>>>>>", name, tmp_obj print describe(tmp_obj) # From line 921, method docmodule: classes = [] for key, value in inspect.getmembers(tmp_obj, inspect.isclass): if (inspect.getmodule(value) or tmp_obj) is tmp_obj: classes.append((key, value)) dump_object(key, value) funcs = [] for key, value in inspect.getmembers(tmp_obj, inspect.isroutine): if inspect.isbuiltin(value) or inspect.getmodule(value) is tmp_obj: funcs.append((key, value)) data = [] for key, value in inspect.getmembers(tmp_obj, isdata): if key not in ['__builtins__', '__doc__']: data.append((key, value)) methods = [] for key, value in inspect.getmembers(tmp_obj, inspect.ismethod): if key not in ['__builtins__', '__doc__']: methods.append((key, value)) print "C:", classes print "\nF:", funcs print "\nD:", data print "\nM:", methods for m in methods: print inspect.getargspec(m[1]), inspect.getdoc(m[1]), inspect.getcomments(m[1]) print "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
def __init__(self, name, item): ChildrenBase.__init__(self, name, object_types.PROPERTY) self.getter = self.setter = self.deleter = '' try: if item.fget: self.getter = item.fget.__name__ if item.fset: self.setter = item.fset.__name__ if item.fdel: self.deleter = item.fdel.__name__ except AttributeError: # Thank you for screwing it up, Cython... if item.fget: self.getter = item.fget.__class__.__name__ if item.fset: self.setter = item.fset.__class__.__name__ if item.fdel: self.deleter = item.fdel.__class__.__name__ self.docs = getdoc(item) self.comments = getcomments(item) self.obj_type = 'Property' self.order = 6
def api_list(self, toplevel=None): """ return a formatted list of functions in an api """ apilist = {} tmsg = [] if toplevel: apilist = self.gettoplevelapilist(toplevel) else: apilist = self.getapilist() tkeys = apilist.keys() tkeys.sort() toplevels = [] for i in tkeys: toplevel, therest = i.split('.', 1) if toplevel not in toplevels: toplevels.append(toplevel) tmsg.append('@G%-10s@w' % toplevel) apif = self.get(i) comments = inspect.getcomments(apif) if comments: comments = comments.strip() tmsg.append(' @G%-15s@w : %s' % (therest, comments)) return tmsg
def process_members(self, package_name, mod): """ Process all members of the package or module passed. """ name = mod.__name__ for k, m in inspect.getmembers(mod): self.log.debug("in %s processing element %s" % (mod.__name__, k)) if not inspect.isclass(m) and hasattr(m, '__module__') and m.__module__ and m.__module__.startswith(package_name): key = "%s.%s" % (m.__module__, k) self.fetch_item_content(key, m) elif inspect.isclass(m) and m.__module__.startswith(package_name): key = "%s.%s" % (mod.__name__, k) try: item_content = inspect.getsource(m) self.artifact.output_data.append("%s:doc" % key, inspect.getdoc(m)) self.artifact.output_data.append("%s:comments" % key, inspect.getcomments(m)) self.add_source_for_key(key, item_content) except IOError: self.log.debug("can't get source for %s" % key) self.add_source_for_key(key, "") try: for ck, cm in inspect.getmembers(m): key = "%s.%s.%s" % (name, k, ck) self.fetch_item_content(key, cm) except AttributeError: pass else: key = "%s.%s" % (name, k) self.fetch_item_content(key, m)
def extract_docs(obj): doc = inspect.getdoc(obj) if doc is None: doc = _strip_comments(inspect.getcomments(obj)) if doc is None: doc = _strip_comments(get_internal_comments(obj)) return doc
def collect_swagger(title, version): swagger = {} swagger['swagger'] = '2.0' swagger['info'] = { 'title': title, "description": str(inspect.getcomments(RootController)), 'version': version, "license": { "name": "Apache 2.0", "url": "http://www.apache.org/licenses/LICENSE-2.0.html" } } swagger['host'] = "google.com" swagger['schemes'] = ['http'] swagger['basePath'] = '/' swagger['produces'] = ['application/json'] controllers = restswag.collect_controllers(RootController) _c.append(controllers) methods = restswag.collect_methods(controllers) paths = wsmeswag.getpaths(methods) swagger['paths'] = paths definitions = wsmeswag._definitions swagger['definitions'] = definitions print json.dumps(swagger, indent=2)
def run(self, args): proc = self.proc arg = proc.cmd_argstr try: if not proc.curframe: # ?? Should we have set up a dummy globals # to have persistence? value = eval(arg, None, None) else: value = eval(arg, proc.curframe.f_globals, proc.curframe.f_locals) except: t, v = sys.exc_info()[:2] if type(t) == str: exc_type_name = t else: exc_type_name = t.__name__ if exc_type_name == 'NameError': self.errmsg("Name Error: %s" % arg) else: self.errmsg("%s: %s" % (exc_type_name, proc._saferepr(v))) return False self.section("What is for %s" % arg) get_doc = False if inspect.ismethod(value): get_doc = True self.msg('method %s%s' % (value.func_code.co_name, inspect.formatargspec(inspect.getargspec(value)))) elif inspect.isfunction(value): get_doc = True self.msg('function %s%s' % (value.func_code.co_name, inspect.formatargspec(inspect.getargspec(value)))) elif inspect.isabstract(value) or \ inspect.isbuiltin(value) or \ inspect.isclass(value) or \ inspect.isgeneratorfunction(value) or \ inspect.ismethoddescriptor(value): get_doc = True self.msg(type(value)) doc = inspect.getdoc(value) if get_doc and doc: self.msg(' doc:\n%s' % doc) comments = inspect.getcomments(value) if comments: self.msg(' comments:\n%s' % comments) try: m = inspect.getmodule(value) if m: self.msg(" module:\t%s" % m) except: try: f = inspect.getfile(value) self.msg(" file: %s" % f) except: pass pass return False
def __bind__(self, func): self.func = func self.__name__ = func.__name__ self.func_args, self.func_varargs, self.func_keywords, self.func_defaults = inspect.getargspec(func) self.func_args = self.func_args if len(self.func_args) > 0 and self.func_args[0] == 'self': self.func_args = self.func_args[1:] self.params = dict([(arg, { 'name': arg, 'required': True, 'paramType': 'path', 'dataType': 'string' }) for arg in self.func_args]) doc = self.parse_docstring(inspect.getdoc(self.func)) if self.summary is None: self.summary = inspect.getcomments(self.func) or doc.to_plaintext(None).split('\n')[0].strip() if self.summary: self.summary = self.summary.strip() if self.notes is None: self.notes = doc.to_plaintext(None) if self.notes: self.notes = self.notes.strip()
def describe_module(module, kind, constants=[]): """ Describe the module object passed as argument including its classes and functions. """ module_name = module.__name__ if kind == object_types.LIBRARY: klass = Library(module_name) else: klass = Module(module_name, kind) klass.docs = getdoc(module) klass.comments = getcomments(module) klass.filename = module.__file__ inheritance_diagram = [] count = 0 for name in dir(module): if name in EXCLUDED_ATTRS: continue obj = getattr(module, name) if ismodule(obj): continue if ismemberdescriptor(obj) or isgetsetdescriptor(obj): continue if isclass(obj): count += 1 describe_class(obj, klass, module_name, constants) if obj.__module__ == module.__name__: inheritance_diagram.append(obj) elif isbuiltin(obj): count += 1 elif ismethod(obj) or isfunction(obj) or ismethoddescriptor(obj) or \ isinstance(obj, types.MethodType): count +=1 describe_func(obj, klass, module_name) else: attribute = Attribute(module_name + '.' + name, type(obj), obj) klass.Add(attribute) if constants: attribute.is_redundant = name not in constants if kind not in [object_types.PACKAGE, object_types.LIBRARY]: if inheritance_diagram and len(inheritance_diagram) < 20: klass.inheritance_diagram = inheritance.InheritanceDiagram(inheritance_diagram, klass) return klass, count
def raw_docs(self): try: return inspect.getdoc(self.py_object) except AttributeError: try: return inspect.getcomments(self.py_object) except AttributeError: return getattr(self.py_object, '__doc__', '')
def print_function(function): spec = inspect.getargspec(function) print "Constructed piecemeal:" print inspect.getcomments(function), print "def {}({}, *{}, **{}):".format( function.__name__, args_to_string(spec.args, spec.defaults), spec.varargs, spec.keywords) # Not varkw as in documentation print " \"\"\"{}\"\"\"".format(inspect.getdoc(function)) print "\nOr using formatargspec():" print "def {}{}:".format( function.__name__, inspect.formatargspec(spec.args, spec.varargs, spec.keywords, spec.defaults)) print "\nOr in one call with getsource():" print inspect.getsource(function)
def getdoc(object): result = inspect.getdoc(object) if not result: try: result = inspect.getcomments(object) except: pass return result and rstrip(result) + '\n' or ''
def get_doc(obj): doc = inspect.getdoc(obj) com = inspect.getcomments(obj) if doc and com: return '%s\n\n(%s)' % (doc, com) elif doc: return doc elif com: return com return ''
def getinfo(obj): s = getdoc(obj) or getcomments(obj) or "" if isinstance(s, type(u"")): s = s.encode("utf-8") else: try: s.decode("utf-8") except: s = "" return s
def persistdrivers(): """ 获取当前系统提供的持久化(persist)驱动 @return: """ res = [] for stcls in inspect.getmembers(storage, inspect.isclass): res.append((stcls[0], inspect.getdoc(stcls[1]) or inspect.getcomments(stcls[1]))) return jsonify(res)
def get_desc(): """Return the description of this module""" try: # Dynamic import of the package - to be able to load comments #inspect.importlib.import_module("excelapps") # return top comments of the package return inspect.getcomments(sys.modules["exceladdins"]) except Exception as e: print(e) return -1
def get_doc(obj): """Get the doc string or comments for an object. :param object: object :returns: doc string :rtype: str >>> get_doc(abs) 'abs(number) -> number\\n\\nReturn the absolute value of the argument.' """ result = inspect.getdoc(obj) or inspect.getcomments(obj) return result and RE_EMPTY_LINE.sub('', result.rstrip()) or ''
def processes(): """ 获取当前系统提供的process @return: """ res = [] for prs in inspect.getmembers(processors, inspect.isfunction): res.append((prs[0], inspect.getdoc(prs[1]) or inspect.getcomments(prs[1]))) return jsonify(res)
def generate(plugin_name, output): plugin_module_name = plugin_name + "Builder" plugin_module = "salome.%s.%s" % (plugin_name, plugin_module_name) import_str = "from salome.%s import %s" % (plugin_name, plugin_module_name) exec( import_str ) exec( "import %s" % plugin_module ) exec( "mod = %s" % plugin_module ) functions = [] for attr in dir( mod ): if attr.startswith( '_' ): continue # skip an internal methods item = getattr( mod, attr ) if type( item ).__name__ == 'function': if item not in functions: functions.append( item ) pass pass pass if functions: for function in functions: comments = inspect.getcomments(function) if comments: comments = comments.strip().split("\n") comments = "\t" + "\n\t".join(comments) output.append(comments) pass sources = inspect.getsource(function) if sources is not None: sources_list = sources.split("\n") sources_new_list = [] found = False for item in sources_list: if '"""' in item: if found == True: found = False continue else: found = True continue pass pass if found == False : sources_new_list.append(item) pass pass sources = "\n".join(sources_new_list) sources = "\t" + sources.replace("\n", "\n\t") output.append(sources) pass pass pass pass
def introspect(self): comments = inspect.getcomments(self.variable_class) # Handle dynamically generated variable classes or Jupyter Notebooks, which have no source. try: source_file_path = inspect.getsourcefile(self.variable_class) except TypeError: source_file_path = None try: source_lines, line_number = inspect.getsourcelines(self.variable_class) source_code = textwrap.dedent(''.join(source_lines)) except (IOError, TypeError): source_code, line_number = None, None return (comments, source_file_path, source_code, line_number)
def getdoc(obj): """Return text documentation generated by pydoc.TextDoc.docroutine""" doc = inspect.getdoc(obj) or inspect.getcomments(obj) or '' doc = unicode(doc) text = {'title': '', 'argspec': '', 'note': '', 'doc': doc} if callable(obj): try: name = obj.__name__ except AttributeError: text['doc'] = doc return text if inspect.ismethod(obj): imclass = obj.im_class if obj.im_self is not None: text['note'] = 'Method of %s instance' \ % obj.im_self.__class__.__name__ else: text['note'] = 'Unbound %s method' % imclass.__name__ obj = obj.im_func elif hasattr(obj, '__module__'): text['note'] = 'Function of %s module' % obj.__module__ else: text['note'] = 'Function' text['title'] = obj.__name__ if inspect.isfunction(obj): args, varargs, varkw, defaults = inspect.getargspec(obj) text['argspec'] = inspect.formatargspec(args, varargs, varkw, defaults, formatvalue=lambda o:'='+repr(o)) if name == '<lambda>': text['title'] = name + ' lambda ' text['argspec'] = text['argspec'][1:-1] # remove parentheses else: # Try to extract the argspec from the first docstring line doclines = text['doc'].split("\n") first_line = doclines[0].strip() argspec = getsignaturesfromtext(first_line, '') if argspec: text['argspec'] = argspec[0] # Eliminate the first docstring line if we found the argspec doc_st = text['doc'].find('\n') + 2 text['doc'] = text['doc'][doc_st:] else: text['argspec'] = '(...)' return text
def addin_get_desc(addin_name): """ Return the description of the given add-in :param addin_name: string containing the name of the add-in :rtype str, -1 on error """ try: # Dynamic import of the package - to be able to load comments module = inspect.importlib.import_module("exceladdins.{}".format(addin_name)) # return top comments of the package return inspect.getcomments(module) except Exception as e: print(e) return -1
def class2md(self, cls, depth=2): """Takes a class and creates markdown text to document its methods and variables. """ section = "#" * depth subsection = "#" * (depth + 2) clsname = cls.__name__ modname = cls.__module__ header = clsname path = self.get_src_path(cls) doc = self.doc2md(cls) try: init = self.func2md(cls.__init__, clsname=clsname) except (ValueError, TypeError): # this happens if __init__ is outside the repo init = "" variables = [] for name, obj in getmembers(cls, lambda a: not (inspect.isroutine(a) or inspect.ismethod(a))): if not name.startswith("_") and type(obj) == property: comments = self.doc2md(obj) or inspect.getcomments(obj) comments = "\n %s" % comments if comments else "" variables.append("\n%s %s.%s%s\n" % (subsection, clsname, name, comments)) handlers = [] for name, obj in getmembers(cls, inspect.ismethoddescriptor): if not name.startswith("_") and hasattr(obj, "__module__") and obj.__module__ == modname: handlers.append("\n%s %s.%s\n *Handler*" % (subsection, clsname, name)) methods = [] for name, obj in getmembers(cls, inspect.ismethod): if not name.startswith("_") and hasattr(obj, "__module__") and obj.__module__ == modname and name not in handlers: methods.append(self.func2md(obj, clsname=clsname, depth=depth + 1)) string = CLASS_TEMPLATE.format(section=section, header=header, path=path, doc=doc if doc else "", init=init, variables="".join(variables), handlers="".join(handlers), methods="".join(methods)) return string
def should_trace_hook(frame, event, arg): """ Return True if this frame should be traced, False if tracing should be blocked. """ # First, check whether this code object has a cached value try: co = frame.f_code result = _code_trace_cache.get(co) if result is not None: return result except: # If the frame doesn't have a code object, it doesn't matter much what we do return True # By default, trace all methods result = True # Now, look up that line of code and check for a @DontTrace # preceding or on the same line as the method. # E.g.: # #@DontTrace # def test(): # pass # ... or ... # def test(): #@DontTrace # pass try: comments = inspect.getcomments(co) if comments is not None and DONT_TRACE_TAG in comments: result = False else: lines, _ = inspect.getsourcelines(co) for line in lines: if DONT_TRACE_TAG in line: result = False break if not RE_DECORATOR.match(line): break except: # If there is any exception, keep the default behavior which is to trace. pass # Cache the result for next time _code_trace_cache[co] = result return result
def getdoc(obj): """ Return text documentation from an object. This comes in a form of dictionary with four keys: name: The name of the inspected object argspec: It's argspec note: A phrase describing the type of object (function or method) we are inspecting, and the module it belongs to. docstring: It's docstring """ docstring = inspect.getdoc(obj) or inspect.getcomments(obj) or '' # Most of the time doc will only contain ascii characters, but there are # some docstrings that contain non-ascii characters. Not all source files # declare their encoding in the first line, so querying for that might not # yield anything, either. So assume the most commonly used # multi-byte file encoding (which also covers ascii). try: docstring = to_text_string(docstring) except: pass # Doc dict keys doc = {'name': '', 'argspec': '', 'note': '', 'docstring': docstring} if callable(obj): try: name = obj.__name__ except AttributeError: doc['docstring'] = docstring return doc if inspect.ismethod(obj): imclass = get_meth_class(obj) if get_meth_class_inst(obj) is not None: doc['note'] = 'Method of %s instance' \ % get_meth_class_inst(obj).__class__.__name__ else: doc['note'] = 'Unbound %s method' % imclass.__name__ obj = get_meth_func(obj) elif hasattr(obj, '__module__'): doc['note'] = 'Function of %s module' % obj.__module__ else: doc['note'] = 'Function' doc['name'] = obj.__name__ if inspect.isfunction(obj): if PY2: args, varargs, varkw, defaults = inspect.getargspec(obj) doc['argspec'] = inspect.formatargspec( args, varargs, varkw, defaults, formatvalue=lambda o: '=' + repr(o)) else: (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations) = inspect.getfullargspec(obj) doc['argspec'] = inspect.formatargspec( args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations, formatvalue=lambda o: '=' + repr(o)) if name == '<lambda>': doc['name'] = name + ' lambda ' doc['argspec'] = doc['argspec'][1:-1] # remove parentheses else: argspec = getargspecfromtext(doc['docstring']) if argspec: doc['argspec'] = argspec # Many scipy and numpy docstrings begin with a function # signature on the first line. This ends up begin redundant # when we are using title and argspec to create the # rich text "Definition:" field. We'll carefully remove this # redundancy but only under a strict set of conditions: # Remove the starting charaters of the 'doc' portion *iff* # the non-whitespace characters on the first line # match *exactly* the combined function title # and argspec we determined above. signature = doc['name'] + doc['argspec'] docstring_blocks = doc['docstring'].split("\n\n") first_block = docstring_blocks[0].strip() if first_block == signature: doc['docstring'] = doc['docstring'].replace( signature, '', 1).lstrip() else: doc['argspec'] = '(...)' # Remove self from argspec argspec = doc['argspec'] doc['argspec'] = argspec.replace('(self)', '()').replace('(self, ', '(') return doc
instanxe = myClass() print(isfunction(instanxe.fu)) print(ismethod(instanxe.fu)) print( "\n We can also obtain the source code of a fucntion throught the ispect module \n" ) print(inspect.getsource(funcIntrospection)) print(inspect.getmodule(funcIntrospection)) print( "\n We can also get the comments preeceding a certain code from the function using isnpect.getcomment\n" ) print(inspect.getcomments(funcIntrospection)) print("\n Learning Signature object\n") print(dir(inspect.signature)) # print(type(inspect.signature)) print(inspect.signature(funcIntrospection)) sig = inspect.signature(funcIntrospection) print("") print(sig.parameters) print("") for param in inspect.signature(funcIntrospection).parameters.values(): print("Name:", param.name) print("Default:", param.default) print("Annotation:", param.annotation)
def _getdoc(object): """Get the doc string or comments for an object.""" result = inspect.getdoc(object) or inspect.getcomments(object) return result and re.sub('^ *\n', '', result.rstrip()) or ''
def describe_class(obj, module_class, module_name, constants): """ Describe the class object passed as argument, including its methods. """ class_name = obj.__name__ if class_name == 'object': return if 'GenBitmapButton' in class_name: print('GenBitmapButton') class_name = module_class.name + '.' + class_name docs = getdoc(obj) comments = getcomments(obj) obj_dict = obj.__dict__ klass = Class(class_name, obj) count = 0 for name in obj_dict: if name.startswith('_') and '__init__' not in name: continue if name in EXCLUDED_ATTRS: continue try: item = getattr(obj, name) except AttributeError: # Thanks to ReportLab for this funny exception... continue except ImportError: # This can come from the pseudo module in wx.lib.six message = "ImportError from '%s.%s'.\n Exception was: %s" % ( obj, name, format_traceback()) print(('\nWARNING: %s\n' % message)) continue if ismodule(item): continue if ismemberdescriptor(item) or isgetsetdescriptor(item): continue if isbuiltin(item): count += 1 elif ismethod(item) or isfunction(item) or ismethoddescriptor(item) or \ isinstance(item, types.MethodType): count += 1 describe_func(item, klass, module_name) elif isclass(item): count += 1 describe_class(item, klass, module_name, constants) else: name = class_name + '.' + name if isinstance(item, property): item_class = Property(name, item) klass.Add(item_class) item_module = getmodule(obj) if item_module and item_module.__name__ != module_name: item_class.is_redundant = True else: item_class = Attribute(name, type(item), item) klass.Add(item_class) if constants: item_class.is_redundant = name not in constants count += 1 klass.docs = docs klass.comments = comments klass_module = getmodule(obj) if klass_module and klass_module.__name__ != module_name: klass.is_redundant = True else: klass.inheritance_diagram = inheritance.InheritanceDiagram([obj], klass) module_class.Add(klass) try: source_code = getsource(obj) except (IOError, TypeError): source_code = '' if source_code: description = get_constructor(source_code) if '(' not in description and ':' in description: description = description[0:description.index(':')] klass.signature = description.strip() klass.number_lines = '%d' % len(source_code.split('\n'))
def gen_mod(mod, indent=0, cls=False, deep=False): children = [] imported = [] out = '' used = [] for pred in [ inspect.ismodule, isclassattr, inspect.isclass, inspect.isroutine, inspect.isbuiltin, None ]: # We want to output constants at the top if pred is None: _out = out out = '' for name, val in inspect.getmembers(mod, pred): if name.startswith('__') or name in used: # Discard these; they're useless in docs continue used.append(name) if inspect.ismodule(val) and deep is True: imported.append(val.__name__) children.append(gen_mod(val)) pass # A function in the toplevel of the module elif inspect.isbuiltin(val): out += "def %s(%s):\n '''%s'''\n pass\n\n" % ( name, proto_from_doc(val.__doc__), indent_doc(val.__doc__)) # A class elif inspect.isclass(val) and name != '__class__': class_name, (class_out, _) = gen_mod(val, indent + 1, True) out += "class %s:\n '''%s'''\n%s\n" % (class_name, val.__doc__, class_out) # A method in a class elif inspect.isroutine(val): proto = proto_from_doc(val.__doc__) if proto != "": proto = 'self, ' + proto else: proto = 'self' out += "def %s(%s):\n '''%s'''\n pass\n\n" % ( name, proto, indent_doc(val.__doc__)) # Regular ol' variables: in classes or constants in toplevel else: if inspect.isgetsetdescriptor( val) or inspect.ismemberdescriptor(val): doc = inspect.getdoc(val) else: doc = inspect.getcomments(val) s = 'None' if cls else repr(val) if s.startswith('<'): s = 'None' if doc: out += "'''%s'''\n%s = %s\n" % (doc, name, s) else: out += '%s = %s\n' % (name, s) if pred is None: out = out + '\n' + _out mod_name = mod.__name__ if inspect.isclass(mod): bases = ','.join(map(fullname, mod.__bases__)) if bases: mod_name += '(%s)' % bases if imported: out = 'from . import %s\n\n%s' % (', '.join(imported), out) out = '\n'.join([(' ' * indent) + line for line in out.splitlines()]) + '\n' return (mod_name, (out, children))
def get_object_comments(obj): return inspect.getcomments(obj)
def test_play_card_comment_check(): assert inspect.getcomments( play_card ) is not None, "Add comments before writing fuctions for better readability"
my_obj = MyClass() print(dir(my_obj.my_func)) print(inspect.isfunction(my_func)) print(inspect.ismethod(my_func)) print(inspect.ismethod(my_obj.my_func)) print(inspect.isfunction(my_obj.my_func)) print(inspect.isroutine(my_func)) print(inspect.isroutine(my_obj.my_func)) print(dir(my_func.__code__)) print(dir(my_func.__code__.co_stacksize)) print(inspect.getsource(my_func)) print(inspect.getmodule(print)) print(inspect.getmodule(my_func)) print(inspect.getcomments(my_func)) print(inspect.getcomments(print)) print(inspect.signature(my_func)) print(inspect.signature(my_func).parameters) sig = inspect.signature(my_func) for k, param in sig.parameters.items(): print(f'Name: {param.name}') print(f'Default: {param.default}') print(f'Annotation: {param.annotation}') print(f'Kind: {param.kind}') print('-----------------------')
def test_normal_func_comment_check(): assert inspect.getcomments( normal_func ) is not None, "Add comments before writing fuctions for better readability"
def _top_comments(self) -> Iterable[str]: for line in (inspect.getcomments(self._obj) or "").splitlines()[::-1]: yield line.strip()
def dumpComponentDocs(self, widgetsDir): widgetsDir = os.path.join(widgetsDir, 'components') if not os.path.exists(widgetsDir): os.mkdir(widgetsDir) imagesDir = os.path.join(widgetsDir, 'images') if not os.path.exists(imagesDir): os.mkdir(imagesDir) toc = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">' toc += '<html>\n<head><title>%s</title></head><body>\n' % 'PythonCard Components' toc += '<h1>PythonCard Components</h1>\n' componentsList = [] for w in self.components.itervalues(): if w.__class__.__name__.startswith(w.name[3:]): # document each widget name = w.__class__.__name__ objspec = w._spec doc = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">' doc += '<html>\n<head><title>%s</title></head><body>\n' % (name + ': PythonCard component') doc += '<h1>Component: %s</h1>' % name doc += '\n<img src="%s"><BR>\n' % ('images/' + name + '.png') doc += '\n<h2>Required Attributes</h2>\n' doc += '<table border="1">\n' doc += '<tr><td><b>Name<b></td><td><b>Default value</b></td></tr>\n' for a in getAttributesList(objspec.getRequiredAttributes()): doc += "<tr><td>%s</td><td>%s</td></tr>\n" % (a[0], a[1]) doc += '</table>' doc += '\n\n<h2>Optional Attributes</h2>\n' doc += '<table border="1">\n' doc += '<tr><td><b>Name<b></td><td><b>Default value</b></td></tr>\n' for a in getAttributesList(objspec.getOptionalAttributes()): doc += "<tr><td>%s</td><td>%s</td></tr>\n" % (a[0], a[1]) doc += '</table>' doc += '\n\n<h2>Events:</h2>\n' doc += '<table border="1">\n' for e in getEventsList(objspec): doc += "<tr><td>%s</td></tr>\n" % e doc += '</table>' doc += '\n\n<h2>Methods:</h2>\n' doc += '<table border="1">\n' td = '<td><b>%s</b></td>' * 4 tr = '<tr>' + td + '</tr>\n' doc += tr % ('method', 'args', 'doc string', 'comments') for e in getMethodsList(w): method = getattr(w, e) docstring = inspect.getdoc(method) if docstring is None: docstring = " " comments = inspect.getcomments(method) if comments is None: comments = " " #source = inspect.getcomments(method) argspec = inspect.getargspec(method) formattedargs = inspect.formatargspec(argspec[0], argspec[1], argspec[2], argspec[3]) doc += "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n" % \ (e, formattedargs, docstring, comments) doc += '</table>' # need to decide what we want to dump from the methods # we probably don't want to dump everything including # wxPython methods, so this is where we need to decide # on the case of the first letter of the method # whatever is done here should be the same thing used # to display methods in the shell # arg lists and tooltips (docstrings) will be used here too # write out the documentation for the component doc += '\n<hr><img src="http://sourceforge.net/sflogo.php?group_id=19015&type=1" width="88" height="31" border="0" alt="SourceForge Logo">' doc += '\n<p>Last updated: %s</p>' % time.strftime("%B %d, %Y") doc += '\n</body>\n</html>' filename = name + '.html' path = os.path.join(widgetsDir, filename) f = open(path, 'w') f.write(doc) f.close() # create an image using the actual component # on screen # comment this out once you have created the images # you want bmp = wx.EmptyBitmap(w.size[0], w.size[1]) memdc = wx.MemoryDC() memdc.SelectObject(bmp) dc = wx.WindowDC(w) memdc.BlitPointSize((0, 0), w.size, dc, (0, 0)) imgfilename = os.path.join(imagesDir, name + '.png') bmp.SaveFile(imgfilename, wx.BITMAP_TYPE_PNG) dc = None memdc.SelectObject(wx.NullBitmap) memdc = None bmp = None componentsList.append('<a href="%s">%s</a><br>\n' % (filename, name)) # now create the table of contents, index.html componentsList.sort() for c in componentsList: toc += c toc += '\n<hr><img src="http://sourceforge.net/sflogo.php?group_id=19015&type=1" width="88" height="31" border="0" alt="SourceForge Logo">' toc += '\n</body>\n</html>' filename = os.path.join(widgetsDir, 'index.html') f = open(filename, 'w') f.write(toc) f.close()
('StupidGit', mod.StupidGit)], 'class list') tree = inspect.getclasstree(map(lambda x: x[1], classes), 1) test(tree == [(mod.ParrotDroppings, ()), (mod.StupidGit, ()), [(mod.MalodorousPervert, (mod.StupidGit,)), [(mod.FesteringGob, (mod.MalodorousPervert, mod.ParrotDroppings)) ] ] ], 'class tree') functions = inspect.getmembers(mod, inspect.isfunction) test(functions == [('eggs', mod.eggs), ('spam', mod.spam)], 'function list') test(inspect.getdoc(mod) == 'A module docstring.', 'getdoc(mod)') test(inspect.getcomments(mod) == '# line 1\n', 'getcomments(mod)') test(inspect.getmodule(mod.StupidGit) == mod, 'getmodule(mod.StupidGit)') test(inspect.getfile(mod.StupidGit) == TESTFN, 'getfile(mod.StupidGit)') test(inspect.getsourcefile(mod.spam) == TESTFN, 'getsourcefile(mod.spam)') test(inspect.getsourcefile(git.abuse) == TESTFN, 'getsourcefile(git.abuse)') def sourcerange(top, bottom): lines = string.split(source, '\n') return string.join(lines[top-1:bottom], '\n') + '\n' test(inspect.getsource(git.abuse) == sourcerange(29, 39), 'getsource(git.abuse)') test(inspect.getsource(mod.StupidGit) == sourcerange(21, 46), 'getsource(mod.StupidGit)') test(inspect.getdoc(mod.StupidGit) == 'A longer,\n\nindented\n\ndocstring.', 'getdoc(mod.StupidGit)')
def __str__(self): comment = inspect.getcomments(self.obj) or "no comment" return repr(self.value + " : " + comment + " in " + self.obj.__module__ + "." + self.obj.__class__.__name__)
def test_getcomments(self): self.assertEqual(inspect.getcomments(mod), '# line 1\n') self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n')
data_fn=tio_doc_str, col_visible=False, width=MEDIUM_COL_WIDTH) ATTR_MODEL_GET_DOC = AttributeModel( 'inspect.getdoc', doc="The object's doc string cleaned up by inspect.getdoc()", data_fn=safe_data_fn(inspect.getdoc), col_visible=False, width=MEDIUM_COL_WIDTH) ATTR_MODEL_GET_COMMENTS = AttributeModel( 'inspect.getcomments', doc= "Comments above the object's definition is retrieved using inspect.getcomments()", data_fn=lambda (tree_item): inspect.getcomments(tree_item.obj), col_visible=False, width=MEDIUM_COL_WIDTH) ATTR_MODEL_GET_MODULE = AttributeModel( 'inspect.getmodule', doc="The object's module retrieved using inspect.module", data_fn=safe_data_fn(inspect.getmodule), col_visible=False, width=MEDIUM_COL_WIDTH) ATTR_MODEL_GET_FILE = AttributeModel( 'inspect.getfile', doc="The object's file retrieved using inspect.getfile", data_fn=safe_data_fn(inspect.getfile), col_visible=False,
def try_inspect(): thing = tester.Tester.do_tests_on_student print(inspect.getsourcefile(tester)) print(inspect.getsourcelines(thing)) print(inspect.getdoc(thing)) print(inspect.getcomments(thing))
class B(object): """""" def func1(self): print('B') # test4 def meth1(self): print('B') def _meth(self): print('B') @mix_in_class_attributes((B, ), protected=True, overwrite=False) @mix_in_functions((func1, func2)) # test1 # test2 class A(object): pass print('mro', inspect.getmro(A)) print('comments', inspect.getcomments(A.func1)) print('comments', inspect.getcomments(A.meth1)) print('dir', dir(A)) a = A() a.func1() a.func2() a.meth1() a._meth()
# getsource if 0: print inspect.getsource(func) # getsourcefile if 0: print inspect.getsourcefile(func) # getdoc if 0: print inspect.getdoc(func) # getcomments if 0: print inspect.getcomments(func) # getmodule if 0: print inspect.getmodule(func) # getmoduleinfo if 0: print inspect.getmoduleinfo("./test_inspect.py") # getclasstree if 0: print inspect.getclasstree([test]) def test_args(a, b, c, d=2): e = 1
def dumpBackgroundDocs(self, widgetsDir): w = self name = w.__class__.__name__ objspec = w._spec doc = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">' doc += '<html>\n<head><title>%s</title></head><body>\n' % (name + ': PythonCard Background') doc += '<h1>Background: %s</h1>' % name doc += '\n<img src="%s"><BR>\n' % ('images/' + name + '.png') doc += '\n<h2>Required Attributes</h2>\n' doc += '<table border="1">\n' doc += '<tr><td><b>Name<b></td><td><b>Default value</b></td></tr>\n' for a in getAttributesList(objspec.getRequiredAttributes()): doc += "<tr><td>%s</td><td>%s</td></tr>\n" % (a[0], a[1]) doc += '</table>' doc += '\n\n<h2>Optional Attributes</h2>\n' doc += '<table border="1">\n' doc += '<tr><td><b>Name<b></td><td><b>Default value</b></td></tr>\n' for a in getAttributesList(objspec.getOptionalAttributes()): doc += "<tr><td>%s</td><td>%s</td></tr>\n" % (a[0], a[1]) doc += '</table>' # KEA 2005-12-29 # Background spec still using default in spec.py so doesn't have # events defined like it should ## doc += '\n\n<h2>Events:</h2>\n' ## doc += '<table border="1">\n' ## for e in getEventsList(objspec): ## doc += "<tr><td>%s</td></tr>\n" % e ## doc += '</table>' doc += '\n\n<h2>Methods:</h2>\n' doc += '<table border="1">\n' td = '<td><b>%s</b></td>' * 4 tr = '<tr>' + td + '</tr>\n' doc += tr % ('method', 'args', 'doc string', 'comments') for e in getMethodsList(w): method = getattr(w, e) docstring = inspect.getdoc(method) if docstring is None: docstring = " " comments = inspect.getcomments(method) if comments is None: comments = " " #source = inspect.getcomments(method) argspec = inspect.getargspec(method) formattedargs = inspect.formatargspec(argspec[0], argspec[1], argspec[2], argspec[3]) doc += "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>\n" % \ (e, formattedargs, docstring, comments) doc += '</table>' # write out the documentation for the component doc += '\n<hr><img src="http://sourceforge.net/sflogo.php?group_id=19015&type=1" width="88" height="31" border="0" alt="SourceForge Logo">' doc += '\n<p>Last updated: %s</p>' % time.strftime("%B %d, %Y") doc += '\n</body>\n</html>' filename = name + '.html' path = os.path.join(widgetsDir, filename) f = open(path, 'w') f.write(doc) f.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- """Show the comment before a method. """ import inspect import example print inspect.getcomments(example)
# All Rights Reserved # # Permission to use, copy, modify, and distribute this software and # its documentation for any purpose and without fee is hereby # granted, provided that the above copyright notice appear in all # copies and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of Doug # Hellmann not be used in advertising or publicity pertaining to # distribution of the software without specific, written prior # permission. # # DOUG HELLMANN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN # NO EVENT SHALL DOUG HELLMANN BE LIABLE FOR ANY SPECIAL, INDIRECT OR # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # """Show the comment before a method. """ __version__ = "$Id$" #end_pymotw_header import inspect import example print inspect.getcomments(example.B.do_something)
def comments_by_endpoint(endpoint: str) -> str: x = application.app.view_functions[endpoint] return inspect.getcomments(x)
def _getComment(obj): '''return comment preceeding *obj*.''' try: return getcomments(obj) except: return ''
def getcomments(object): with InspectMock(): return inspect.getcomments(object)
#!/usr/bin/env python3 """Show the comment before a method. """ #end_pymotw_header import inspect import example print(inspect.getcomments(example))
def describe_func(obj, parent_class, module_name): """ Describe the function object passed as argument. If this is a method object, the second argument will be passed as True. """ try: name = obj.__name__ except AttributeError: # Funny comtypes... return if name.startswith('_') and '__init__' not in name: return name = parent_class.name + '.' + name docs = getdoc(obj) comments = getcomments(obj) if isfunction(obj): # in Py3 unbound methods have same type as functions. if isinstance(parent_class, Class): method = object_types.METHOD else: method = object_types.FUNCTION elif ismethod(obj): method = object_types.METHOD elif ismethoddescriptor(obj): method = object_types.METHOD_DESCRIPTOR if isinstance(obj, types.MethodType): method = object_types.INSTANCE_METHOD try: source_code = getsource(obj) except (IOError, TypeError): source_code = '' klass = Method(name, method) klass.docs = docs klass_module = getmodule(obj) if klass_module and klass_module.__name__ != module_name: klass.is_redundant = True if source_code: inspect_source(klass, obj, source_code) klass.number_lines = '%d' % len(source_code.split('\n')) if isinstance(obj, staticmethod): klass.method = method = object_types.STATIC_METHOD try: code = None if method in [ object_types.METHOD, object_types.METHOD_DESCRIPTOR, object_types.INSTANCE_METHOD ]: if isPython3(): code = obj.__func__.__code__ else: code = obj.im_func.func_code elif method == object_types.STATIC_METHOD: if isPython3(): code = obj.__func__.__code__ else: code = obj.im_func.func_code else: if isPython3(): code = obj.__code__ else: code = obj.func_code except AttributeError: code = None if code is not None: klass.firstlineno = '%d' % code.co_firstlineno parent_class.Add(klass)
def get_comments(self, obj): """Get ``obj``'s comments. """ return inspect.getcomments(obj)
""" # inspect - перегляд об'єктів часу виконання Модуль inspect містить додаткові функції, які допомагають отримати інформацію про об’єкти часу виконання (модулі, класи, методи, функції, об'єкти трасування, кадрів виконання і коду). """ import inspect # клас A class A(): pass print inspect.getmro(A) # кортеж з ієрархією базових класів print inspect.getmembers( A) # повертає список пар (ім'я, значення) членів об'єкта print inspect.getcomments(A) # коментар перед класом A #print inspect.getsource(A) # текст вихідного коду класу A print inspect.isclass(A) # чи A є класом? def f(a, b=0, *args, **kwargs): cf = inspect.currentframe() # об'єкт поточного кадру виконання #cf=sys._getframe() # або #cf.f_back # попередній кадр стеку (який викликав f) print cf.f_lineno, cf.f_back.f_lineno # поточний рядок коду і рядок, який викликав f print cf.f_locals # локальні імена f #print cf.f_back.f_code.co_filename # файл модуля, що викликав f print inspect.ismethod(f) # чи f є методом? print inspect.isfunction(f) # чи f є функцією?
source = '''# line 1 'A module docstring.' import sys, inspect # line 5 # line 7 def spam(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h): eggs(b + d, c + f) # line 11 def eggs(x, y): "A docstring." global fr, st fr = inspect.currentframe() st = inspect.stack() p = x q = y / 0 # line 20 class StupidGit: """A longer, indented docstring.""" # line 27 def abuse(self, a, b, c): """Another \tdocstring containing \ttabs \t """ self.argue(a, b, c) # line 40