Search code examples
pythonigraphgoogle-colaboratory

python-igraph "'bytes' object has no attribute 'encode'" when plotting in Colab


I'm unable to plot anything using python-igraph in Google Colab despite having apt-installed libcairo2-dev and pip-installed cairocffi.

I'd like to use igraph in a project in Colab, specifically to plot graphs and node-communities. The installation steps go trough without erros. But when I try to draw a simple graph, I get an error from igraph/drawing/__init__.py about utf-8 encoding. Having swapped pycairo for cairocffi, I get the same error.

!sudo apt install build-essential python-dev libxml2 libxml2-dev zlib1g-dev libcairo2-dev
!pip install cairocffi python-igraph
import igraph as ig
g = ig.Graph(edges=[(0,1)])
ig.plot(g)

No plot appears, and I get:

AttributeError                            Traceback (most recent call last)

/usr/local/lib/python3.6/dist-packages/IPython/core/formatters.py in __call__(self, obj)
    336             method = get_real_method(obj, self.print_method)
    337             if method is not None:
--> 338                 return method()
    339             return None
    340         else:

/usr/local/lib/python3.6/dist-packages/igraph/drawing/__init__.py in _repr_svg_(self)
    352         surface.finish()
    353         # Return the raw SVG representation
--> 354         return io.getvalue().encode("utf-8")
    355 
    356     @property

AttributeError: 'bytes' object has no attribute 'encode'

<igraph.drawing.Plot at 0x7f6b34afb160>

Solution

  • Following the explanation by @Silmathoron, I have swapped !pip install cairocffi python-igraph in my original question for

    !pip install cairocffi
    !pip download python-igraph
    !tar -xf python-igraph-0.7.1.post6.tar.gz
    with open("python-igraph-0.7.1.post6/igraph/drawing/__init__.py", 'r') as file:
      text = file.read()
    assert text[14797:14803] == 'encode'
    with open("python-igraph-0.7.1.post6/igraph/drawing/__init__.py", 'w') as file:
      file.write(text[:14797] + "decode" + text[14803:])
    !pip install --no-index --find-links="." python-igraph
    

    which have solved the problem. (Colab had hung for a strangely long time at the last pip install though.)