How can I reload a Python module on the *first* attempt?



  • Re: Working with modules

    The post above gives a very helpful suggestion of how to reload modules while working on a script, but I have a question.

    Question

    I can only get modules to reload on the second time I run a script.

    For example, here's a project setup:

    myScript
    ├── __init__.py
    ├── myScript.py
    └── helpers
        ├── __init__.py
        └── myScriptHelper.py
    

    myScriptHelper.py looks like this:

    def testReload():
        print("hello, I'm reloaded")
    

    And myScript.py looks like this:

    import importlib
    import helpers
    from helpers.myScriptHelper import *
    
    print("hello from myScript")
    
    importlib.reload(helpers.myScriptHelper)
    testReload()
    

    So, I would expect to see "hello, I'm reloaded" in the Output Window when I run myScript.py. However, I'm finding that I only end up seeing updates to myScriptHelper.py on the second time I run myScript.py after making any changes.

    Example

    I run myScript.py. In the Output, I see this:

    hello from myScript
    hello, I'm reloaded
    

    Next, I change myScriptHelper.py to this:

    def testReload():
        print("hello, I'm REALLY reloaded")
    

    However, when I run myScript.py again, I see the same output again:

    hello from myScript
    hello, I'm reloaded
    hello from myScript
    hello, I'm reloaded
    

    It's only when I run myScript.py again a second time that I see the output of the updated module:

    hello from myScript
    hello, I'm reloaded
    hello from myScript
    hello, I'm reloaded
    hello from myScript
    hello, I'm REALLY reloaded
    

    Have I missed a step, or is it expected that it should take two runs of a script for importlib.reload() to take effect?

    Thanks for any help here! I know this is a tiny question, but I'm trying to learn how to do the little things right so I can be more effective overall. :)


  • admin

    hello @ArrowType,

    to update a module you need to reload it before you import stuff from it:

    import importlib
    import helpers.myScriptHelper
    importlib.reload(helpers.myScriptHelper)
    
    from helpers.myScriptHelper import *
    
    print("hello from myScript")
    testReload()
    

    also, unless you wish to run some code when the module is imported, you don’t really need to include empty __init__.py files to indicate namespace packages in Python 3.

    hope this helps! cheers



  • Ahhh, that makes sense now.

    That’s a good tip about __init.py__ as well.

    Thank you so much for your help, Gustavo!


Log in to reply