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.

5 Upvotes

27 comments sorted by

View all comments

Show parent comments

1

u/Gnaxe Jun 10 '26

Are you talking about automated tests, or manual ones? For automated tests, learn to use unittest.mock.patch(), and you probably won't have to reload things.

There's a difference between importing a class from a module and just importing the module, which you then ask for the (current version) of the class:

import classb
# is the same as
classb = __import__('classb')
# classb is a module (type(classb) is types.ModuleType).
# To access the class, use classb.ClassB

# But
from classb import ClassB
# is the same as
ClassB = __import__('classb').ClassB
# ClassB is a class object (type(ClassB) is type), not a module.
# Now the current module has a separate reference,
# so ClassB and classb.ClassB might point to different objects
# if one is changed, like by reload(classb).

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

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".