Skip to content Skip to sidebar Skip to footer

Reloading A Function Within A Module

Goal I would like to import a custom module from the interpreter, run it, modify it, reload it, and run it again to see the changes. Background I'm using python 2.7. Before I st

Solution 1:

At @MoinuddinQuadri 's suggestion, I updated my __init__.py file to contain:

from .plotmeimport plot
reload(plot)
from .plotmeimport plot

and it works. It's a tad cumbersome as my end application will have a LOT of independent functions to load, but it works. Thanks, MoinuddinQuadri.

Does anyone have other suggestions? If I have 20 functions, it's a bit tedious to write this out 20 times. Is there a way to reload all functions quickly?

Solution 2:

You must reload both demo module (i.e. the file demo/__init__.py) **and** the filedemo/plotme.pywhich isdemo.plotme. More precisely, as you importplotfunction from theplotmesub module, you must import firstplotmeand thendemo`:

reload(demo.plotme)
reload(demo)

After those 2 commands, any changes in plotme will be taken into account.

Solution 3:

related:

How do I unload (reload) a Python module?Why are there dummy modules in sys.modules?

my answer:

import sys
for n in filter(lambda x: x.startswith('demo') and x != 'demo', sys.modules):
    del(sys.modules[n])
reload(demo)

Post a Comment for "Reloading A Function Within A Module"