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:
error
This entry was posted in Python and tagged , . Bookmark the permalink.

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

  1. Juanpablo says:

    what is the CNOGraph var?

    • admin says:

      a typo… should be the name of the class of course (MyGraph). It does not affect the issue raised in the post though. Thanks for spotting the typo. T.

  2. JB says:

    Thank you for this solution, I was stuck with my pytorch code because of the order I reload the files in my jupyter notebook …

  3. coder says:

    In Python 3, using the new `super().__init__()` instead of `super(Derived, self).__init__()` solves the problem.
    Source: https://stackoverflow.com/a/52898473/2476373

Leave a Reply

Your email address will not be published.