How to reload elegantly

Hi there

What would you do if you have a file like that defines the same name class Debugger and you want to import and reload it?
This works, but it seems a bit verbose to me.

import Debugger
    from importlib import reload
except ImportError:
from Debugger import Debugger

I want to know if any, more pythonic ways. Any IDEA?

Many people would say that reloading is never Pythonic, you should exit
the interpreter and start it again.

Otherwise, using importlib.reload is the correct solution.

Why do you need to reload? The “best way” to reload will depend on why
you want to reload, and your code snippet doesn’t make it clear why you
are doing it.

If the purpose is for the Debugger module to clear its caches and any
globals, you would be better off creating a “cleanup()” function that
does that.

Your code snippet has some problems.

  1. You import the Debugger module, which you then immediately reload,
    which seems pointless.

  2. You have an unneccessary try…except guard around the line
    from importlib import reload. It is unneccessary because it will
    always succeed in Python 3.

  3. But if it doesn’t succeed, your code snippet goes ahead and tries to
    use reload() anyway. So catching the import error was pointless.

(Don’t catch any error you can’t actually deal with.)

  1. After reloading the module, you then use from Debugger import Debugger, which replaces the name Debugger (a module) with a class.
    That means that if you go to reload it for a second time, reload will
    fail with the rather confusing error:

    ImportError: module Debugger not in sys.modules

(Because Debugger the class is not the same as module Debugger, which is
in sys.modules.)

Hi, Steven

Thank you very much for your reply.
The try…catch statement is necessary for the PY2-backward compatibility for my case. But this was unnecessary for now, and sorry for the confusion. Let me ask by simplifying my code again.

The code snippet is a header part of the module ‘’ that is a plugin module of my GUI application. Reload is required because I want to reload the plugin every time I edit without restarting the GUI. (one of the reasons I :heart: python is, right this reload feature, no matter who says reloading is never Pythonic!).

At the realoding time, I want to reload Debugger class too.

  • Case.1
>>> from Debugger import Debugger
>>> reload(Debugger)

As you mentioned, this fails in TypeError: reload() argument must be a module

  • Case.2
>>> import Debugger
>>> reload(Debugger)

This is ok, but I have to type in my app plugin.Debugger.Debugger instead of plugin.Debugger.

  • Case.3
>>> import Debugger
>>> reload(Debugger)
>>> from Debugger import Debugger

This is ok too, and the best I can do for now. However, this seems a bit verbose to me.
In addition, the flake8 complains me ‘E402 module level import not at top of file’.
It goes back to my first question.