add tag
5 years ago anoldmaninthesea

I have defined a class with a mistake.

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.

Top Answer
5 years ago halloleo

How to reload a class definition depends where you define the class:

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

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

  3. 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):

    And then you import this file as a module (e.g. in the REPL) with:

    (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 a NameError. So you change the class in first_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):

    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.

Enter question or answer id or url (and optionally further answer ids/urls from the same question) from

Separate each id/url with a space. No need to list your own answers; they will be imported automatically.