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: Block

A DOT language builder.

Parameters:
  • directed – Make the graph directed.

  • strict – Include the strict keyword. This argument is present for completeness. It’s unlikely to be useful with Dot objects since Dot guarantees 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(), and edge_update().

  • id – The graph identifier.

  • comment – Possibly multiline text prepended as a // style comment.

Raises:

ValueError – If both strict and multigraph are True.

class Block

A scope for graph and default attribute assignments and a container for node, edge, and subgraph definitions.

Block is the base class of Dot.

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 graph or digraph form. The remaining Block objects are those returned by methods subgraph() or subgraph_define().

Blocks should only be created by calling Dot(), subgraph(), or subgraph_define(). Executing Block() directly raises a RuntimeError.

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 of theme are ignored.

Dot forms 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 theme is 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.

Block.graph_default(**attrs: ID | None) Self

Establish or amend default graph attributes.

Parameters:

attrs – New or amending attribute value assignments.

Block.graph(**attrs: ID | None) Self

Establish or amend graph attributes.

Parameters:

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.

Block.node_update(id: ID, /, **attrs: ID | None) Self

Same as method node(), except require the node to be defined.

Parameters:
  • id – The node to amend.

  • attrs – Amending attribute value assignments.

Raises:

RuntimeError – The node is not defined.

Block.node_is_defined(id: ID) bool

Return True iff the identified node is defined.

Parameters:

id – The node to test.

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 id portion of a Port is relevant to edge identification. In the code below, the first edge() 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 of

dot = 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.

Block.edge_update(point1: ID | Port, point2: ID | Port, discriminant: ID | None = None, /, **attrs: ID | None) Self

Same as method edge(), except require the edge to be defined.

Parameters:
Raises:

RuntimeError – The edge is not defined.

Block.edge_is_defined(point1: ID | Port, point2: ID | Port, discriminant: ID | None = None) bool

Return True iff the identified edge is defined.

Parameters:

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). program should 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 -T argument 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, program is interpreted as a path relative to directory.

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. ProcessException objects include the status code and stderr of the program as properties.

  • TimeoutException – The invoked program took longer than timeout seconds to run and was killed.

If the process’s PATH includes directory /opt/graphviz/bin and that is the only directory in PATH including Graphviz executables, the following to_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 exclusive is true.

For the remaining parameters, and for additional exceptions raised, see to_rendered().

Parameter format is optional. If not given, save() attempts to infer the format from the file extension. The file extensions for which save() 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 SVG or Image object. show() generates the data required by invoking a Graphviz program.

Raises:
  • ShowExceptionshow() could not complete because the program could not be invoked, it timed out, or it exited with a non-zero status code. When show() raises ShowException, it also displays a Markdown block explaining why it could not complete.

  • RuntimeError – IPython is not installed.

For the parameters, see to_rendered(). The size parameter can be especially useful: a value such as "5,5" can help ensure the graph visually fits in the notebook. Note the default format for show() is 'svg'.

Dot.show_source() None

Display the Dot object’s DOT language representation in a Jupyter notebook as an IPython Code object.

Raises:

RuntimeError – IPython is not installed.

Other Methods

Dot.is_multigraph() bool

Return True iff this is a multigraph Dot object.

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 executing

dot.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 executing

block.graph_default(**attrs)
block.node_default(**attrs)
block.edge_default(**attrs)
Block.parent() Block | None

Return the parent Block object, if there is one. Otherwise return None.

Block.dot() Dot

Return the enveloping Dot object.

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 x as an ID is equivalent to using str(x)

  • using a float x as an ID is equivalent to using str(x)

  • using Markup(x) as an ID is different than using x

For convenience, given that Graphviz uses true and false for boolean values,

  • using True as an ID is equivalent to using "true"

  • using False as an ID is 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 uses Markup to 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 Dot resolves to a unique ID in DOT language representations.

When generating the DOT language representation of a Dot object, Dot resolves 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. Dot resolves two Nonce objects u and v to the same ID if and only if u is v.

Parameters:

prefixDot will 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 nil like

_nonce_1 [label="NIL" fontname="sans-serif" fontsize=8 style=filled
    shape=box width=0 height=0 margin=0.02]

and, if last_value is "Fred", an edge statement like

Fred -> _nonce_1

Dot dynamically 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 Hashable and objects u and v compare equal if and only if u 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 InvocationException(program: str)

An attempt to run a Graphviz program failed.

program: str

The program that could not be run.

exception ProcessException(program: str, status: int, stderr: str | bytes)

A Graphviz program exited with a non-zero status code.

program: str

The program that ran.

status: int

The program’s non-zero exit status code.

stderr: str

Text the program wrote to stderr.

exception TimeoutException(program: str, timeout: float, stderr: str | bytes)

A Graphviz program timed out.

program: str

The program that timed out.

timeout: float

The timeout value.

stderr: str

Text the program wrote to stderr before timing out.

exception ShowException

Dot.show() could not complete.