Reputation: 5480
I am trying to print an instance of NetworkX MultiDiGraph as follows:
import networkx as nx
G = nx.MultiDiGraph()
G.add_node(0)
print(G)
My understanding is that since G
is an instance of a class, it should print something to the string even if __str__
is not implemented. However, this only prints a blank line. I also tested whether this is a NoneType
object:
isinstance(G, nx.MultiDiGraph)
This returns True
. How is this possible? If it is relevant, I am passing this graph to some other package which is returning an error related to NoneType
input. Thanks in advance for any help.
Upvotes: 0
Views: 175
Reputation: 23887
Networkx allows you to name a graph, which is what you get when you print the graph. So for example:
import networkx as nx
G = nx.MultiDiGraph(name = 'myG')
G.add_node(0)
print(G)
> myG
The name defaults to an empty string. So that is what is being printed. I think it's not obvious from the code, but at this link, the definition of the Graph
class is given. In it, __str__
is defined to return the graph name. The graph name is defined as
@property
def name(self):
"""String identifier of the graph.
This graph attribute appears in the attribute dict G.graph
keyed by the string `"name"`. as well as an attribute (technically
a property) `G.name`. This is entirely user controlled.
"""
return self.graph.get("name", "")
So the default name is an empty string. Now you've used a MultiDiGraph
, so this is hidden away - a MultiDiGraph
is built on a DiGraph
, which is built on a Graph
, so hidden in all of that, if the MultiDiGraph
isn't given a name, it defaults to an empty string.
Upvotes: 1