Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reimport a module in python while interactive

Tags:

python

I know it can be done, but I never remember how.

How can you reimport a module in python? The scenario is as follows: I import a module interactively and tinker with it, but then I face an error. I fix the error in the .py file and then I want to reimport the fixed module without quitting python. How can I do it ?

like image 616
Stefano Borini Avatar asked Aug 10 '09 11:08

Stefano Borini


People also ask

Can you Unimport a module Python?

You can use https://pypi.org/project/unimport/, it can find and remove unused imports for you.

How do I reimport a file in Python?

1 Answer. You can re-import a module in python, by using the importlib and its function reload.


1 Answers

For Python 3.4+:

import importlib importlib.reload(nameOfModule) 

For Python < 3.4:

reload(my.module) 

From the Python docs

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.

Don't forget the caveats of using this method:

  • When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem, but if the new version of a module does not define a name that was defined by the old version, the old definition is not removed.

  • If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

  • If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

like image 171
Benjamin Wohlwend Avatar answered Sep 22 '22 03:09

Benjamin Wohlwend