super() function in Python raises a TypeError

Playing with class inheritance, I came across an unexpected behavior of super() function, which is used in the inheritance process.

Consider this simple example of a class MyGraph thah inherits from a DiGraph class from networkx:

import networkx as nx
 
class MyGraph(nx.DiGraph):
 
    def __init__(self, data):
        super(MyGraph, self).__init__()
        self.data = data

Then, you can create an instance as follows:

a = MyGraph([1,2,3])

and everything works as expected. However, when I reloaded the module after some changes (or not), and tried to instantiate again, I got this error message:

TypeError: super(type, obj): obj must be an instance or subtype of type

Looking on the web, it appears that the problem resides in the mechanism of reloading modules. Reloading a module often changes the internal object in memory which makes the isinstance test of super return False. Indeed, if you use a print statement to check if the instance is an instance of MyGraph, a False is returned !!

I haven’t yet found a solution to this issue. More information related to this topic can be found in the
reload section of Python documentation

Solution and thorough explanation can be found in this good post on this subject.

Follow-up and solution: In the example above, I was reloading not only the module that causes problem but also another module. It appears, that the order matters ! I used :

If I inverse the reload order, then everything seems to work as expected...

Please follow and like us:
This entry was posted in Python and tagged , . Bookmark the permalink.

7 Responses to super() function in Python raises a TypeError

Leave a Reply

Your email address will not be published. Required fields are marked *