Skip to content

networkx: Types for Graph properties are more general than required #14592

@jenshnielsen

Description

@jenshnielsen

The types introduced in #14569 are more general than required. As an example look at DiGraph.out_degree
This is now typed as def out_degree(self) -> int | OutDegreeView[_Node] | OutMultiDegreeView[_Node]: ...
This seems to be based on the documentation here that claims that an int can be returned. However looking at the examples and the documentation an int is only returned if a single node is given as an argument. This is a somewhat confusing statement as this is a property and therefor does not take any argument. Furthermore, looking at the source code an OutDegreeView is always the property. What is meant by the docstring is that the property returned which is always a OutDegreeView can return an int if that is called with a single node

import networkx as nx
G = nx.DiGraph()
nx.add_path(G, [0, 1, 2, 3])

out_view = G.out_degree  # this is always an `OutDegreeView`
G.out_degree(0)  # this returns an int
G.out_degree([0, 1, 2])

The same applies to in_degree and edges in the DiGraph class and probably similar in other graph classes.

Suggested solution remove int (and probably also ...MultiDegreeView from the return type of DiGraph.in_degree DiGraph.out_degree and DiGraph.degree and similar in other Graph classes.
It might also be worthwile improving the docs in networkx to clarify this. As a bonus the types for OutDegreeView could be improved such that it overloads on the type of nbunch to clarify that an int is returned if a single node is given and a view otherwise.

An example of the issues this creates can be found in microsoft/Qcodes#7401

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions