Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload a module's function in Python?

Following up on this question regarding reloading a module, how do I reload a specific function from a changed module?

pseudo-code:

from foo import bar  if foo.py has changed:     reload bar 
like image 316
Jonathan Livni Avatar asked Sep 01 '11 13:09

Jonathan Livni


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 reload a .PY file?

import importlib import inputs #import the module here, so that it can be reloaded. importlib. reload(inputs) from inputs import A # or whatever name you want. import inputs #import the module here, so that it can be reloaded.


2 Answers

As of today, the proper way of doing this is:

import sys, importlib importlib.reload(sys.modules['foo']) from foo import bar 

Tested on python 2.7, 3.5, 3.6.

like image 84
Antony Hatchkins Avatar answered Sep 24 '22 10:09

Antony Hatchkins


What you want is possible, but requires reloading two things... first reload(foo), but then you also have to reload(baz) (assuming baz is the name of the module containing the from foo import bar statement).

As to why... When foo is first loaded, a foo object is created, containing a bar object. When you import bar into the baz module, it stores a reference to bar. When reload(foo) is called, the foo object is blanked, and the module re-executed. This means all foo references are still valid, but a new bar object has been created... so all references that have been imported somewhere are still references to the old bar object. By reloading baz, you cause it to reimport the new bar.


Alternately, you can just do import foo in your module, and always call foo.bar(). That way whenever you reload(foo), you'll get the newest bar reference.

NOTE: As of Python 3, the reload function needs to be imported first, via from importlib import reload

like image 35
Eli Collins Avatar answered Sep 26 '22 10:09

Eli Collins