Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reimporting a single function in python

Using python in an interactive mode one imports a module then if the module is changed (a bug fix or something) one can simply use the reload() command.

But what if I didn't import the entire module and used the 'from M import f,g' import statement. Is there any way to reimport only g?

(I tried removing the function from the parameter table by 'del g' AND delete the .pyc file from the directory. It didn't help. when I reimported the function 'from M import g' the old g was loaded).

like image 773
ScienceFriction Avatar asked Dec 08 '10 09:12

ScienceFriction


People also ask

How do you reload a function in Python?

You can't reload a method from a module but you can load the module again with a new name, say foo2 and say bar = foo2. bar to overwrite the current reference.

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.

How the reload () operation is executed in Python?

When reload() is executed: Python module's code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module's dictionary by reusing the loader which originally loaded the module. The init function of extension modules is not called a second time.

How do I reload a Jupyter module?

Simple solution: Use the autoreload to make sure the latest version of the module is used. The autoreloading module is not enabled by default. So you have to load it as an extension. And each time you execute some code, IPython will reimport all the modules to make sure that you are using the latest possible versions.


1 Answers

When you do a from foo import bar, you are importing the entire module. You are just making a copy of the symbol bar in the current namespace. You are not importing just the function.

The reload function is not totally reliable (e.g. it will not work for compiled C modules). I would recommend that you exit and restart your interpreter.

like image 160
Noufal Ibrahim Avatar answered Sep 27 '22 20:09

Noufal Ibrahim