def get_shortest_path()

in src/doc_builder/autodoc.py [0:0]


def get_shortest_path(obj, package):
    """
    Simplifies the path to `obj` to be the shortest possible, for instance if `obj` is in the main init of its
    package.
    """
    if isinstance(obj, property):
        # Properties have no __module__ or __name__ attributes, but their getter function does.
        obj = obj.fget

    if not hasattr(obj, "__module__") or obj.__module__ is None:
        return None
    long_path = obj.__module__
    # Sometimes methods are defined in another module from the class (flax.struct.dataclass)
    if not long_path.startswith(package.__name__):
        return None
    long_name = obj.__qualname__ if hasattr(obj, "__qualname__") else obj.__name__
    short_name = long_name.split(".")[0]
    path_splits = long_path.split(".")
    module = package
    idx = module.__name__.count(".")
    while idx + 1 < len(path_splits) and not hasattr(module, short_name):
        idx += 1
        module = getattr(module, path_splits[idx])
    return ".".join(path_splits[: idx + 1]) + "." + long_name