Reloading a function within a module

寵の児 提交于 2019-12-25 01:58:59

问题


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 started writing my own modules, I made great use of the reload() function in python 2.7.

I reproduced my issue in a simple example

  • I create a folder called: demo
  • Inside demo, I place two files: __init__.py and plotme.py

My __init__.py file contains:

from .plotme import plot

My plotme.py file contains:

import matplotlib.pyplot as plt
import numpy as np

def plot():
    x=np.linspace(0,np.pi*4,1000)
    y=np.cos(x)
    plt.plot(x,y,'b')

I run it with the commands:

>>> import demo
>>> demo.plot()

and it works just fine.

Next, I decide that I want the plot to be red, not blue. I modify 'b' to 'r' in plotme.py and save. I then type:

>>> import(demo)
>>> demo.plot()

and the plot is still blue, not red. Not what I want. Instead I try:

>>> reload(demo)
>>> demo.plot()

and again, the color has not updated.

I figure that there needs to be a reload command inside \__init__.py. I try updating it to:

from .plotme import plot
reload(plot)

and when I type:

>>> reload(demo)

I get the error:

TypeError: reload() argument must be module

I instead try reloading with reload(.plotme). Same error. When I try reload(plotme), it doesn't throw an error, but the color of the plot isn't updating to red.

How do I fix this?

I would prefer not to have to close and relaunch the interpreter every time I modify a few lines of code.


回答1:


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

from .plotme import plot
reload(plot)
from .plotme import 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?




回答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.




回答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)


来源:https://stackoverflow.com/questions/48038180/reloading-a-function-within-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!