python refresh/reload python refresh/reload python python

python refresh/reload


It's unclear what you mean with "refresh", but the normal behavior of Python is that you need to restart the software for it to take a new look on a Python module and reread it.

If your changes isn't taken care of even after restart, then this is due to one of two errors:

  1. The timestamp on the pyc-file is incorrect and some time in the future.
  2. You are actually editing the wrong file.

You can with reload re-read a file even without restarting the software with the reload() command. Note that any variable pointing to anything in the module will need to get reimported after the reload. Something like this:

import themodulefrom themodule import AClassreload(themodule)from themodule import AClass


One way to do this is to call reload.

Example: Here is the contents of foo.py:

def bar():    return 1

In an interactive session, I can do:

>>> import foo>>> foo.bar()1

Then in another window, I can change foo.py to:

def bar():    return "Hello"

Back in the interactive session, calling foo.bar() still returns 1, until I do:

>>> reload(foo)<module 'foo' from 'foo.py'>>>> foo.bar()'Hello'

Calling reload is one way to ensure that your module is up-to-date even if the file on disk has changed. It's not necessarily the most efficient (you might be better off checking the last modification time on the file or using something like pyinotify before you reload), but it's certainly quick to implement.

One reason that Python doesn't read from the source module every time is that loading a module is (relatively) expensive -- what if you had a 300kb module and you were just using a single constant from the file? Python loads a module once and keeps it in memory, until you reload it.


I used the following when importing all objects from within a module to ensure web2py was using my current code:

import buttonsimport tablereload(buttons)reload(table)from buttons import *from table import *