Handle/catch RuntimeWarnings in connection with igraph python
Question: I am running the code

    
    
    testgraph = igraph.Graph.Degree_Sequence(degseq,method = "vl")
    

which sometimes throws the warning

    
    
    RuntimeWarning: Cannot shuffle graph, maybe there is only a single one? at gengraph_graph_molloy_hash.cpp:332
    

I would like to catch this warning, so I can stop working with degree
sequences that only have one graph.

I tried

    
    
    degseq = [1,2,2,3]
    try:
        testgraph = igraph.Graph.Degree_Sequence(degseq,method = "vl")
    except RuntimeWarning:
        print degseq
    else:
        print "go on"
    

which returns the warning and then "go on".

I tried upgrading the warning to an exception with

    
    
    warnings.simplefilter('error', 'Cannot shuffle graph')
    degseq = [1,2,2,3]
    try:
        testgraph = igraph.Graph.Degree_Sequence(degseq,method = "vl")
    except RuntimeWarning:
        print degseq
    else:
        print "go on"
    

among others, and now something weird happens! It returns

    
    
    testgraph = igraph.Graph.Degree_Sequence(degseq,method = "vl")
    MemoryError: Error at src/attributes.c:284: not enough memory to allocate attribute hashes, Out of memory
    

How do I make python catch the RuntimeWarning? And why does the new exception
occur when I upgrade the warning to an exception?


Answer: You can try this to catch all warnings during an igraph call:

    
    
    from warnings import catch_warnings
    with catch_warnings(record=True) as caught_warnings:
        testgraph = igraph.Graph.Degree_Sequence(degseq, method="vl")
        if caught_warnings:
            # caught_warnings is a list of warnings; do something with them here
    

Regarding the `MemoryError` that you see: it is actually a bug in the Python
interface of igraph. Internally, the C core of the igraph library (which does
not know anything about the host language it is embedded in) raises a warning
for your degree sequence. This is then turned into a Python warning, which is
then turned into an exception by your warning handler. However, the C core of
the igraph library does not anticipate that igraph core warnings are sometimes
turned into exceptions so it happily proceeds with the execution of the code
for `Graph.Degree_Sequence`, notices the warning-that-was-turned-into-an-
exception a few internal calls later, and wrongly attributes it to the failure
of some other memory allocation (that has nothing to do with your original
warning).

