I have defined a class with a mistake.
xxxxxxxxxx
class FirstClass:
def setdata(self,value):
self.data=value
def display(Tupac): # the first argument is ALWAYS the instance being called.
print(Tupa.data) # we just call it self by mere convention. In this class I called it Tupac
Without noticing it, I ran the above, with the wrong object (Tupa.data instead of Tupac.data). So, I corrected the code above changing Tupa.data to Tupac.data, and tried to rerun the code. However, the new definition didn’t load. Therefore, I tried using this answer with autoreload but it didn’t solve the problem, because it seems I should have called autoreload before running the class definition.
Therefore, how would I go about solving this?
Edit: In my case, I’m stating the class definitions in a Jupyter notebook, the same where I’m working on, and running other calls.
How to reload a class definition depends where you define the class:
-
If you define it in the REPL (e.g. after starting Python on the command line with
python3
), you can just write the whole definition again with the change and it overwrites the old definition. -
If you define the class in a Jupyter notebook session, the situation is the same: Just type the whole corrected definition again in a new cell. It will overwrite the old definition. Make sure not only to retype the
display
method, but the whole class. -
The more common case is that you define the class in a file. So say you have defined your class in a file
first_class.py
with the follwoing cotent (containing the error):xxxxxxxxxx
class FirstClass:
def setdata(self,value):
self.data=value
def display(Tupac):
print(Tupa.data)
And then you import this file as a module (e.g. in the REPL) with:
xxxxxxxxxx
>>> import first_class
(Note that in the line above “
>>>
” just stands for the REPL prompt and should not be entered.)Now you notice that calling the
display
method causes aNameError
. So you change the class infirst_class.py
and save the file.But this is not enough. The REPL still holds the old definition in its memory. So you need to tell the REPL to reload the file. Do it in Python 3 like this (in the REPL):
xxxxxxxxxx
>>> import importlib # importlib is a module from the standard library
>>> importlib.reload(first_class)
Now a call to the
display
method should work (if you had corrected the definition in the file.)
For more info on the imp
module in he standard library see here.