dgl.add_self_loop(g, etype=None)[source]

Add self-loops for each node in the graph and return a new graph.

  • g (DGLGraph) – The graph.

  • etype (str or (str, str, str), optional) –

    The type names of the edges. The allowed type name formats are:

    • (str, str, str) for source node type, edge type and destination node type.

    • or one str edge type name if the name can uniquely identify a triplet format in the graph.

    Can be omitted if the graph has only one type of edges.


The graph with self-loops.

Return type



  • The function only supports homogeneous graphs or heterogeneous graphs but the relation graph specified by the etype argument is homogeneous.

  • The function adds self-loops regardless of whether they already exist or not. If one wishes to have exactly one self-loop for every node, call remove_self_loop() before invoking add_self_loop().

  • Features of the new edges (self-loop edges) will be filled with zeros.


>>> import dgl
>>> import torch

Homogeneous Graphs

>>> g = dgl.graph((torch.tensor([0, 0, 2]), torch.tensor([2, 1, 0])))
>>> g.ndata['hv'] = torch.arange(3).float().reshape(-1, 1)
>>> g.edata['he'] = torch.arange(3).float().reshape(-1, 1)
>>> g = dgl.add_self_loop(g)
>>> g
Graph(num_nodes=3, num_edges=6,
    ndata_schemes={'hv': Scheme(shape=(1,), dtype=torch.float32)}
    edata_schemes={'he': Scheme(shape=(1,), dtype=torch.float32)})
>>> g.edata['he']

Heterogeneous Graphs

>>> g = dgl.heterograph({
...     ('user', 'follows', 'user'): (torch.tensor([1, 2]),
...                                   torch.tensor([0, 1])),
...     ('user', 'plays', 'game'): (torch.tensor([0, 1]),
...                                 torch.tensor([0, 1]))})
>>> g = dgl.add_self_loop(g, etype='follows')
>>> g
Graph(num_nodes={'user': 3, 'game': 2},
    num_edges={('user', 'plays', 'game'): 2, ('user', 'follows', 'user'): 5},
    metagraph=[('user', 'user'), ('user', 'game')])