Skip to content

Commit 0c0ebd7

Browse files
committed
feat: added Graph.to_networkx(create_using=...)
1 parent 6915ff6 commit 0c0ebd7

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313

1414
* `Graph.to_directed()` now supports a `mode=...` keyword argument.
1515

16+
* Added a `create_using=...` keyword argument to `Graph.to_networkx()` to
17+
let the user specify which NetworkX class to use when converting the graph.
18+
1619
### Changed
1720

1821
* Updated igraph dependency to 0.9.3.

src/igraph/__init__.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1867,28 +1867,33 @@ def maximum_bipartite_matching(self, types="type", weights=None, eps=None):
18671867
#############################################
18681868
# Auxiliary I/O functions
18691869

1870-
def to_networkx(self):
1871-
"""Converts the graph to networkx format"""
1870+
def to_networkx(self, create_using=None):
1871+
"""Converts the graph to networkx format.
1872+
1873+
@param create_using: specifies which NetworkX graph class to use when
1874+
constructing the graph. C{None} means to let igraph infer the most
1875+
appropriate class based on whether the graph is directed and whether
1876+
it has multi-edges.
1877+
"""
18721878
import networkx as nx
18731879

18741880
# Graph: decide on directness and mutliplicity
1875-
if any(self.is_multiple()):
1876-
if self.is_directed():
1877-
cls = nx.MultiDiGraph
1881+
if create_using is None:
1882+
if self.has_multiple():
1883+
cls = nx.MultiDiGraph if self.is_directed() else nx.MultiGraph
18781884
else:
1879-
cls = nx.MultiGraph
1885+
cls = nx.DiGraph if self.is_directed() else nx.Graph
18801886
else:
1881-
if self.is_directed():
1882-
cls = nx.DiGraph
1883-
else:
1884-
cls = nx.Graph
1887+
cls = create_using
18851888

18861889
# Graph attributes
18871890
kw = {x: self[x] for x in self.attributes()}
18881891
g = cls(**kw)
18891892

18901893
# Nodes and node attributes
18911894
for i, v in enumerate(self.vs):
1895+
# TODO: use _nx_name if the attribute is present so we can achieve
1896+
# a lossless round-trip in terms of vertex names
18921897
g.add_node(i, **v.attributes())
18931898

18941899
# Edges and edge attributes

0 commit comments

Comments
 (0)