Skip to content

Commit

Permalink
Convert %-format to fstring
Browse files Browse the repository at this point in the history
  • Loading branch information
jarrodmillman committed Jan 1, 2020
1 parent 0a3d69c commit 1bbcc51
Show file tree
Hide file tree
Showing 59 changed files with 239 additions and 292 deletions.
9 changes: 6 additions & 3 deletions networkx/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,12 @@
# Release data
from networkx import release

__author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \
(release.authors['Hagberg'] + release.authors['Schult'] +
release.authors['Swart'])

__author__ = (
f"{release.authors['Hagberg'][0]} <{release.authors['Hagberg'][1]}>\n"
f"{release.authors['Schult'][0]} <{release.authors['Schult'][1]}>\n"
f"{release.authors['Swart'][0]} <{release.authors['Swart'][1]}>"
)

__date__ = release.date
__version__ = release.version
Expand Down
6 changes: 3 additions & 3 deletions networkx/algorithms/approximation/connectivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,9 @@ def node_connectivity(G, s=None, t=None):
# Local node connectivity
if s is not None and t is not None:
if s not in G:
raise nx.NetworkXError('node %s not in graph' % s)
raise nx.NetworkXError(f"node {s} not in graph")
if t not in G:
raise nx.NetworkXError('node %s not in graph' % t)
raise nx.NetworkXError(f"node {t} not in graph")
return local_node_connectivity(G, s, t)

# Global node connectivity
Expand Down Expand Up @@ -396,4 +396,4 @@ def _bidirectional_pred_succ(G, source, target, exclude):
if w in pred:
return pred, succ, w # found path

raise nx.NetworkXNoPath("No path between %s and %s." % (source, target))
raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
2 changes: 1 addition & 1 deletion networkx/algorithms/approximation/kcomponents.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def neighbors(self, n):
try:
return iter(set(self._adj) - set(self._adj[n]) - set([n]))
except KeyError:
raise NetworkXError("The node %s is not in the graph." % (n,))
raise NetworkXError(f"The node {n} is not in the graph.")

class AntiAtlasView(Mapping):
"""An adjacency inner dict for AntiGraph"""
Expand Down
14 changes: 4 additions & 10 deletions networkx/algorithms/bipartite/edgelist.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,7 @@ def parse_edgelist(lines, comments='#', delimiter=None,
u = nodetype(u)
v = nodetype(v)
except:
raise TypeError("Failed to convert nodes %s,%s to type %s."
% (u, v, nodetype))
raise TypeError(f"Failed to convert nodes {u},{v} to type {nodetype}.")

if len(d) == 0 or data is False:
# no data or data type specified
Expand All @@ -248,22 +247,17 @@ def parse_edgelist(lines, comments='#', delimiter=None,
try: # try to evaluate as dictionary
edgedata = dict(literal_eval(' '.join(d)))
except:
raise TypeError(
"Failed to convert edge data (%s) to dictionary." % (d))
raise TypeError(f"Failed to convert edge data ({d}) to dictionary.")
else:
# convert edge data to dictionary with specified keys and type
if len(d) != len(data):
raise IndexError(
"Edge data %s and data_keys %s are not the same length" %
(d, data))
raise IndexError(f"Edge data {d} and data_keys {data} are not the same length")
edgedata = {}
for (edge_key, edge_type), edge_value in zip(data, d):
try:
edge_value = edge_type(edge_value)
except:
raise TypeError(
"Failed to convert %s data %s to type %s."
% (edge_key, edge_value, edge_type))
raise TypeError(f"Failed to convert {edge_key} data {edge_value} to type {edge_type}.")
edgedata.update({edge_key: edge_value})
G.add_node(u, bipartite=0)
G.add_node(v, bipartite=1)
Expand Down
24 changes: 8 additions & 16 deletions networkx/algorithms/bipartite/generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def complete_bipartite_graph(n1, n2, create_using=None):
G.add_nodes_from(top, bipartite=0)
G.add_nodes_from(bottom, bipartite=1)
G.add_edges_from((u, v) for u in top for v in bottom)
G.graph['name'] = "complete_bipartite_graph(%s,%s)" % (n1, n2)
G.graph['name'] = f"complete_bipartite_graph({n1},{n2})"
return G


Expand Down Expand Up @@ -105,9 +105,7 @@ def configuration_model(aseq, bseq, create_using=None, seed=None):
sumb = sum(bseq)

if not suma == sumb:
raise nx.NetworkXError(
'invalid degree sequences, sum(aseq)!=sum(bseq),%s,%s'
% (suma, sumb))
raise nx.NetworkXError(f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}")

G = _add_nodes_with_bipartite_label(G, lena, lenb)

Expand Down Expand Up @@ -179,9 +177,7 @@ def havel_hakimi_graph(aseq, bseq, create_using=None):
sumb = sum(bseq)

if not suma == sumb:
raise nx.NetworkXError(
'invalid degree sequences, sum(aseq)!=sum(bseq),%s,%s'
% (suma, sumb))
raise nx.NetworkXError(f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}")

G = _add_nodes_with_bipartite_label(G, naseq, nbseq)

Expand Down Expand Up @@ -252,9 +248,7 @@ def reverse_havel_hakimi_graph(aseq, bseq, create_using=None):
sumb = sum(bseq)

if not suma == sumb:
raise nx.NetworkXError(
'invalid degree sequences, sum(aseq)!=sum(bseq),%s,%s'
% (suma, sumb))
raise nx.NetworkXError(f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}")

G = _add_nodes_with_bipartite_label(G, lena, lenb)

Expand Down Expand Up @@ -326,9 +320,7 @@ def alternating_havel_hakimi_graph(aseq, bseq, create_using=None):
sumb = sum(bseq)

if not suma == sumb:
raise nx.NetworkXError(
'invalid degree sequences, sum(aseq)!=sum(bseq),%s,%s'
% (suma, sumb))
raise nx.NetworkXError(f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}")

G = _add_nodes_with_bipartite_label(G, naseq, nbseq)

Expand Down Expand Up @@ -404,7 +396,7 @@ def preferential_attachment_graph(aseq, p, create_using=None, seed=None):
raise nx.NetworkXError("Directed Graph not supported")

if p > 1:
raise nx.NetworkXError("probability %s > 1" % (p))
raise nx.NetworkXError(f"probability {p} > 1")

naseq = len(aseq)
G = _add_nodes_with_bipartite_label(G, naseq, 0)
Expand Down Expand Up @@ -479,7 +471,7 @@ def random_graph(n, m, p, seed=None, directed=False):
G = _add_nodes_with_bipartite_label(G, n, m)
if directed:
G = nx.DiGraph(G)
G.name = "fast_gnp_random_graph(%s,%s,%s)" % (n, m, p)
G.name = f"fast_gnp_random_graph({n},{m},{p})"

if p <= 0:
return G
Expand Down Expand Up @@ -564,7 +556,7 @@ def gnmk_random_graph(n, m, k, seed=None, directed=False):
G = _add_nodes_with_bipartite_label(G, n, m)
if directed:
G = nx.DiGraph(G)
G.name = "bipartite_gnm_random_graph(%s,%s,%s)" % (n, m, k)
G.name = f"bipartite_gnm_random_graph({n},{m},{k})"
if n == 1 or m == 1:
return G
max_edges = n * m # max_edges for bipartite networks
Expand Down
2 changes: 1 addition & 1 deletion networkx/algorithms/bipartite/matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def biadjacency_matrix(G, row_order, column_order=None,
# From Scipy 1.1.0, asformat will throw a ValueError instead of an
# AttributeError if the format if not recognized.
except (AttributeError, ValueError):
raise nx.NetworkXError("Unknown sparse matrix format: %s" % format)
raise nx.NetworkXError(f"Unknown sparse matrix format: {format}")


def from_biadjacency_matrix(A, create_using=None, edge_attribute='weight'):
Expand Down
2 changes: 1 addition & 1 deletion networkx/algorithms/centrality/current_flow_betweenness.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def approximate_current_flow_betweenness_centrality(G, normalized=True,
l = 1 # parameter in approximation, adjustable
k = l * int(np.ceil((cstar / epsilon)**2 * np.log(n)))
if k > kmax:
msg = 'Number random pairs k>kmax (%d>%d) ' % (k, kmax)
msg = f"Number random pairs k>kmax ({k}>{kmax}) "
raise nx.NetworkXError(msg, 'Increase kmax or epsilon')
cstar2k = cstar / (2 * k)
for i in range(k):
Expand Down
4 changes: 2 additions & 2 deletions networkx/algorithms/centrality/katz.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def katz_centrality(G, alpha=0.1, beta=1.0, max_iter=1000, tol=1.0e-6,
>>> phi = (1 + math.sqrt(5)) / 2.0 # largest eigenvalue of adj matrix
>>> centrality = nx.katz_centrality(G, 1/phi - 0.01)
>>> for n, c in sorted(centrality.items()):
... print("%d %0.2f" % (n, c))
... print(f"{n} {c:.2f}")
0 0.37
1 0.60
2 0.60
Expand Down Expand Up @@ -253,7 +253,7 @@ def katz_centrality_numpy(G, alpha=0.1, beta=1.0, normalized=True,
>>> phi = (1 + math.sqrt(5)) / 2.0 # largest eigenvalue of adj matrix
>>> centrality = nx.katz_centrality_numpy(G, 1/phi)
>>> for n, c in sorted(centrality.items()):
... print("%d %0.2f" % (n, c))
... print(f"{n} {c:.2f}")
0 0.37
1 0.60
2 0.60
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def test_degree_centrality_3(self):
exact = {0: .444, 1: .444, 2: .333, 3: .667, 4: .333,
5: .556, 6: .556, 7: .333, 8: .222, 9: .111}
for n, dc in d.items():
assert almost_equal(exact[n], float("%5.3f" % dc))
assert almost_equal(exact[n], float(f"{dc:.3f}"))

def test_degree_centrality_4(self):
d = nx.degree_centrality(self.F)
Expand All @@ -74,7 +74,7 @@ def test_degree_centrality_4(self):
0.071, 0.429, 0.071, 0.214, 0.214, 0.143, 0.286, 0.214]
exact = dict(zip(names, dcs))
for n, dc in d.items():
assert almost_equal(exact[n], float("%5.3f" % dc))
assert almost_equal(exact[n], float(f"{dc:.3f}"))

def test_indegree_centrality(self):
d = nx.in_degree_centrality(self.G)
Expand Down
3 changes: 1 addition & 2 deletions networkx/algorithms/chordal.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,8 +302,7 @@ def _find_chordality_breaker(G, s=None, treewidth_bound=sys.maxsize):
# The graph seems to be chordal by now. We update the treewidth
current_treewidth = max(current_treewidth, len(clique_wanna_be))
if current_treewidth > treewidth_bound:
raise nx.NetworkXTreewidthBoundExceeded(
"treewidth_bound exceeded: %s" % current_treewidth)
raise nx.NetworkXTreewidthBoundExceeded(f"treewidth_bound exceeded: {current_treewidth}")
else:
# sg is not a clique,
# look for an edge that is not included in sg
Expand Down
2 changes: 1 addition & 1 deletion networkx/algorithms/community/kclique.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def k_clique_communities(G, k, cliques=None):
doi:10.1038/nature03607
"""
if k < 2:
raise nx.NetworkXError("k=%d, k must be greater than 1." % k)
raise nx.NetworkXError(f"k={k}, k must be greater than 1.")
if cliques is None:
cliques = nx.find_cliques(G)
cliques = [frozenset(c) for c in cliques if len(c) >= k]
Expand Down
8 changes: 4 additions & 4 deletions networkx/algorithms/connectivity/connectivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,9 +302,9 @@ def node_connectivity(G, s=None, t=None, flow_func=None):
# Local node connectivity
if s is not None and t is not None:
if s not in G:
raise nx.NetworkXError('node %s not in graph' % s)
raise nx.NetworkXError(f"node {s} not in graph")
if t not in G:
raise nx.NetworkXError('node %s not in graph' % t)
raise nx.NetworkXError(f"node {t} not in graph")
return local_node_connectivity(G, s, t, flow_func=flow_func)

# Global node connectivity
Expand Down Expand Up @@ -752,9 +752,9 @@ def edge_connectivity(G, s=None, t=None, flow_func=None, cutoff=None):
# Local edge connectivity
if s is not None and t is not None:
if s not in G:
raise nx.NetworkXError('node %s not in graph' % s)
raise nx.NetworkXError(f"node {s} not in graph")
if t not in G:
raise nx.NetworkXError('node %s not in graph' % t)
raise nx.NetworkXError(f"node {t} not in graph")
return local_edge_connectivity(G, s, t, flow_func=flow_func,
cutoff=cutoff)

Expand Down
10 changes: 5 additions & 5 deletions networkx/algorithms/connectivity/cuts.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ def minimum_st_node_cut(G, s, t, flow_func=None, auxiliary=None, residual=None):

# The edge cut in the auxiliary digraph corresponds to the node cut in the
# original graph.
edge_cut = minimum_st_edge_cut(H, '%sB' % mapping[s], '%sA' % mapping[t],
edge_cut = minimum_st_edge_cut(H, f'{mapping[s]}B', f'{mapping[t]}A',
**kwargs)
# Each node in the original graph maps to two nodes of the auxiliary graph
node_cut = set(H.nodes[node]['id'] for edge in edge_cut for node in edge)
Expand Down Expand Up @@ -392,9 +392,9 @@ def minimum_node_cut(G, s=None, t=None, flow_func=None):
# Local minimum node cut.
if s is not None and t is not None:
if s not in G:
raise nx.NetworkXError('node %s not in graph' % s)
raise nx.NetworkXError(f"node {s} not in graph")
if t not in G:
raise nx.NetworkXError('node %s not in graph' % t)
raise nx.NetworkXError(f"node {t} not in graph")
return minimum_st_node_cut(G, s, t, flow_func=flow_func)

# Global minimum node cut.
Expand Down Expand Up @@ -544,9 +544,9 @@ def minimum_edge_cut(G, s=None, t=None, flow_func=None):
# Local minimum edge cut if s and t are not None
if s is not None and t is not None:
if s not in G:
raise nx.NetworkXError('node %s not in graph' % s)
raise nx.NetworkXError(f"node {s} not in graph")
if t not in G:
raise nx.NetworkXError('node %s not in graph' % t)
raise nx.NetworkXError(f"node {t} not in graph")
return minimum_st_edge_cut(H, s, t, **kwargs)

# Global minimum edge cut
Expand Down
14 changes: 7 additions & 7 deletions networkx/algorithms/connectivity/disjoint_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,9 @@ def edge_disjoint_paths(G, s, t, flow_func=None, cutoff=None, auxiliary=None,
"""
if s not in G:
raise nx.NetworkXError('node %s not in graph' % s)
raise nx.NetworkXError(f"node {s} not in graph")
if t not in G:
raise nx.NetworkXError('node %s not in graph' % t)
raise nx.NetworkXError(f"node {t} not in graph")

if flow_func is None:
flow_func = default_flow_func
Expand Down Expand Up @@ -346,9 +346,9 @@ def node_disjoint_paths(G, s, t, flow_func=None, cutoff=None, auxiliary=None,
"""
if s not in G:
raise nx.NetworkXError('node %s not in graph' % s)
raise nx.NetworkXError(f"node {s} not in graph")
if t not in G:
raise nx.NetworkXError('node %s not in graph' % t)
raise nx.NetworkXError(f"node {t} not in graph")

if auxiliary is None:
H = build_auxiliary_node_connectivity(G)
Expand All @@ -360,8 +360,8 @@ def node_disjoint_paths(G, s, t, flow_func=None, cutoff=None, auxiliary=None,
raise nx.NetworkXError('Invalid auxiliary digraph.')

# Maximum possible edge disjoint paths
possible = min(H.out_degree('%sB' % mapping[s]),
H.in_degree('%sA' % mapping[t]))
possible = min(H.out_degree(f'{mapping[s]}B'),
H.in_degree(f'{mapping[t]}A'))
if not possible:
raise NetworkXNoPath

Expand All @@ -375,7 +375,7 @@ def node_disjoint_paths(G, s, t, flow_func=None, cutoff=None, auxiliary=None,

# The edge disjoint paths in the auxiliary digraph correspond to the node
# disjoint paths in the original graph.
paths_edges = edge_disjoint_paths(H, '%sB' % mapping[s], '%sA' % mapping[t],
paths_edges = edge_disjoint_paths(H, f'{mapping[s]}B', f'{mapping[t]}A',
**kwargs)
for path in paths_edges:
# Each node in the original graph maps to two nodes in auxiliary graph
Expand Down
16 changes: 8 additions & 8 deletions networkx/algorithms/connectivity/kcutsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def all_node_cuts(G, k=None, flow_func=None):
for v in non_adjacent:
# step 4: compute maximum flow in an Even-Tarjan reduction H of G
# and step 5: build the associated residual network R
R = flow_func(H, '%sB' % mapping[x], '%sA' % mapping[v], **kwargs)
R = flow_func(H, f'{mapping[x]}B', f'{mapping[v]}A', **kwargs)
flow_value = R.graph['flow_value']

if flow_value == k:
Expand Down Expand Up @@ -177,7 +177,7 @@ def all_node_cuts(G, k=None, flow_func=None):
for n in S:
S_ancestors.update(R_closure._pred[n])
S.update(S_ancestors)
if '%sB' % mapping[x] not in S or '%sA' % mapping[v] in S:
if f'{mapping[x]}B' not in S or f'{mapping[v]}A' in S:
continue
# Find the cutset that links the node partition (S,~S) in H
cutset = set()
Expand Down Expand Up @@ -207,18 +207,18 @@ def all_node_cuts(G, k=None, flow_func=None):
# Add edges to the auxiliary digraph.
# See build_residual_network for convention we used
# in residual graphs.
H.add_edge('%sB' % mapping[x], '%sA' % mapping[v],
H.add_edge(f'{mapping[x]}B', f'{mapping[v]}A',
capacity=1)
H.add_edge('%sB' % mapping[v], '%sA' % mapping[x],
H.add_edge(f'{mapping[v]}B', f'{mapping[x]}A',
capacity=1)
# Add edges to the residual network.
R.add_edge('%sB' % mapping[x], '%sA' % mapping[v],
R.add_edge(f'{mapping[x]}B', f'{mapping[v]}A',
capacity=1)
R.add_edge('%sA' % mapping[v], '%sB' % mapping[x],
R.add_edge(f'{mapping[v]}A', f'{mapping[x]}B',
capacity=0)
R.add_edge('%sB' % mapping[v], '%sA' % mapping[x],
R.add_edge(f'{mapping[v]}B', f'{mapping[x]}A',
capacity=1)
R.add_edge('%sA' % mapping[x], '%sB' % mapping[v],
R.add_edge(f'{mapping[x]}A', f'{mapping[v]}B',
capacity=0)

# Add again the saturated edges to reuse the residual network
Expand Down
2 changes: 1 addition & 1 deletion networkx/algorithms/connectivity/tests/test_cuts.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def _generate_no_biconnected(max_attempts=50):
yield G
else:
if attempts >= max_attempts:
msg = "Tried %d times: no suitable Graph." % attempts
msg = f"Tried {attempts} times: no suitable Graph."
raise Exception(msg % max_attempts)
else:
attempts += 1
Expand Down
2 changes: 1 addition & 1 deletion networkx/algorithms/connectivity/tests/test_kcutsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def _generate_no_biconnected(max_attempts=50):
yield G
else:
if attempts >= max_attempts:
msg = "Tried %d times: no suitable Graph." % attempts
msg = f"Tried {attempts} times: no suitable Graph."
raise Exception(msg % max_attempts)
else:
attempts += 1
Expand Down
Loading

0 comments on commit 1bbcc51

Please sign in to comment.