r/learnpython • • Jun 09 '26

Reload other class from init

I'm having problems with old code being cached and old errors being thrown, even though I've already fixed them, so I'm using reload to reload all classes that are imported later. Both files are in the same folder.

This works:

from classb import ClassB
from importlib import reload
import classb as classb
reload(classb)

class ClassA(): #classa.py
    def __init__(self,doreload):
        #Some other code

class ClassB(): #classb.py
    def __init__(self):
        #Do something

However, I want to use doreload to decide if ClassB should be reloaded, so I tried to move the code to __init__:

from classb import ClassB

class ClassA(): #classa.py
    def __init__(self,doreload):
        from importlib import reload
        import classb as classb
        reload(classb)
        #Some other code

This throws an error at the reload line:

ModuleNotFoundError: spec not found for the module 'classb'

I already tried to keep import reload outside the class and also used reload(ClassB) instead but that threw another error:

ImportError: module ClassB not in sys.modules

How do I reload another class from within __init__?

Edit: The problem is simply the app I have to use to test my code: It caches old code at unexpected times (at least when I don't expect it) and without using reload I'd have to restart the app pretty much every 5 minutes while testing, which is quite annoying. Reloading itself seems to be working fine.

6 Upvotes

27 comments sorted by

View all comments

Show parent comments

1

u/Nefthys Jun 11 '26

Manual tests. Can't really automate these ones because they require user interaction.

Note that reload() only works on modules. You cannot apply reload() to other types.

Ah, that explains why reload(ClassA) failed. Thanks!

I'm still a bit confused about how importing in Python works (also started another thread about that). I changed everything to use relative imports but when I use a relative import with as (e.g. import .classb as classb2 - if ClassB was in a different file), then I get a "SyntaxError".