Skip to content

Commit

Permalink
Switch to code formatter Black: Quotes, 2nd run
Browse files Browse the repository at this point in the history
Let `black` take care of the quotes as well, meaning a switch from
single quotes to double quotes (except for where it would result in
more backslash escapes). Currently, `black` can only be configured to
either enforce double quotes or skip this altogether, not to enforce
single quotes.

I had some doubts about this switch at first, but noticed that several
other projects and their documentation examples have switched to using
double quotes now. Holding on to a consistent use of single quotes
could become more of a burden, while offering only little benefit.

Changes from single quotes to double quotes that were made manually:
- Examples in `README.md`.
- `pydot.py`, the `*_ATTRIBUTES` constants at the top, because they are
  surrounded by `# fmt: off` and `# fmt: on` pragmas.

Note this is all about quotes around Python strings in the pydot source
code and not at all related to quotes that are part of a DOT string.
  • Loading branch information
peternowee committed Jun 12, 2021
1 parent 65988af commit cdbfc3e
Show file tree
Hide file tree
Showing 6 changed files with 508 additions and 509 deletions.
24 changes: 12 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ start with. Here are 3 common options:
```python
import pydot

graphs = pydot.graph_from_dot_file('example.dot')
graphs = pydot.graph_from_dot_file("example.dot")
graph = graphs[0]
```

Expand Down Expand Up @@ -81,19 +81,19 @@ start with. Here are 3 common options:
```python
import pydot

graph = pydot.Dot('my_graph', graph_type='graph', bgcolor='yellow')
graph = pydot.Dot("my_graph", graph_type="graph", bgcolor="yellow")

# Add nodes
my_node = pydot.Node('a', label='Foo')
my_node = pydot.Node("a", label="Foo")
graph.add_node(my_node)
# Or, without using an intermediate variable:
graph.add_node(pydot.Node('b', shape='circle'))
graph.add_node(pydot.Node("b", shape="circle"))

# Add edges
my_edge = pydot.Edge('a', 'b', color='blue')
my_edge = pydot.Edge("a", "b", color="blue")
graph.add_edge(my_edge)
# Or, without using an intermediate variable:
graph.add_edge(pydot.Edge('b', 'c', color='blue'))
graph.add_edge(pydot.Edge("b", "c", color="blue"))
```

Imagine using these basic building blocks from your Python program
Expand Down Expand Up @@ -124,14 +124,14 @@ You can now further manipulate your graph using pydot methods:
- Add further nodes and edges:

```python
graph.add_edge(pydot.Edge('b', 'd', style='dotted'))
graph.add_edge(pydot.Edge("b", "d", style="dotted"))
```

- Edit attributes of graph, nodes and edges:

```python
graph.set_bgcolor('lightyellow')
graph.get_node('b')[0].set_shape('box')
graph.set_bgcolor("lightyellow")
graph.get_node("b")[0].set_shape("box")
```

Output
Expand All @@ -155,7 +155,7 @@ Here are 3 different output options:
the `write_*` methods:

```python
graph.write_png('output.png')
graph.write_png("output.png")
```

2. Retrieve the DOT string.
Expand All @@ -170,7 +170,7 @@ Here are 3 different output options:
# As a string:
output_raw_dot = graph.to_string()
# Or, save it as a DOT-file:
graph.write_raw('output_raw.dot')
graph.write_raw("output_raw.dot")
```

- The Graphviz DOT: You can use it to check how Graphviz lays out
Expand All @@ -181,7 +181,7 @@ Here are 3 different output options:
# As a bytes literal:
output_graphviz_dot = graph.create_dot()
# Or, save it as a DOT-file:
graph.write_dot('output_graphviz.dot')
graph.write_dot("output_graphviz.dot")
```

3. Convert to a NetworkX graph.
Expand Down
96 changes: 48 additions & 48 deletions dot_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@

import pydot

__author__ = ['Michael Krause', 'Ero Carrera']
__license__ = 'MIT'
__author__ = ["Michael Krause", "Ero Carrera"]
__license__ = "MIT"


PY3 = sys.version_info >= (3, 0, 0)
Expand All @@ -52,7 +52,7 @@ def __init__(self, toks):

while i < len(toks):
attrname = toks[i]
if i + 2 < len(toks) and toks[i + 1] == '=':
if i + 2 < len(toks) and toks[i + 1] == "=":
attrvalue = toks[i + 2]
i += 3
else:
Expand Down Expand Up @@ -95,15 +95,15 @@ def push_top_graph_stmt(str, loc, toks):

element = element[0]

if element == 'strict':
attrs['strict'] = True
if element == "strict":
attrs["strict"] = True

elif element in ['graph', 'digraph']:
elif element in ["graph", "digraph"]:

attrs = {}

g = pydot.Dot(graph_type=element, **attrs)
attrs['type'] = element
attrs["type"] = element

top_graphs.append(g)

Expand All @@ -112,10 +112,10 @@ def push_top_graph_stmt(str, loc, toks):

elif isinstance(element, pydot.Subgraph):

g.obj_dict['attributes'].update(element.obj_dict['attributes'])
g.obj_dict['edges'].update(element.obj_dict['edges'])
g.obj_dict['nodes'].update(element.obj_dict['nodes'])
g.obj_dict['subgraphs'].update(element.obj_dict['subgraphs'])
g.obj_dict["attributes"].update(element.obj_dict["attributes"])
g.obj_dict["edges"].update(element.obj_dict["edges"])
g.obj_dict["nodes"].update(element.obj_dict["nodes"])
g.obj_dict["subgraphs"].update(element.obj_dict["subgraphs"])

g.set_parent_graph(g)

Expand All @@ -127,7 +127,7 @@ def push_top_graph_stmt(str, loc, toks):

else:
raise ValueError(
'Unknown element statement: {s}'.format(s=element)
"Unknown element statement: {s}".format(s=element)
)

for g in top_graphs:
Expand All @@ -143,7 +143,7 @@ def update_parent_graph_hierarchy(g, parent_graph=None, level=0):
if parent_graph is None:
parent_graph = g

for key_name in ('edges',):
for key_name in ("edges",):

if isinstance(g, pydot.frozendict):
item_dict = g
Expand All @@ -156,26 +156,26 @@ def update_parent_graph_hierarchy(g, parent_graph=None, level=0):
for key, objs in item_dict[key_name].items():
for obj in objs:
if (
'parent_graph' in obj
and obj['parent_graph'].get_parent_graph() == g
"parent_graph" in obj
and obj["parent_graph"].get_parent_graph() == g
):
if obj['parent_graph'] is g:
if obj["parent_graph"] is g:
pass
else:
obj['parent_graph'].set_parent_graph(parent_graph)
obj["parent_graph"].set_parent_graph(parent_graph)

if key_name == 'edges' and len(key) == 2:
for idx, vertex in enumerate(obj['points']):
if key_name == "edges" and len(key) == 2:
for idx, vertex in enumerate(obj["points"]):
if isinstance(
vertex,
(pydot.Graph, pydot.Subgraph, pydot.Cluster),
):
vertex.set_parent_graph(parent_graph)
if isinstance(vertex, pydot.frozendict):
if vertex['parent_graph'] is g:
if vertex["parent_graph"] is g:
pass
else:
vertex['parent_graph'].set_parent_graph(
vertex["parent_graph"].set_parent_graph(
parent_graph
)

Expand Down Expand Up @@ -223,56 +223,56 @@ def add_elements(

elif isinstance(element, DefaultStatement):

if element.default_type == 'graph':
if element.default_type == "graph":

default_graph_attrs = pydot.Node('graph', **element.attrs)
default_graph_attrs = pydot.Node("graph", **element.attrs)
g.add_node(default_graph_attrs)

elif element.default_type == 'node':
elif element.default_type == "node":

default_node_attrs = pydot.Node('node', **element.attrs)
default_node_attrs = pydot.Node("node", **element.attrs)
g.add_node(default_node_attrs)

elif element.default_type == 'edge':
elif element.default_type == "edge":

default_edge_attrs = pydot.Node('edge', **element.attrs)
default_edge_attrs = pydot.Node("edge", **element.attrs)
g.add_node(default_edge_attrs)
defaults_edge.update(element.attrs)

else:
raise ValueError(
'Unknown DefaultStatement: {s}'.format(
"Unknown DefaultStatement: {s}".format(
s=element.default_type
)
)

elif isinstance(element, P_AttrList):

g.obj_dict['attributes'].update(element.attrs)
g.obj_dict["attributes"].update(element.attrs)

else:
raise ValueError(
'Unknown element statement: {s}'.format(s=element)
"Unknown element statement: {s}".format(s=element)
)


def push_graph_stmt(str, loc, toks):
g = pydot.Subgraph('')
g = pydot.Subgraph("")
add_elements(g, toks)
return g


def push_subgraph_stmt(str, loc, toks):
g = pydot.Subgraph('')
g = pydot.Subgraph("")
for e in toks:
if len(e) == 3:
e[2].set_name(e[1])
if e[0] == 'subgraph':
e[2].obj_dict['show_keyword'] = True
if e[0] == "subgraph":
e[2].obj_dict["show_keyword"] = True
return e[2]
else:
if e[0] == 'subgraph':
e[1].obj_dict['show_keyword'] = True
if e[0] == "subgraph":
e[1].obj_dict["show_keyword"] = True
return e[1]

return g
Expand All @@ -289,10 +289,10 @@ def push_default_stmt(str, loc, toks):
else:
attrs = {}

if default_type in ['graph', 'node', 'edge']:
if default_type in ["graph", "node", "edge"]:
return DefaultStatement(default_type, attrs)
else:
raise ValueError('Unknown default statement: {s}'.format(s=toks))
raise ValueError("Unknown default statement: {s}".format(s=toks))


def push_attr_list(str, loc, toks):
Expand All @@ -304,16 +304,16 @@ def get_port(node):
if len(node) > 1:
if isinstance(node[1], ParseResults):
if len(node[1][0]) == 2:
if node[1][0][0] == ':':
if node[1][0][0] == ":":
return node[1][0][1]

return None


def do_node_ports(node):
node_port = ''
node_port = ""
if len(node) > 1:
node_port = ''.join([str(a) + str(b) for a, b in node[1]])
node_port = "".join([str(a) + str(b) for a, b in node[1]])

return node_port

Expand Down Expand Up @@ -372,7 +372,7 @@ def push_edge_stmt(str, loc, toks):
n_prev = n_next[0] + n_next_port
else:
raise Exception(
'Edge target {r} with type {s} unsupported.'.format(
"Edge target {r} with type {s} unsupported.".format(
r=toks[2][0], s=type(toks[2][0])
)
)
Expand Down Expand Up @@ -432,17 +432,17 @@ def graph_definition():
identifier = Word(alphanums + "_.").setName("identifier")

double_quoted_string = QuotedString(
'"', multiline=True, unquoteResults=False, escChar='\\'
'"', multiline=True, unquoteResults=False, escChar="\\"
)

noncomma = "".join([c for c in printables if c != ","])
alphastring_ = OneOrMore(CharsNotIn(noncomma + ' '))
alphastring_ = OneOrMore(CharsNotIn(noncomma + " "))

def parse_html(s, loc, toks):
return '<%s>' % ''.join(toks[0])
return "<%s>" % "".join(toks[0])

opener = '<'
closer = '>'
opener = "<"
closer = ">"
html_text = (
nestedExpr(opener, closer, (CharsNotIn(opener + closer)))
.setParseAction(parse_html)
Expand Down Expand Up @@ -504,7 +504,7 @@ def parse_html(s, loc, toks):
)

edge_point << Group(subgraph | graph_stmt | node_id).setName(
'edge_point'
"edge_point"
)

node_stmt = (
Expand Down

0 comments on commit cdbfc3e

Please sign in to comment.