Reference
Many methods accept identifier and attribute value assignment parameters. See the IDs, Attributes, and Roles discussions. The terms define, establish, and amend are defined here.
Dot and Block
- class Dot(*, directed: bool = False, strict: bool = False, multigraph: bool = False, id: ID | None = None, comment: str | None = None)
Bases:
BlockA DOT language builder.
- Parameters:
directed – Make the graph directed.
strict – Include the
strictkeyword. This argument is present for completeness. It’s unlikely to be useful with Dot objects sinceDotguarantees edge uniqueness for non-multigraphs.multigraph – Support multiple edges between the same node pair (ordered pair in the directed case.) This parameter affects the behavior of methods
edge(),edge_define(), andedge_update().id – The graph identifier.
comment – Possibly multiline text prepended as a
//style comment.
- Raises:
ValueError – If both
strictandmultigraphare True.
- class Block
A scope for graph and default attribute assignments and a container for node, edge, and subgraph definitions.
Blockis the base class ofDot.There is a one-to-one correspondence between Block objects and the graph and subgraph statements of a Dot object’s DOT language representation. The Dot object itself corresponds to the top-level
graphordigraphform. The remaining Block objects are those returned by methodssubgraph()orsubgraph_define().Blocks should only be created by calling
Dot(),subgraph(), orsubgraph_define(). ExecutingBlock()directly raises aRuntimeError.
NOTE: The methods of Dot and Block described below
are organized by category, not by class. Keep in mind that each
Block method is also a method of Dot.
Theme Methods
- Dot.use_theme(theme: Dot | None) Self
Inherit graph, default graph, default node, default edge, and role attribute values from
theme. Any nodes, edges, or subgraphs ofthemeare ignored.Dotforms DOT language representations by merging inherited attribute values with a Dot object’s own assigned values (which have precedence). Inheritance can be chained, with themes inheriting from themes. The final merged result incorporates attributes from the entire chain.Theme use is dynamic. Any change to the theme inheritance chain or heritable attributes of a theme in the chain is immediately reflected in the Dot object’s DOT language representation.
- Parameters:
theme – The attribute inheritance source or None. If
themeis None, the Dot object does not inherit from any theme.- Raises:
ValueError – Using the theme would create an inheritance cycle.
See also the Themes discussion.
Graph Methods
- Dot.graph_role(role: str, /, **attrs: ID | None) Self
Define a graph role or amend its attributes.
- Parameters:
role – The graph role to define or amend.
attrs – New or amending attribute value assignments.
Node Methods
- Dot.node_role(role: str, /, **attrs: ID | None) Self
Define a node role or amend its attributes.
- Parameters:
role – The node role to define or amend.
attrs – New or amending attribute value assignments.
- Block.node_default(**attrs: ID | None) Self
Establish or amend default node attributes.
- Parameters:
attrs – New or amending attribute value assignments.
- Block.node(id: ID, /, **attrs: ID | None) Self
Define a node or amend its attributes.
- Parameters:
id – The node to define or amend.
attrs – New or amending attribute value assignments.
The Block object through which a node is defined determines where in the DOT language representation the corresponding node statement will appear. However, node identity is global, so a node may be amended through any Block object.
For example,
dot = Dot() sub1 = dot.subgraph("Sub1") sub2 = dot.subgraph("Sub2") sub2.node("a", label="Defined in Sub2") sub1.node("a", fontsize=10) dot.node("a", color="blue")
has the Dot language representation
graph { subgraph Sub1 { } subgraph Sub2 { a [label="Defined in Sub2" fontsize=10 color=blue] } }
- Block.node_define(id: ID, /, **attrs: ID | None) Self
Same as method
node(), except require the node to be undefined.- Parameters:
id – The node to define.
attrs – New attribute value assignments.
- Raises:
RuntimeError – The node is already defined.
Edge Methods
- Dot.edge_role(role: str, /, **attrs: ID | None) Self
Define an edge role or amend its attributes.
- Parameters:
role – The edge role to define or amend.
attrs – New or amending attribute value assignments.
- Block.edge_default(**attrs: ID | None) Self
Establish or amend default edge attributes.
- Parameters:
attrs – New or amending attribute value assignments.
- Block.edge(point1: ID | Port, point2: ID | Port, discriminant: ID | None = None, /, **attrs: ID | None) Self
Define an edge or amend its attributes and endpoints.
- Parameters:
point1 – The first edge endpoint, either a node identifier or a port. In the directed case, this is the tail of the arc.
point2 – The second edge endpoint, either a node identifier or a port. In the directed case, this is the head of the arc.
discriminant – A value allowing the application to refer to specific edges created in a multigraph. Discriminants may only be provided for multigraphs, but are not required for multigraphs. If provided, discriminants need only be unique for a given node pair. Discriminants do not appear in the DOT language representation.
attrs – New or amending attribute value assignments.
The Block object through which an edge is defined determines where in the DOT language representation the corresponding edge statement will appear. However, edge identity is global, so an edge may be amended through any Block object.
Consistent with the DOT language, only the
idportion of aPortis relevant to edge identification. In the code below, the firstedge()call defines an edge, and the second amends the same edge’s attributes.dot = Dot() dot.edge(Port("a",cp="n"), Port("b","output","s"), color="blue") dot.edge("a","b",style="dashed")
The outcome of calling
edge()for an endpoint node pair between which there is an existing edge depends on whether or not the Dot object is multigraph and the specified discriminant.Multigraph
Specified Discriminant
Outcome
No
(Not permitted)
Existing edge amended
Yes
None
New edge defined
Yes
Existing among node pair edges
Existing edge amended
Yes
New among node pair edges
New edge defined
When amending an edge, if an endpoint argument is a
Port, that specification replaces the endpoint’s previous port (if any). For example, the DOT representation ofdot = Dot() dot.edge(Port("a", cp="s"), Port("b", cp="s")) dot.edge(Port("a", cp="n"), "b")
includes the edge
a:n -- b:s.For non-directed graphs, amending an edge updates the edge’s endpoint order if the given order differs.
dot = Dot() dot.edge("a","b") # Define a non-directed edge between a and b. dot.edge("b","a") # Amend the edge
The Dot object above has the DOT language representation
graph { b -- a }
As in DOT, edge endpoint nodes need not be defined. The output of
dot = Dot() dot.edge("a","b",label="An example edge") print(dot,file=output_file)
will include an edge statement, but no node statements.
See also the Multigraphs discussion.
- Block.edge_define(point1: ID | Port, point2: ID | Port, discriminant: ID | None = None, /, **attrs: ID | None) Self
Same as method
edge(), except require the edge to be undefined.- Parameters:
- Raises:
RuntimeError – The edge is already defined.
Subgraph Methods
- Block.subgraph(id: ID | None = None) Block
Define or prepare to amend a subgraph.
- Parameters:
id – The subgraph to define or amend.
- Returns:
A new or existing Block object. Graph attributes, attribute defaults, and nodes and edges defined through the block appear within a subgraph statement of the enveloping Dot object’s DOT language representation.
Subgraph identities are scoped to parent graphs or subgraphs, so
dot = Dot(id="Name") dot.subgraph("Name").subgraph("Name").subgraph("Name")
raises no exceptions and has the DOT language representation
graph Name { subgraph Name { subgraph Name { subgraph Name { } } } }
See also the Subgraphs discussion.
- Block.subgraph_define(id: ID) Block
Same as
subgraph(), except require the subgraph to be undefined.- Parameters:
id – The subgraph to define.
- Raises:
RuntimeError – The subgraph is already defined.
- Block.subgraph_update(id: ID) Block
Same as
subgraph(), except require the subgraph to be defined.- Parameters:
id – The subgraph to amend.
- Raises:
RuntimeError – The subgraph is not defined.
Render Methods
- Dot.__str__() str
The DOT language representation of the Dot object.
- Raises:
RuntimeError – An assigned role is not defined.
See also the DOT language representation discussion.
- Dot.to_rendered(program: str | PathLike = 'dot', *, format='png', dpi: float | None = None, size: int | float | str | None = None, ratio: float | str | None = None, timeout: float | None = None, directory: str | PathLike | None = None) bytes
Render the Dot object by invoking a Graphviz program. The input to the program is the object’s DOT language representation.
- Parameters:
program – Which Graphviz program to use (dot by default).
programshould either be the name of the program or a path to the program.format – The output format desired (png by default).
to_rendered()converts the specified value to lowercase if it isn’t already, then uses it to form the-Targument to the specified program.dpi – Render with this many pixels per inch. See the Graphviz dpi attribute documentation.
size – Specify a maximum or minimum size. See the Graphviz size attribute documentation.
ratio – Set the aspect ratio. See the Graphviz ratio attribute documentation.
timeout – Limit the program execution time to this many seconds.
directory – If specified,
programis interpreted as a path relative todirectory.
- Returns:
The output bytes of the specified program.
- Raises:
InvocationException – Could not invoke the program, likely because it wasn’t found.
ProcessException – The invoked program exited with a non-zero status code.
ProcessExceptionobjects include the status code and stderr of the program as properties.TimeoutException – The invoked program took longer than
timeoutseconds to run and was killed.
If the process’s
PATHincludes directory/opt/graphviz/binand that is the only directory inPATHincluding Graphviz executables, the followingto_rendered()calls are equivalent:data = dot.to_rendered(program="circo") data = dot.to_rendered(program="/opt/graphviz/bin/circo") data = dot.to_rendered(program="circo", directory="/opt/graphviz/bin") data = dot.to_rendered(program="graphviz/bin/circo", directory="/opt")
- Dot.to_svg(program: str | PathLike = 'dot', *, inline=False, dpi: float | None = None, size: int | float | str | None = None, ratio: float | str | None = None, timeout: float | None = None, directory: str | PathLike | None = None) str
Convert the Dot object to an SVG string by invoking a Graphviz program.
- Parameters:
inline – Generate SVG without an XML header. Be aware that older, still commonly installed versions of Graphviz do not support inline SVG generation.
For the remaining parameters, and for the exceptions raised, see
to_rendered().
- Dot.save(filename: str | PathLike, program: str | PathLike = 'dot', *, exclusive: bool = False, format: str | None = None, dpi: float | None = None, size: int | float | str | None = None, ratio: float | str | None = None, timeout: float | None = None, directory: str | PathLike | None = None) None
Save a rendering of the Dot object to a file.
save()generates the file data by invoking a Graphviz program.- Parameters:
filename – The name of the file to write.
exclusive – Fail if the file already exists.
- Raises:
ValueError – The format was not specified and could not be inferred from the file extension.
FileExistsError – The file already exists and option
exclusiveis true.
For the remaining parameters, and for additional exceptions raised, see
to_rendered().Parameter
formatis optional. If not given,save()attempts to infer the format from the file extension. The file extensions for whichsave()infers formats by case insensitive comparison are.svg,.png,.jpg,.jpeg,.gif, and.pdf.
- Dot.show(program: str | PathLike = 'dot', *, format: str = 'svg', dpi: float | None = None, size: int | float | str | None = None, ratio: float | str | None = None, timeout: float | None = None, directory: str | PathLike | None = None) None
Display the Dot object in a Jupyter notebook as an IPython
SVGorImageobject.show()generates the data required by invoking a Graphviz program.- Raises:
ShowException –
show()could not complete because the program could not be invoked, it timed out, or it exited with a non-zero status code. Whenshow()raisesShowException, it also displays aMarkdownblock explaining why it could not complete.RuntimeError – IPython is not installed.
For the parameters, see
to_rendered(). Thesizeparameter can be especially useful: a value such as"5,5"can help ensure the graph visually fits in the notebook. Note the default format forshow()is'svg'.
- Dot.show_source() None
Display the Dot object’s DOT language representation in a Jupyter notebook as an IPython
Codeobject.- Raises:
RuntimeError – IPython is not installed.
Other Methods
- Dot.copy(*, id: ID | None = None, comment: str | None = None) Dot
Return a deep copy of the Dot object.
- Parameters:
id – The copy’s graph identifier. If not provided, the copy will have the Dot object’s graph identifier.
comment – The copy’s comment. If not provided, the copy will have the Dot object’s comment.
If the Dot object is using a theme, the copy will use the identical theme.
- Dot.all_role(role: str, /, **attrs: ID | None) Self
Define or amend the attributes of same-named graph, node, and edge roles all at once.
Executing
dot.all_role(role, **attrs)has the same effect as executingdot.graph_role(role, **attrs) dot.node_role(role, **attrs) dot.edge_role(role, **attrs)
- Block.all_default(**attrs: ID | None) Self
Establish or amend default graph, node, and edge attributes all at once.
Executing
block.all_default(**attrs)has the same effect as executingblock.graph_default(**attrs) block.node_default(**attrs) block.edge_default(**attrs)
Supporting Types
- type ID = str | int | float | bool | Markup | Nonce
Values corresponding to the DOT language non-terminal ID used for both entity identifiers and attribute values. Consistent with the grammar,
using an int
xas anIDis equivalent to usingstr(x)using a float
xas anIDis equivalent to usingstr(x)using
Markup(x)as anIDis different than usingx
For convenience, given that Graphviz uses
trueandfalsefor boolean values,using
Trueas anIDis equivalent to using"true"using
Falseas anIDis equivalent to using"false"
Nonce objects are placeholders for generated IDs. See
Nonce.
- class Markup(markup: str)
A Graphviz DOT language markup string.
Graphviz supports what it calls HTML strings such as
<x<sub>1</sub>>. Because in DOT language"<x<sub>1</sub>>"(note the quotes) is an ordinary non-HTML ID, gvdot usesMarkupto delineate HTML strings.- Parameters:
markup – The DOT language markup text excluding the opening and closing angle brackets.
- class Nonce(prefix: str = '_nonce')
A placeholder that
Dotresolves to a unique ID in DOT language representations.When generating the DOT language representation of a Dot object,
Dotresolves every Nonce that is part of the object or its theme chain to a DOT language ID, choosing IDs not used anywhere else in the object or theme chain.Dotresolves two Nonce objectsuandvto the same ID if and only ifu is v.- Parameters:
prefix –
Dotwill resolve the Nonce to an ID of the form prefix_n where prefix is the given value and n is a small positive integer.
Applications use Nonce objects to create identifiers that do not conflict with each other or with identifiers derived from input values. For example, an application might complete an illustration of a linked list with
nil = Nonce() dot.node(nil, role="nil") dot.edge(last_value, nil)
The DOT language representation would then include a node statement for
nillike_nonce_1 [label="NIL" fontname="sans-serif" fontsize=8 style=filled shape=box width=0 height=0 margin=0.02]
and, if
last_valueis"Fred", an edge statement likeFred -> _nonce_1
Dotdynamically resolves Nonce objects each time it generates a DOT language representation. Changing a Dot object may change the ID to which a Nonce object resolves.Nonce objects are
Hashableand objectsuandvcompare equal if and only ifu is v.See also the Nonces discussion.
- class Port(node: ID, name: ID | None = None, cp: str | None = None)
An edge endpoint. Graphviz allows endpoints to be specified as a node identifier, an optional port name, and an optional compass point. Properly speaking, in the DOT language grammar a port is the name and compass point components only, but for simplicity this class incorporates all three.
- Parameters:
node – The node identifier.
name – The optional port name.
cp – The optional compass point, which must be one of “n”, “ne” “e”, “se”, “s”, “sw”, “w”, “nw”, “c”, or “_”. Compass point “_” appears in the DOT grammar and is equivalent to None; it’s included for completeness.
Exceptions
- exception ProcessException(program: str, status: int, stderr: str | bytes)
A Graphviz program exited with a non-zero status code.
- exception TimeoutException(program: str, timeout: float, stderr: str | bytes)
A Graphviz program timed out.
- exception ShowException
Dot.show()could not complete.