12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

doesn’t help in every situation, but where it does, it makes for a much shorter developmentcycle. For instance, imagine a database program that must connect to aserver on startup; because program changes or customizations can be tested immediatelyafter reloads, you need to connect only once while debugging.Because <strong>Python</strong> is interpreted (more or less), it already gets rid of the compile/linksteps you need to go through to get a C program to run: modules are loaded dynamicallywhen imported by a running program. Reloading offers a further performanceadvantage by allowing you to also change parts of running programs without stopping.Note that reload currently only works on modules written in <strong>Python</strong>; compiledextension modules coded in a language such as C can be dynamically loaded at runtime,too, but they can’t be reloaded.reload BasicsUnlike import and from:• reload is a built-in function in <strong>Python</strong>, not a statement.• reload is passed an existing module object, not a name.Because reload expects an object, a module must have been previously imported successfullybefore you can reload it (if the import was unsuccessful, due to a syntax orother error, you may need to repeat it before you can reload the module). Furthermore,the syntax of import statements and reload calls differs: reloads requireparentheses, but imports do not. Reloading looks like this:import module# Initial import...use module.attributes...... # Now, go change the module file...reload(module)# Get updated exports...use module.attributes...The typical usage pattern is that you import a module, then change its source code ina text editor, and then reload it. When you call reload, <strong>Python</strong> rereads the modulefile’s source code, and reruns its top-level statements. Perhaps the most importantthing to know about reload is that it changes a module object in-place; it does notdelete and re-create the module object. Because of that, every reference to a moduleobject anywhere in your program is automatically affected by a reload. Here are thedetails:• reload runs a module file’s new code in the module’s current namespace. Rerunninga module file’s code overwrites its existing namespace, rather than deletingand re-creating it.• Top-level assignments in the file replace names with new values. For instance,rerunning a def statement replaces the prior version of the function in the module’snamespace by reassigning the function name.410 | Chapter 19: Module Coding Basics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!