0

In module 1:

class Parent(object):
    def my_method(self):
        print 'Hello World'


class Child(Parent):
    def __init__(self, name):
        self.name = name

    def my_method(self):
        # Do something
        super(Child, self).my_method()
        # Do something more


import sys
sys.modules[__name__] = Child(__name__)

In module 2:

import module1
module1.my_method()

Loading module2 fails.

Result:

File "c:\archive2\stack\module2.py", line 3, in <module>
  module1.my_method()
File "c:\archive2\stack\module1.py", line 12, in my_method
  super(Child, self).my_method()

TypeError: super() argument 1 must be type, not None

Looks like the value of variables Child and Parent is None when module2 is executed.

A similar problem was asked in this question. Is there a generic solution for accessing method of parent class when child class is not available in global namespace?

Vinayak Kaniyarakkal
  • 1,110
  • 17
  • 23
  • 1
    I tried, but I can't make this code "fail" (whatever that means, exactly). I don't see any reason why assigning an object into `sys.modules` should make your class stop working. Please provide a [mcve]. – Aran-Fey Mar 26 '18 at 09:28
  • @Aran-Fey: I have edited with more details. I believe now it can be reproduced. – Vinayak Kaniyarakkal Mar 26 '18 at 09:38
  • It seems like you have a bug in the my_method function under the child class, should be : super(Parent, self).my_method() – Rohi Mar 26 '18 at 09:41
  • @Rohi: No, it should be Parent.my_method(self) of super(Child, self).my_method() – Vinayak Kaniyarakkal Mar 26 '18 at 09:44
  • 2
    @Rohi No, that's not how you use `super`. `super(Child, self)` is correct. – Aran-Fey Mar 26 '18 at 09:44
  • @VinayakKaniyarakkal Can you add the error message to your question, please? – Aran-Fey Mar 26 '18 at 09:44
  • https://pastebin.com/rvcquhqm Seems like the value of variables Child and Parent is None at my_method when this code is executed. – Vinayak Kaniyarakkal Mar 26 '18 at 09:47
  • Please [edit] it into the question. It makes your question better and makes it easier for people to help you. – Aran-Fey Mar 26 '18 at 09:48
  • Possible duplicate of [imported modules becomes None when replacing current module in sys.modules using a class object](https://stackoverflow.com/questions/29107470/imported-modules-becomes-none-when-replacing-current-module-in-sys-modules-using) – Aran-Fey Mar 26 '18 at 09:50
  • 1
    Your module is being garbage collected because you removed it from `sys.modules`. The easy workaround is to save a reference to the module before you overwrite it: `_ = sys.modules[__name__]; sys.modules[__name__] = Child(__name__)`. Also, this workaround isn't necessary upwards of python 3.4. – Aran-Fey Mar 26 '18 at 09:52

0 Answers0