def get_all_subclasses(asts): """Compute a class->subclasses mapping. Args: asts: A list of ASTs. Returns: A dictionary, mapping instances of pytd.Type (types) to lists of pytd.Class (the derived classes). """ hierarchy = {} for ast in asts: hierarchy.update(ast.Visit(visitors.ExtractSuperClasses())) def filter_superclasses(superclasses): return [ superclass for superclass in superclasses if hasattr(superclass, "name") and is_complete(superclass) ] hierarchy = { cls: filter_superclasses(superclasses) for cls, superclasses in hierarchy.items() if is_complete(cls) } # typically this is a fairly short list, e.g.: # [ClassType(basestring), ClassType(int), ClassType(object)] return utils.invert_dict(hierarchy)
def GetSubClasses(): """Get a reverse Python type hierarchy mapping. This generates a dictionary that can be used to look up the (known) subclasses of a type in the abstract base class hierarchy. Returns: A dictionary mapping a type, as string, to a list of direct subclasses (also as strings). E.g. "Sized" -> ["Set", "Mapping", "MappingView", "Sequence"]. """ return utils.invert_dict(GetSuperClasses())
def GetAllSubClasses(ast): """Compute a class->subclasses mapping. Args: ast: Parsed PYTD. Returns: A dictionary, mapping instances of pytd.Type (types) to lists of pytd.Class (the derived classes). """ hierarchy = ast.Visit(pytd_visitors.ExtractSuperClasses()) hierarchy = {cls: list(superclasses) for cls, superclasses in hierarchy.items()} return utils.invert_dict(hierarchy)
def test_invert_dict(self): a = {"p": ["q", "r"], "x": ["q", "z"]} b = utils.invert_dict(a) six.assertCountEqual(self, b["q"], ["p", "x"]) self.assertEqual(b["r"], ["p"]) self.assertEqual(b["z"], ["x"])
def __init__(self, superclasses): self._superclasses = superclasses self._subclasses = utils.invert_dict(self._superclasses)
def testInvertDict(self): a = {"p": ["q", "r"], "x": ["q", "z"]} b = utils.invert_dict(a) self.assertEqual(sorted(b["q"]), ["p", "x"]) self.assertEqual(b["r"], ["p"]) self.assertEqual(b["z"], ["x"])