Details about modules.

Working in an interactive Python, it's very important to know about modules. Every file you edit must be imported as a module (or run as a script) before you can run it. Now, what happens if you import a file, and then change it?

The system has a special, obscure way to remember the details of each module that has been loaded. The "import" statement only makes the name of the module available. If your main program (call it "circus.py") contains the statement, "import flying", then editing the file flying.py will not change the behavior of your circus. Even saving the file won't be enough (unless flying has never been imported, by anything, since you started PythonWin).

Once a module has been imported, the only way to change it is by executing a reload statement, as in "reload(flying)". This will reload the module from the disk file. Note: any name that was in flying, but is not in the new version, will still keep its old meaning. If you delete "def ni(): ..." from flying, and then reload, you'll still have flying.ni() available... until you quit PythonWin and restart. This can cause confusion. Avoid it with "del flying.ni". See that little button in the toolbar, three rectangles and an arrow? It's called "Import/Reload". Develop the habit of clicking it Every Time You Make A Change. Trust me, you'll be confused until you learn to do this. Develop another habit: every time you click that button, look down at the status bar. That's how you know if you have an error which prevents the module from reloading (and again, your program will keep exhibiting old behavior). Note: This only reloads the file in the topmost window! And there's no warning when a window hasn't been reloaded!

To be specific, the Import/Reload button saves your file for you if it's unsaved. Then, if it's never been imported, it imports it into the top level (module __main__). But if it has been imported, it does a reload()--and makes sure that its name is added to module __main__.

A couple other features: If you click Import/Reload or Run when the Interactive Window is topmost, you'll be asked what to load. You can load a file that's not in Python's search path, and this will add that directory to the path.

For more on modules, check out Help Index; Main Python Documentation; Library Reference; 2.3 Built-In Functions; reload(). Also, Help Index; Main Python Documentation; Language Reference; Contents; 6.11 The import statement. Oh yes, I promised to talk about the underscores in "if __name__=='__main__':". Well, every module has a variable called __name__ that tells what its name is. The interactive window uses a module which has the name "__main__". So this is a test to see whether the file is running as a script (from the running-figure tool) or being loaded as a module (from an "import" statement or the Import/Reload button). PythonWin makes it easy to use a file either way.