How do I make ipython aware of changes made to a selfwritten module?

前端 未结 3 1360
忘掉有多难
忘掉有多难 2021-01-01 01:55

When trying a selfwritten module, it is likely to end with errors at the first few times.

But when fixing these errors, ipython does not seem to notice that.

相关标签:
3条回答
  • 2021-01-01 02:10

    This is not just for ipython , but Python in general caches a module when it is first imported into sys.modules . So after the first import, whenever you try to import it, you would get the cached module object from sys.modules .

    To make Python reload the module object without having to restart Python, so that changes done to the module are reflected, you should use reload() built-in function (Python 2.x) or importlib.reload() (Python 3.x).

    Python 2.x -

    <module> = reload(<module>)
    

    Example -

    import module
    module = reload(module) #This requires the module as it is, not a string.
    

    Python 3.x -

    import importlib
    <module> = importlib.reload(<module>)
    

    Similar to Python 2.x example above, just use importlib.reload() instead of reload()

    0 讨论(0)
  • 2021-01-01 02:19

    There is an Ipython specific way, you can use set up autoreload:

    In [1]: %load_ext autoreload
    
    In [2]: %autoreload 2
    
    In [3]: from foo import some_function
    
    In [4]: some_function()
    Out[4]: 42
    
    In [5]: # open foo.py in an editor and change some_function to return 43
    
    In [6]: some_function()
    Out[6]: 43
    

    The module was reloaded without reloading it explicitly, and the object imported with from foo import ... was also updated.

    Usage The following magic commands are provided:

    %autoreload

    Reload all modules (except those excluded by %aimport) automatically now.

    %autoreload 0

    Disable automatic reloading.

    %autoreload 1

    Reload all modules imported with %aimport every time before executing the >Python code typed.

    %autoreload 2

    Reload all modules (except those excluded by %aimport) every time before executing the Python code typed.

    %aimport

    List modules which are to be automatically imported or not to be imported.

    %aimport foo

    Import module ‘foo’ and mark it to be autoreloaded for %autoreload 1

    %aimport -foo

    Mark module ‘foo’ to not be autoreloaded.

    There is also dreload which will work for python2 and 3.

     dreload(module)
    
    0 讨论(0)
  • 2021-01-01 02:23

    When you kill the IPython notebook server and restart it, you will have a new kernel instance which does not persist with your notebook itself. You should start your workflow right after opening your notebook by running all cells. In the top menu, select "Cell->Run all"

    0 讨论(0)
提交回复
热议问题