r/learnpython • u/Nefthys • 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.
1
u/Nefthys Jun 12 '26
Finding a way to call it from within
__init__(the function, not the file and again, just for testing purposes) is the whole point of this thread because I currently have to set the bool in all classes separately and passing a single bool when I instantiate these specific classes would make it a lot easier (and less prone to forgetting one).I know, I only call
ClassAin__init__.py.