def test_getclasses(self): classes = inspect.getmembers(mod, inspect.isclass) self.assertEqual(classes, [('FesteringGob', mod.FesteringGob), ('MalodorousPervert', mod.MalodorousPervert), ('ParrotDroppings', mod.ParrotDroppings), ('StupidGit', mod.StupidGit), ('Tit', mod.MalodorousPervert), ]) tree = inspect.getclasstree([cls[1] for cls in classes]) self.assertEqual(tree, [(mod.ParrotDroppings, ()), [(mod.FesteringGob, (mod.MalodorousPervert, mod.ParrotDroppings)) ], (mod.StupidGit, ()), [(mod.MalodorousPervert, (mod.StupidGit,)), [(mod.FesteringGob, (mod.MalodorousPervert, mod.ParrotDroppings)) ] ] ]) tree = inspect.getclasstree([cls[1] for cls in classes], True) self.assertEqual(tree, [(mod.ParrotDroppings, ()), (mod.StupidGit, ()), [(mod.MalodorousPervert, (mod.StupidGit,)), [(mod.FesteringGob, (mod.MalodorousPervert, mod.ParrotDroppings)) ] ] ])
def gmems(): """ This stuff is for Python 2.5 Documentation for inspection (Python 2.5) http://www.doughellmann.com/PyMOTW/inspect/ """ import inspect e87 = crm.E87() #from pprint import pprint #print inspect.getmembers(crm.E87()) print inspect.getclasstree([crm.E87])
def test_getclasses(self): classes = inspect.getmembers(mod, inspect.isclass) self.assertEqual( classes, [ ("FesteringGob", mod.FesteringGob), ("MalodorousPervert", mod.MalodorousPervert), ("ParrotDroppings", mod.ParrotDroppings), ("StupidGit", mod.StupidGit), ], ) tree = inspect.getclasstree([cls[1] for cls in classes], 1) self.assertEqual( tree, [ (object, ()), [ (mod.ParrotDroppings, (object,)), (mod.StupidGit, (object,)), [ (mod.MalodorousPervert, (mod.StupidGit,)), [(mod.FesteringGob, (mod.MalodorousPervert, mod.ParrotDroppings))], ], ], ], )
def getanc(results, cls): if not issubclass(cls, Control): return for p in [c[0] for c in inspect.getclasstree([cls], unique=True) if type(c) != list]: getanc(results, p) # Add the descendant class after the ancestor results.append(cls)
def _format_cls_doc(cls, full_name): "Formatted `cls` definition to show in documentation" parent_class = inspect.getclasstree([cls])[-1][0][1][0] name, args = _format_func_doc(cls, full_name) if parent_class != object: args += f' :: {doc_link(get_name(parent_class))}' return name, args
def generate_hierarchy_groups(*modules: types.ModuleType) -> Sequence[str]: """Returns a Graphviz-compatible list of grouped edges from type hierarchy. Args: *modules: Python modules to generate type hierarchies from. Returns: list of edges in the format `"x"->"y"`. Edges may contain additional attributes. e.g., `"x"->"y" [group="z"]` """ processed = set() edges = [] for module in modules: for _, cls in inspect.getmembers( module, lambda cls: inspect.isclass(cls) and cls is not type): nodes = inspect.getclasstree(cls.mro(), unique=True) nodes.pop(0) # remove the (object, ()) tuple. while nodes: node = nodes.pop(0) if type(node) is tuple: child, parents = node edges.extend( '"%s"->"%s" [group="%s"]' % (parent.__name__, child.__name__, module.__name__) for parent in parents if child.__name__ not in processed) processed.add(child.__name__) elif type(node) is list: nodes.extend(node) else: raise NotImplementedError() return edges
def _ensureCompatLoaded(): if not _versionsMap: def flattenClassTree(tree): root = tree[0][0] assert isinstance(root, types.TypeType), root yield root if len(tree) > 1: assert len(tree) == 2 rest = tree[1] assert isinstance(rest, types.ListType), rest for c in flattenClassTree(rest): yield c classes = [] regex = re.compile(r'^MxCompatibility[0-9a-z]*$') for name, clazz in inspect.getmembers(sys.modules[__name__], inspect.isclass): m = regex.match(name) if m: classes.append(clazz) previousVersion = None for clazz in flattenClassTree(inspect.getclasstree(classes)): if clazz == object: continue assert previousVersion is None or previousVersion < clazz.version() previousVersion = clazz.version() _versionsMap[previousVersion] = clazz()
def get_cls_doc(elt, full_name: str) -> str: "Class definition." parent_class = inspect.getclasstree([elt])[-1][0][1][0] doc = format_ft_def(elt, full_name) if parent_class != object: doc += f' :: {link_type(parent_class, include_bt=True)}' return doc
def _list_impl(proc_name: str, command_args: List[str]) -> int: # noqa: C901 # Grab the configuration so we can determine which modules to list from config = _find_and_load_config() parser = argparse.ArgumentParser( description="List all codemods available to run.", prog=f"{proc_name} list", ) _ = parser.parse_args(command_args) # Now, import each of the modules to determine their paths. codemods: List[str] = [] for module in config["modules"]: try: imported_module = importlib.import_module(module) except AttributeError: imported_module = None except ModuleNotFoundError: imported_module = None if not imported_module: print( f"Could not import {module}, cannot list codemods inside it", file=sys.stderr, ) continue # Grab the path, try to import all of the files inside of it. path = os.path.dirname(os.path.abspath(imported_module.__file__)) for filename in os.listdir(path): if not filename.endswith(".py"): continue try: potential_codemod = importlib.import_module( f"{module}.{filename[:-3]}") except AttributeError: continue except ModuleNotFoundError: continue for objname in dir(potential_codemod): try: obj = getattr(potential_codemod, objname) if not issubclass(obj, CodemodCommand): continue if inspect.isabstract(obj): continue # isabstract is broken for direct subclasses of ABC which # don't themselves define any abstract methods, so lets # check for that here. if any(cls[0] is ABC for cls in inspect.getclasstree([obj])): continue codemods.append( f"{filename[:-3]}.{obj.__name__} - {obj.DESCRIPTION}") except TypeError: continue print("\n".join(sorted(codemods))) return 0
def trace(this): def _trace_tree(iterable): def _trace_bases(iterable): name = _which_name[NAME_FULL] derived, bases = iterable cls_name = name(derived) bases_str = '' if bases: bases_str = ', '.join([name(base) for base in bases]) print("{0}({1})".format(cls_name, bases_str)) for item in iterable: trace = _trace_bases if isinstance(item, tuple) else _trace_tree trace(item) mro = getmro(this) tree = getclasstree(mro, unique=1) print('-'*79) print(this) print('') if ENABLE_DEFAULT: pprint(tree) print('') _trace_tree(tree)
def sort_by_class_tree(objs): """ Sorts a list of objects by their class tree. Each item in the list should inherit from a common base class. The list is returned ordered from the most specific to the least specific. """ # Since all objects must inherit from a common base class the list # returned by 'getclasstree' will be of length two:- # # The first element is a tuple of the form:- # # (CommonBaseClass, (HasTraits,)) # # The second element is a possibly nested list containing all of the # classes derived from 'CommonBaseClass'. hierarchy = getclasstree([type(obj) for obj in objs]) # Do an in-order traversal of the tree and return just the classes. # # This returns them ordered from least specific to most specific. classes = get_classes(hierarchy) # Note the reverse comparison (i.e., compare y with x). This is # because we want to return the classes ordered from the MOST # specfic to the least specific. objs.sort(key=lambda x: classes.index(type(x)), reverse=True) return
def _list_impl(proc_name: str, command_args: List[str]) -> int: # noqa: C901 # Grab the configuration so we can determine which modules to list from config = _find_and_load_config(proc_name) parser = argparse.ArgumentParser( description="List all codemods available to run.", prog=f"{proc_name} list", fromfile_prefix_chars="@", ) _ = parser.parse_args(command_args) # Now, import each of the modules to determine their paths. codemods: Dict[Type[CodemodCommand], str] = {} for module in config["modules"]: try: imported_module = importlib.import_module(module) except AttributeError: imported_module = None except ModuleNotFoundError: imported_module = None if not imported_module: print( f"Could not import {module}, cannot list codemods inside it", file=sys.stderr, ) continue # Grab the path, try to import all of the files inside of it. path = os.path.dirname(os.path.abspath(imported_module.__file__)) for name, imported_module in _recursive_find(path, module): for objname in dir(imported_module): try: obj = getattr(imported_module, objname) if not issubclass(obj, CodemodCommand): continue if inspect.isabstract(obj): continue # isabstract is broken for direct subclasses of ABC which # don't themselves define any abstract methods, so lets # check for that here. if any(cls[0] is ABC for cls in inspect.getclasstree([obj])): continue # Deduplicate any codemods that were referenced in other # codemods. Always take the shortest name. fullname = f"{name}.{obj.__name__}" if obj in codemods: if len(fullname) < len(codemods[obj]): codemods[obj] = fullname else: codemods[obj] = fullname except TypeError: continue printable_codemods: List[str] = [ f"{name} - {obj.DESCRIPTION}" for obj, name in codemods.items() ] print("\n".join(sorted(printable_codemods))) return 0
def getStorageObject(implementation, the_element): """ returns the storage object by the implementation attribute and the given element.""" module=__import__(implementation) for i in implementation.split(".")[1:]: module = getattr(module, i) if module: cls=None for key in module.__dict__.keys(): import inspect if inspect.isclass(getattr(module, key)) and inspect.getclasstree([getattr(module, key)], True)[0][0] == Storage: cls=getattr(module, key) break if cls: try: inst=object.__new__(cls) Storage.log.debug("class is %s" %(cls)) inst.__init__(element=the_element) connname=inst.getConnectionName() if not StorageConnections.has_key(connname): Storage.log.debug("Creating new storage connection %s %s" %(connname, StorageConnections.keys())) StorageConnections[connname]=inst return inst else: Storage.log.debug("Returning already established storage connection %s" %(connname)) return StorageConnections[connname] except: import traceback traceback.print_exc() raise IncompatibleObjectException(cls, Storage) else: raise IncompatibleObjectException(getattr(module, key), Storage) else: raise ModuleNotFoundException(implementation)
def IsChildOf(lc, rc): tree = inspect.getclasstree([lc]) clsmap = tree[0] if clsmap[0] == rc: return True if not clsmap[1]: return False return Class.IsChildOf(clsmap[0], rc)
def _meta_new(mcs, cls_or_name, bases=None, dct=None): if inspect.isclass(cls_or_name): name = cls_or_name.__name__ bases = inspect.getclasstree((cls_or_name,))[-1][0][1] # Respect the class's metaclass return type(mcs).__new__(mcs, name, bases, dict(cls_or_name.__dict__)) else: # This allows subclasses of cls to be constructed normally... return type(mcs).__new__(mcs, cls_or_name, bases, dct)
def create_inheritance(self): for klass, representation in self.klasses.iteritems(): direct_ancestors = inspect.getclasstree([klass])[-1][0][1] for i, ancestor in enumerate(direct_ancestors): if ancestor in self.klasses: Inheritance.objects.create( parent=self.klasses[ancestor], child=representation, order=i )
def _create_module_classes_content(self, module, name: str, classes: list) -> str: contents = [ self._formattree( inspect.getclasstree([value for key, value in classes], 1), module, name, [item[0] for item in classes]) ] for key, value in classes: contents.append(self.__rule) contents.append(self.document(value, key, name, 2)) return self.__newline.join(contents)
def __store_algorithms_for_group(self, group, adapter, has_sub_algorithms): """ For the group passed as parameter do the following: If it has sub-algorithms, get the list of them, add sub-algorithm references into the DB with all the required fields. If it is not a GroupAdapter add a single algorithm into the DB with an empty identifier. """ if has_sub_algorithms: algos = adapter.get_algorithms_dictionary() for algo_ident in algos: in_params = adapter.get_input_for_algorithm(algo_ident) req_type, param_name, flt = self.__get_required_input(in_params) outputs = adapter.get_output_for_algorithm(algo_ident) algo_description = "" if self.__is_matlab_parent(inspect.getclasstree([adapter.__class__])): root_folder = adapter.get_matlab_file_root() file_name = adapter.get_matlab_file(algo_ident) if file_name: algo_description = self.extract_matlab_doc_string(os.path.join(root_folder, file_name)) algorithm = dao.get_algorithm_by_group(group.id, algo_ident) if algorithm is None: #Create new algorithm = model.Algorithm(group.id, algo_ident, algos[algo_ident][ATT_NAME], req_type, param_name, str(outputs), flt, description=algo_description) else: #Edit previous algorithm.name = algos[algo_ident][ATT_NAME] algorithm.required_datatype = req_type algorithm.parameter_name = param_name algorithm.outputlist = str(outputs) algorithm.datatype_filter = flt algorithm.description = algo_description dao.store_entity(algorithm) else: input_tree = adapter.get_input_tree() req_type, param_name, flt = self.__get_required_input(input_tree) outputs = str(adapter.get_output()) algorithm = dao.get_algorithm_by_group(group.id, None) if hasattr(adapter, '_ui_name'): algo_name = getattr(adapter, '_ui_name') else: algo_name = adapter.__class__.__name__ if algorithm is None: #Create new algorithm = model.Algorithm(group.id, None, algo_name, req_type, param_name, outputs, flt) else: #Edit previous algorithm.name = algo_name algorithm.required_datatype = req_type algorithm.parameter_name = param_name algorithm.outputlist = str(outputs) algorithm.datatype_filter = flt dao.store_entity(algorithm)
def create_inheritance(self): print "" print t.red("Inheritance") for klass, representation in self.klasses.iteritems(): print "" print t.green(representation.__unicode__()), direct_ancestors = inspect.getclasstree([klass])[-1][0][1] for i, ancestor in enumerate(direct_ancestors): if ancestor in self.klasses: print ".", Inheritance.objects.create(parent=self.klasses[ancestor], child=representation, order=i) print ""
def PYB11getBaseClasses(klass): stuff = inspect.getclasstree(inspect.getmro(klass), unique=True) def flatten(s, result): if type(s) is list: for val in s: s = flatten(val, result) else: result.append(s) flatstuff = [] flatten(stuff, flatstuff) result = { k[0] : k[1] for k in flatstuff } return result
def _printClassTree(cls): def _printTree(data, level): if isinstance(data, tuple): level += 1 for d in data: _printTree(d, level) else: print data print cls tree = inspect.getclasstree(cls) print tree _printTree(tree)
def order_classes(classes): classes = list(classes) ordered = list(flatten(inspect.getclasstree(classes))) ordered.reverse() for cls in list(ordered): if cls not in classes or ordered.count(cls) > 1: ordered.remove(cls) ordered.reverse() return ordered
def objBaseTree(obj): """ Obtain the base-class tree of an object. Input obj - object Output tree - class tree """ import inspect tree = inspect.getclasstree(inspect.getmro(obj.__class__)) return tree
def list_plugin_types(request_handler, plugin_name, format=None): if format is None: format = 'list' types = plugin_registry.get_types(plugin_name=plugin_name) if format == 'list': return {'types': [t.uri for t in types]} elif format == 'tree': cls_tree = inspect.getclasstree([t for t in types]) return _list_tree_to_dict_tree( cls_tree) # TODO use better JSON tree representation else: raise ValueError("Unrecognized format: %r" % format)
def create_inheritance(self): print '' print t.red('Inheritance') for klass, representation in self.klasses.iteritems(): print '' print t.green(representation.__unicode__()), direct_ancestors = inspect.getclasstree([klass])[-1][0][1] for i, ancestor in enumerate(direct_ancestors): if ancestor in self.klasses: print '.', Inheritance.objects.create(parent=self.klasses[ancestor], child=representation, order=i) print ''
def list_plugin_types(request_handler, plugin_name, format=None): if format is None: format = 'list' types = plugin_registry.get_types(plugin_name=plugin_name) if format == 'list': return { 'types': [t.uri for t in types] } elif format == 'tree': cls_tree = inspect.getclasstree([t for t in types]) return _list_tree_to_dict_tree(cls_tree) # TODO use better JSON tree representation else: raise ValueError("Unrecognized format: %r" % format)
def genclassrelations(clses): '''对clses的所有类,取得其上游所有类,以继承关系tuple list返回''' dd=set() def processtree(t): for i in t: if type(i) is tuple: c,bases=i dd.update({(c,b) for b in bases}) else: processtree(i) for c in clses: processtree( inspect.getclasstree(inspect.getmro(c),True) ) return dd
def __create_instance(self, category_key, class_ref, init_parameter=None): """ Validate Class reference. Return None of Algorithm instance, from class reference. """ if self.matlab_executable: return model.AlgorithmGroup(class_ref.__module__, class_ref.__name__, category_key, init_parameter=init_parameter, last_introspection_check=datetime.datetime.now()) else: if self.__is_matlab_parent(inspect.getclasstree([class_ref])): self.logger.debug("Skip Adapter because MATLAB is not found:" + str(class_ref)) return None else: return model.AlgorithmGroup(class_ref.__module__, class_ref.__name__, category_key, init_parameter=init_parameter, last_introspection_check=datetime.datetime.now())
def create_inheritance(self): print('') print(t.red('Inheritance')) for klass, representation in self.klasses.items(): print('') print(t.green(representation.__str__()), end=' ') direct_ancestors = inspect.getclasstree([klass])[-1][0][1] for i, ancestor in enumerate(direct_ancestors): if ancestor in self.klasses: print('.', end=' ') Inheritance.objects.create( parent=self.klasses[ancestor], child=representation, order=i ) print('')
def __get_supertype_names(clazz): result = [] classtree = inspect.getclasstree([clazz]) def get_supertypes_r(node): if isinstance(node, list) or isinstance(node, tuple): for child in node: get_supertypes_r(child) elif isinstance(node, type): name = node.__name__ self_name = clazz.__name__ if name != self_name and name not in result: result.append(name) get_supertypes_r(classtree) return result
def getClassInfo(_class): parentClassName = inspect.getclasstree([_class])[0][0].__name__ writeDefinition("class %s(%s):\n" % (_class.__name__, parentClassName)) writeDefinition("\n") indent() for memberName in _class.__dict__: member = getattr(_class, memberName) if inspect.isbuiltin(member): getMemberInfo(member, isBuiltIn=True) continue if inspect.ismethod(member): getMemberInfo(member) continue if inspect.isfunction(member): getMemberInfo(member) continue if inspect.isroutine(member): getMemberInfo(member, isBuiltIn=True) continue if inspect.istraceback(member): getMemberInfo(member) continue if inspect.isframe(member): getMemberInfo(member) continue if inspect.iscode(member): getMemberInfo(member) continue if inspect.ismethoddescriptor(member): getMemberInfo(member) continue if inspect.isdatadescriptor(member): getMemberInfo(member) continue if inspect.isgetsetdescriptor(member): getMemberInfo(member) continue if inspect.ismemberdescriptor(member): getMemberInfo(member) dedent()
def get_class_info(self, cls): """Resolves the signature, docstring and members of a class""" base = inspect.getclasstree([cls])[0][0].__name__ signature = "\nclass {0}({1}):".format(cls.__name__, base) self.write(signature) self.indent() doc = '"""{0}"""'.format(cls.__doc__) self.write(doc) for member_name, member in cls.__dict__.items(): if member_name.startswith("__"): continue if not member: logger.info("Failed to resolve {0}".format(member_name)) else: self.get_info(member) self.dedent()
def get_class_info(self, cls): """Resolves the signature, docstring and members of a class""" base = inspect.getclasstree([cls])[0][0].__name__ signature = '\nclass %s(%s):' % (cls.__name__, base) self.write(signature) self.indent() doc = '"""%s"""' % cls.__doc__ self.write(doc) for member_name, member in cls.__dict__.items(): if member_name.startswith('__'): continue if not member: logger.info('Failed to resolve %s', member_name) else: self.get_info(member) self.dedent()
def find_interface(interface, iface, do_inspect=True): """ Look for an interface in iface's class hierarchy. Return boolean value. """ if do_inspect: class_tree = inspect.getclasstree([iface, ]) else: class_tree = iface for item in class_tree: try: (typ, sub_tree) = item except TypeError: return False except ValueError: (typ, sub_tree) = item[0] if (interface.__name__ == typ.__name__) \ or find_interface(interface, sub_tree, do_inspect=False) : return True return False
def classify(klass, obj, name=None, mod=None, *ignored): if not inspect.isclass(obj): raise Exception mro = list(reversed(inspect.getmro(obj))) klass.update({ 'name': obj.__name__, 'docstring': pydoc.getdoc(obj), 'ancestors': [k.__name__ for k in mro], 'parents': inspect.getclasstree([obj])[-1][0][1] }) def get_attrs(obj): all_attrs = filter(lambda data: pydoc.visiblename(data[0], obj=obj), pydoc.classify_class_attrs(obj)) return filter(lambda data: data[2] == obj, all_attrs) for cls in mro: if cls is __builtin__.object: continue attrs = get_attrs(cls) ## ATTRIBUTES for attribute in build_attributes( filter(lambda t: t[1] == 'data', attrs), obj): name = attribute.pop('name') klass['attributes'][name].append(attribute) ## METHODS is_method = lambda t: (t[1] == 'method' or t[1] == 'class method' or t[ 1] == 'static method') for method in build_methods(filter(is_method, attrs)): name = method.pop('name') klass['methods'][name].append(method) # descriptors = filter(lambda t: t[1] == 'data descriptor', attrs) return klass
def find_interface(interface, iface, do_inspect=True): """ Look for an interface in iface's class hierarchy. Return boolean value. """ if do_inspect: class_tree = inspect.getclasstree([ iface, ]) else: class_tree = iface for item in class_tree: try: (typ, sub_tree) = item except TypeError: return False except ValueError: (typ, sub_tree) = item[0] if (interface.__name__ == typ.__name__) \ or find_interface(interface, sub_tree, do_inspect=False) : return True return False
def sort_by_class_tree(objs): """ Sorts a list of objects by their class tree. Each item in the list should inherit from a common base class. The list is returned ordered from the most specific to the least specific. """ # Since all objects must inherit from a common base class the list # returned by 'getclasstree' will be of length two:- # # The first element is a tuple of the form:- # # (CommonBaseClass, (HasTraits,)) # # The second element is a possibly nested list containing all of the # classes derived from 'CommonBaseClass'. hierarchy = getclasstree([type(obj) for obj in objs]) # Do an in-order traversal of the tree and return just the classes. # # This returns them ordered from least specific to most specific. classes = get_classes(hierarchy) # Now we can actually do the sort! def by_class_tree(x, y): ix = classes.index(type(x)) iy = classes.index(type(y)) # Note the reverse comparison (i.e., compare y with x). This is # because we want to return the classes ordered from the MOST # specfic to the least specific. return cmp(iy, ix) objs.sort(by_class_tree) return
def sortClassesByTree(classes: List[type]) -> List[type]: """ Sort classes according to their inheritance tree Args: classes: a list of classes Returns: the list of classes, sorted by inheritance """ assert all(isinstance(cls, type) for cls in classes) seen = set() coll = [] later = [] def walk(tree): for entry in tree: if isinstance(entry, tuple): cls, bases = entry if cls == object: continue if bases[0] != object and bases[0] not in seen: later.append(cls) continue coll.append(cls) seen.add(cls) elif isinstance(entry, list): walk(entry) else: raise ValueError(f"Got {entry}") walk(inspect.getclasstree(classes)) coll.extend(later) assert all(isinstance(cls, type) for cls in coll) return coll
def classtree(cls, namespace): ''' Prints classtree from inspect.getclasstree in intuitive manner ''' import inspect classes = [] names = namespace.get('__all__', namespace) for name in sorted(names): value = namespace[name] if isinstance(value, types.TypeType): classes.append(value) def tree(deps, start=''): 'Prints tree of classes inheritance' walk = (u'│ ', u' ') turn = (u'├───', u'└───') for i in range(len(deps)): dep = deps[i] tail = tuple not in set(type(e) for e in deps[i+1:]) if isinstance(dep, list): tree(dep, start + walk[tail]) elif isinstance(dep, tuple): print start + turn[tail] + dep[0].__name__ tree(inspect.getclasstree(classes))
def __create_instance(self, category_key, class_ref, init_parameter=None): """ Validate Class reference. Return None of Algorithm instance, from class reference. """ if self.matlab_executable: return model.AlgorithmGroup( class_ref.__module__, class_ref.__name__, category_key, init_parameter=init_parameter, last_introspection_check=datetime.datetime.now()) else: if self.__is_matlab_parent(inspect.getclasstree([class_ref])): self.logger.debug("Skip Adapter because MATLAB is not found:" + str(class_ref)) return None else: return model.AlgorithmGroup( class_ref.__module__, class_ref.__name__, category_key, init_parameter=init_parameter, last_introspection_check=datetime.datetime.now())
from bokeh.model import Model from bokeh.util.warnings import BokehDeprecationWarning dest_dir = sys.argv[1] classes = [ member for name, member in inspect.getmembers(models) if inspect.isclass(member) ] model_class = next(klass for klass in classes if klass.__name__ == 'Model') # getclasstree returns a list which contains [ (class, parentClass), [(subClassOfClass, class), ...]] # where the subclass list is omitted if there are no subclasses. # If you say unique=True then mixins will be registered as leaves so don't use unique=True, # and expect to have duplicates in the result of leaves() all_tree = inspect.getclasstree(classes, unique=False) def leaves(tree, underneath): if len(tree) == 0: return [] elif len(tree) > 1 and isinstance(tree[1], list): subs = tree[1] if underneath is None or tree[0][0] != underneath: return leaves(subs, underneath) + leaves(tree[2:], underneath) else: # underneath=None to return all leaves from here out return leaves(subs, underneath=None) else: leaf = tree[0] tail = tree[1:]
def docmodule(self, object, name=None, mod=None, *ignored): """Produce HTML5 documentation for a module object.""" level = 1 # FIXME: use passed level in the future components = {} # where we're storing all components to be output name = object.__name__ # ignore the passed-in name. not passed in anyways? try: all = object.__all__ except AttributeError: all = None parts = name.split('.') links = [] for i in range(len(parts) - 1): links.append('<a href="%s">%s</a>' % (self.url('.'.join(parts[:i + 1])), parts[i])) head_link = '.'.join(links + parts[-1:]) try: path = inspect.getabsfile(object) if self.local: url = path if sys.platform == 'win32': # in case i want to give this to the python project import nturl2path url = nturl2path.pathname2url(path) components[ 'fileref'] = '<a class="file-reference" href="file:%s">%s</a>' % ( url, path) else: components[ 'fileref'] = '<span class="file-reference">%s</span>' % path except TypeError: components[ 'fileref'] = '<span class="file-reference builtin">(built-in)</span>' components['fileref'] = '' # TODO remove fileref info = [] if hasattr(object, '__version__'): version = pydoc._binstr(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(pydoc._binstr(object.__date__))) # build the main heading if info: components['head'] = self.heading( level + 1, '%s (<span class="info">%s)' % (head_link, ', '.join(info))) else: # heading which is a linked representation of the module "address" components['head'] = self.heading(level + 1, head_link) # get the official url of object, if any docloc = self.getdocloc(object) if docloc is not None: components[ 'docloc'] = '<a class="official-docs" href="%s" target="_blank" rel="noreferrer noopener">Module Docs</a>' % docloc else: components['docloc'] = '' # collect modules, classes, functions and data in `object` modules = inspect.getmembers(object, inspect.ismodule) classes, cdict = [], {} for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if pydoc.visiblename(key, all, object): classes.append((key, value)) cdict[key] = cdict[value] = '#' + \ key # key used as URL fragment for key, value in classes: for base in value.__bases__: key, modname = base.__name__, base.__module__ module = sys.modules.get(modname) if modname != name and module and hasattr(module, key): if getattr(module, key) is base: if not key in cdict: cdict[key] = cdict[base] = self.url( modname ) + '#' + key # key used as URL fragment funcs, fdict = [], {} for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if pydoc.visiblename(key, all, object): funcs.append((key, value)) fdict[key] = '#-' + key if inspect.isfunction(value): fdict[value] = fdict[key] data = [] for key, value in inspect.getmembers(object, pydoc.isdata): if pydoc.visiblename(key, all, object): data.append((key, value)) # build documentation for the thing passed in components['doc'] = self.getdoc(object) if hasattr(object, '__path__'): modpkgs = [] for importer, modname, ispkg in pkgutil.iter_modules( object.__path__): modpkgs.append((modname, name, ispkg, 0)) modpkgs.sort() components['modules'] = self.heading( level + 2, 'Package Contents') + self.listing( modpkgs, formatter=self.modpkglink) elif modules: components['modules'] = self.heading( level + 2, 'Modules') + self.listing( [module for _, module in modules], formatter=self.modulelink) if classes: classlist = [cls for _, cls in classes] classtree = self.formattree(inspect.getclasstree(classlist, 1), name) classdocs = [] for key, value in classes: classdocs.append(self.document(value, key, name, fdict, cdict)) components['classes'] = self.heading(level + 2, 'Classes') components['classes'] += classtree components['classes'] += '<dl class="classes">' components['classes'] += '\n'.join(classdocs) components['classes'] += '</dl>' if funcs: docs = [] for key, value in funcs: docs.append(self.document(value, key, name, fdict, cdict)) components['funcs'] = self.heading(level + 2, 'Functions') components['funcs'] += '<dl class="functions">' components['funcs'] += '\n'.join(docs) components['funcs'] += '</dl>' if data: docs = [] for key, value in data: docs.append(self.document(value, key)) components['data'] = self.heading(level + 2, 'Data') components['data'] += '<dl class="data">' components['data'] += '\n'.join(docs) components['data'] += '</dl>' if hasattr(object, '__author__'): components['author'] = self.heading( level + 2, 'Author') + pydoc._binstr(object.__author__) if hasattr(object, '__credits__'): components['credits'] = self.geadubg( level + 2, 'Credits') + pydoc._binstr(object.__credits__) result = '%(head)s %(docloc)s' % components # result = '%(head)s %(fileref)s %(docloc)s' % components # TODO fileref disabled result += '<div class="module">' % components result += ' <div class="docstring">%(doc)s</div>' % components if 'modules' in components: result += ' <div class="modules">%(modules)s</div>' % components if 'classes' in components: result += ' <div class="classes">%(classes)s</div>' % components if 'funcs' in components: result += ' <div class="functions">%(funcs)s</div>' % components if 'author' in components: result += '<div class="author">%(author)s</div>' % components if 'credits' in components: result += '<div class="credits">%(credits)s</div>' % components result += '</div>' return result
#!/usr/bin/env python3 """ """ #end_pymotw_header import inspect import example class C(example.B): pass class D(C, example.A): pass def print_class_tree(tree, indent=-1): if isinstance(tree, list): for node in tree: print_class_tree(node, indent + 1) else: print(' ' * indent, tree[0].__name__) return if __name__ == '__main__': print('A, B, C, D:') print_class_tree(inspect.getclasstree([example.A, example.B, C, D]))
def docmodule(self, obj, name=None, mod=None, package_context=None, *ignored): """Produce HTML documentation for a module object.""" name = obj.__name__ # ignore the passed-in name parts = name.split('.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % ('.'.join(parts[:i+1]), parts[i])) linked_name = '.'.join(links + parts[-1:]) head = '<big><big><strong>{0}</strong></big></big>'.format(linked_name) try: path = inspect.getabsfile(obj) url = path if sys.platform == 'win32': import nturl2path url = nturl2path.pathname2url(path) fake_link = '<a href="file:{0}">{1}</a>'.format(url, path) except TypeError: fake_link = '(built-in)' info = [] if hasattr(obj, '__version__'): version = str(obj.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = version[11:-1].strip() info.append('version %s' % self.escape(version)) if hasattr(obj, '__date__'): info.append(self.escape(str(obj.__date__))) if info: head += ' ({0})'.format(', '.join(info)) result = self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + fake_link) modules = inspect.getmembers(obj, inspect.ismodule) classes, cdict = [], {} for key, value in inspect.getmembers(obj, inspect.isclass): if (inspect.getmodule(value) or obj) is obj: classes.append((key, value)) cdict[key] = cdict[value] = '#' + key for key, value in classes: for base in value.__bases__: key, modname = base.__name__, base.__module__ module = sys.modules.get(modname) if modname != name and module and hasattr(module, key): if getattr(module, key) is base: if key not in cdict: cdict[key] = cdict[base] = modname + '.html#' + key funcs, fdict = [], {} for key, value in inspect.getmembers(obj, inspect.isroutine): if inspect.isbuiltin(value) or inspect.getmodule(value) is obj: funcs.append((key, value)) fdict[key] = '#-' + key if inspect.isfunction(value): fdict[value] = fdict[key] data = [] for key, value in inspect.getmembers(obj, pydoc.isdata): if key not in ['__builtins__', '__doc__']: data.append((key, value)) doc = self.markup(pydoc.getdoc(obj), self.preformat, fdict, cdict) doc = doc and '<tt>%s</tt>' % doc result += '<p>{0}</p>\n'.format(doc) package_context.clean(classes, obj) package_context.clean(funcs, obj) package_context.clean(data, obj) if hasattr(obj, '__path__'): modpkgs = [] modnames = [] for file in os.listdir(obj.__path__[0]): path = os.path.join(obj.__path__[0], file) modname = inspect.getmodulename(file) if modname and modname not in modnames: modpkgs.append((modname, name, 0, 0)) modnames.append(modname) elif pydoc.ispackage(path): modpkgs.append((file, name, 1, 0)) modpkgs.sort() contents = self.multicolumn(modpkgs, self.modpkglink) ## result = result + self.bigsection( ## 'Package Contents', '#ffffff', '#aa55cc', contents) result = result + self.module_section(obj, package_context) elif modules: contents = self.multicolumn( modules, lambda a: self.modulelink(a[1]) ) result = result + self.bigsection( 'Modules', '#fffff', '#aa55cc', contents) if classes: class_list = map(lambda a: a[1], classes) contents = [ self.formattree(inspect.getclasstree(class_list, 1), name)] for key, value in classes: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Classes', '#ffffff', '#ee77aa', ''.join(contents) ) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Functions', '#ffffff', '#eeaa77', ''.join(contents) ) if data: contents = [] for key, value in data: try: contents.append(self.document(value, key)) except Exception: pass result = result + self.bigsection( 'Data', '#ffffff', '#55aa55', '<br>\n'.join(contents) ) if hasattr(obj, '__author__'): contents = self.markup(str(obj.__author__), self.preformat) result = result + self.bigsection( 'Author', '#ffffff', '#7799ee', contents) if hasattr(obj, '__credits__'): contents = self.markup(str(obj.__credits__), self.preformat) result = result + self.bigsection( 'Credits', '#ffffff', '#7799ee', contents) return result
def get_super_classes(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type]
def docmodule(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a module object.""" name = object.__name__ # ignore the passed-in name try: all = object.__all__ except AttributeError: all = None parts = split(name, '.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % (join(parts[:i+1], '.'), parts[i])) linkedname = join(links + parts[-1:], '.') head = '<big><big><strong>%s</strong></big></big>' % linkedname try: path = inspect.getabsfile(object) url = path if sys.platform == 'win32': import nturl2path url = nturl2path.pathname2url(path) # modified filelink = self.filelink(url, path) # end modified except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = strip(version[11:-1]) info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % join(info, ', ') docloc = self.getdocloc(object) if docloc is not None: docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals() else: docloc = '' result = self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink + docloc) modules = inspect.getmembers(object, inspect.ismodule) classes, cdict = [], {} for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if visiblename(key, all): classes.append((key, value)) cdict[key] = cdict[value] = '#' + key for key, value in classes: for base in value.__bases__: key, modname = base.__name__, base.__module__ module = sys.modules.get(modname) if modname != name and module and hasattr(module, key): if getattr(module, key) is base: if not key in cdict: cdict[key] = cdict[base] = modname + '.html#' + key funcs, fdict = [], {} for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if visiblename(key, all): funcs.append((key, value)) fdict[key] = '#-' + key if inspect.isfunction(value): fdict[value] = fdict[key] data = [] for key, value in inspect.getmembers(object, isdata): if visiblename(key, all): data.append((key, value)) doc = self.markup(getdoc(object), self.preformat, fdict, cdict) doc = doc and '<tt>%s</tt>' % doc result = result + '<p>%s</p>\n' % doc if hasattr(object, '__path__'): modpkgs = [] for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): modpkgs.append((modname, name, ispkg, 0)) modpkgs.sort() contents = self.multicolumn(modpkgs, self.modpkglink) result = result + self.bigsection( 'Package Contents', '#ffffff', '#aa55cc', contents) elif modules: contents = self.multicolumn( modules, lambda (key, value), s=self: s.modulelink(value)) result = result + self.bigsection( 'Modules', '#fffff', '#aa55cc', contents) if classes: classlist = map(lambda (key, value): value, classes) contents = [ self.formattree(inspect.getclasstree(classlist, 1), name)] for key, value in classes: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Classes', '#ffffff', '#ee77aa', join(contents)) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Functions', '#ffffff', '#eeaa77', join(contents)) if data: contents = [] for key, value in data: contents.append(self.document(value, key)) result = result + self.bigsection( 'Data', '#ffffff', '#55aa55', join(contents, '<br>\n')) if hasattr(object, '__author__'): contents = self.markup(str(object.__author__), self.preformat) result = result + self.bigsection( 'Author', '#ffffff', '#7799ee', contents) if hasattr(object, '__credits__'): contents = self.markup(str(object.__credits__), self.preformat) result = result + self.bigsection( 'Credits', '#ffffff', '#7799ee', contents) return result
istest(inspect.ismethod, 'git.argue') istest(inspect.ismodule, 'mod') istest(inspect.istraceback, 'tb') import __builtin__ istest(inspect.isdatadescriptor, '__builtin__.file.closed') istest(inspect.isdatadescriptor, '__builtin__.file.softspace') test(inspect.isroutine(mod.spam), 'isroutine(mod.spam)') test(inspect.isroutine([].count), 'isroutine([].count)') classes = inspect.getmembers(mod, inspect.isclass) test(classes == [('FesteringGob', mod.FesteringGob), ('MalodorousPervert', mod.MalodorousPervert), ('ParrotDroppings', mod.ParrotDroppings), ('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)')
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # """ """ __version__ = "$Id$" #end_pymotw_header import inspect import example class C(example.B): pass class D(C, example.A): pass def print_class_tree(tree, indent=-1): if isinstance(tree, list): for node in tree: print_class_tree(node, indent+1) else: print ' ' * indent, tree[0].__name__ return if __name__ == '__main__': print 'A, B, C, D:' print_class_tree(inspect.getclasstree([example.A, example.B, C, D]))
# 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. # """ """ __version__ = "$Id$" #end_pymotw_header import inspect import example from inspect_getclasstree import * print_class_tree(inspect.getclasstree([example.A, example.B, C, D], unique=True, ))
def _what(obj): """ Internal call to abstract out the wrapper. """ return inspect.getclasstree(inspect.getmro(obj))
from bokeh.model import Model import bokeh.models as models from bokeh.core.json_encoder import serialize_json dest_dir = sys.argv[1] classes = [member for name, member in inspect.getmembers(models) if inspect.isclass(member)] model_class = next(klass for klass in classes if klass.__name__ == 'Model') widget_class = next(klass for klass in classes if klass.__name__ == 'Widget') # getclasstree returns a list which contains [ (class, parentClass), [(subClassOfClass, class), ...]] # where the subclass list is omitted if there are no subclasses. # If you say unique=True then mixins will be registered as leaves so don't use unique=True, # and expect to have duplicates in the result of leaves() all_tree = inspect.getclasstree(classes, unique=False) def leaves(tree, underneath): if len(tree) == 0: return [] elif len(tree) > 1 and isinstance(tree[1], list): subs = tree[1] if underneath is None or tree[0][0] != underneath: return leaves(subs, underneath) + leaves(tree[2:], underneath) else: # underneath=None to return all leaves from here out return leaves(subs, underneath=None) else: leaf = tree[0] tail = tree[1:] if leaf[0] == underneath: