Home > database >  How to instantiate and extend Python igraph Vertex class
How to instantiate and extend Python igraph Vertex class

Time:04-05

I'd like to extend the igraph Vertex class with some extra variables methods I need for a simulation study. However, when I try to import and extend the vertex class, I get an error.

from igraph import Vertex

v = Vertex()

TypeError: cannot create 'igraph.Vertex' instances

Likewise, the same error occurs when I try to extend the class.

from igraph import Vertex

class MyVertex(Vertex):

    def __init__(self):
        super().__init__()

my_vertex = MyVertex()

TypeError: cannot create 'MyVertex' instances

How can I instantiate igraph vertices and extend the igraph Vertex class?

CodePudding user response:

Vertex instances are not meant to be instantiated; this is intentional. A Vertex is simply a wrapper around a reference to a graph and a vertex index, and it provides a few convenience methods that are usually just proxies to the same method on the associated graph instance. Even if you created your own Vertex subclass, there is currently no way to tell an igraph Graph object to start returning your Vertex subclass for expressions like graph.vs[x] instead of Vertex itself.

If you want to create your own vertex-like classes, you can try composition instead of inheritance, i.e. you create a MyVertex class that takes a Vertex as its constructor argument, stores the vertex and then forwards method calls to it, depending on what you need to support in your own MyVertex instance:

class MyVertex:
    def __init__(self, v):
        self._v = v

    def degree(self, *args, **kwds):
        return self._v.degree(*args, **kwds)
    
    ...

Note that since Vertex instances are simply wrappers for a graph and a vertex ID, things can get confusing if you remove vertices from a graph because the remaining vertices are re-indexed by the underlying C library to ensure that their IDs are always in the range [0; n-1] for n vertices.

  • Related