Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

pycharm - How do I reload a module after changing it?

Python Console with Python 3.4.2

I defined a function in a module which runs correctly in Python Console in PyCharm Community Edition 4.5.4:
ReloadTest.py:

def reloadtest(x):
    print("Version A: {}".format(x))

Python Console:

Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on win32
>>> from ReloadTest import reloadtest
>>> reloadtest(1)
Version A: 1   

After I modified the function to "Version B", PyCharm can't find the change, and importlib.reload(ReloadTest) gives me error.
I must reload the Python Console or restart PyCharm every time I modify a module. What did I do wrong? What is the best way to handle this?

ReloadTest.py:

def reloadtest(x):
    print("Version B: {}".format(x))

Python Console:

>>> reloadtest(1)
Version A: 1
>>> from ReloadTest import reloadtest
>>> reloadtest(1)
Version A: 1
>>> import importlib
>>> importlib.reload(ReloadTest)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'ReloadTest' is not defined
>>> from ReloadTest import reloadtest
>>> reloadtest(1)
Version A: 1
>>> import ReloadTest
>>> reloadtest(1)
Version A: 1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I took me some time to understand the previous answer... And also, that answer is not very practical if the chuck of code you need to run is in the middle of a script that you do not feel like modifying for running it once.

You can simply do:

import importlib
importlib.reload(my_module)
from my_module import my_function

Then, you can run your code with the updated version of the function.

Works with PyCharm Community Edition 2016.3.2

Edit w.r.t. first comment: This only works if you first imported the module itself (otherwise you get an error as said in the first comment).

import my_module
from my_module import my_function
# Now calls a first version of the function
# Then you change the function
import importlib
importlib.reload(my_module)
from my_module import my_function
# Now calls the new version of the function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...