How do I reload a module after changing it?

后端 未结 4 1833
太阳男子
太阳男子 2020-12-09 09:51

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:

相关标签:
4条回答
  • 2020-12-09 10:23

    You can instruct Pycharm to automatically reload modules upon changing by adding the following lines to settings->Build,Excecution,Deployment->Console->Python Console in the Starting Script:

    %load_ext autoreload
    %autoreload 2
    

    This function comes from IPython as described here: Reloading submodules in IPython

    0 讨论(0)
  • 2020-12-09 10:26

    Get it to work!
    Instead of from Module import function, I should import the whole module import Module, then call the function by Module.function(). This is because

    from ReloadTest import reloadtest
    

    and

    importlib.reload(ReloadTest)
    

    can't go together.

    >>> import ReloadTest
    >>> ReloadTest.reloadtest(1)
    Version A: 1
    

    After making changes:

    >>> importlib.reload(ReloadTest)
    <module 'ReloadTest' from 'C:\\...\\ReloadTest.py'>
    >>> ReloadTest.reloadtest(2)
    Version B: 2
    
    0 讨论(0)
  • 2020-12-09 10:31

    Since this question asked specifically about PyCharm, please check out the answer on the PyCharm Support site. This answer is almost identical to @wokbot's, the distinction is that PyCharm removes the need to import importlib. It also uses the from ... import ... trick after import ... to make typing easier if you plan to use reloadtest frequently.

    In[2]: import ReloadTest
    In[3]: from ReloadTest import reloadtest
    In[4]: reloadtest(1)
    Out[4]: Version A: 1
    

    ...make changes

    In[5]: reload(ReloadTest)
    Out[5]: <module 'ReloadTest' from 'C:\\...\\ReloadTest.py'>
    In[6]: from ReloadTest import reloadtest
    In[7] reloadtest(2)
    Out[7]Version B: 2
    
    0 讨论(0)
  • 2020-12-09 10:33

    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
    
    0 讨论(0)
提交回复
热议问题