Reloading modules

  • Steve Jones - SSC Editor

    SSC Guru

    Points: 715841

    Comments posted to this topic are about the item Reloading modules

  • Stewart "Arturius" Campbell

    SSC Guru

    Points: 71399

    Interesting, thanks Steve
    Learned something new

    ____________________________________________
    Space, the final frontier? not any more...
    All limits henceforth are self-imposed.
    “libera tute vulgaris ex”

  • marsigme

    SSCommitted

    Points: 1792

    I failed to come up with the correct answer given the steps listed.
    When I tried to reload the module using...

    from importlib import reload
    reload(sample)

    I received the following error:

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'sample' is not defined

    Checking the names in the current scope I had the following.

    >>> dir()
    ['TwiceThePrice', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']

    The reload error makes more sense now...the initial import statement only imports the TwiceThePrice function definition from the sample module. The importlib's reload function only works on modules as noted by the following error...

    >>> reload(TwiceThePrice)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "C:\winroot\usr\bin\python\lib\importlib\__init__.py", line 122, in reload
      raise TypeError("reload() argument must be module")
    TypeError: reload() argument must be module

    In order to get the preferred answer, I tweaked the REPL commands as follows.

    >>> import sample
    >>>
    >>> sample.TwiceThePrice(42)
    84
    >>>
    >>> from importlib import reload
    >>> reload(sample)
    <module 'sample' from 'C:\\Users\\username\\workspaces\\python.wksp\\importTest\\sample.py'>
    >>>
    >>> sample.TwiceThePrice(42)
    $84

    Thanks for the question...I enjoyed spending a little time playing with Python!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply