12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

• Reloads impact all clients that use import to fetch modules. Because clients thatuse import qualify to fetch attributes, they’ll find new values in the moduleobject after a reload.• Reloads impact future from clients only. Clients that used from to fetchattributes in the past won’t be affected by a reload; they’ll still have references tothe old objects fetched before the reload.reload ExampleHere’s a more concrete example of reload in action. In the following example, we’llchange and reload a module file without stopping the interactive <strong>Python</strong> session.Reloads are used in many other scenarios, too (see the sidebar “Why You Will Care:Module Reloads”), but we’ll keep things simple for illustration here. First, in the texteditor of your choice, write a module file named changer.py with the followingcontents:message = "First version"def printer( ):print messageThis module creates and exports two names—one bound to a string, and another toa function. Now, start the <strong>Python</strong> interpreter, import the module, and call the functionit exports. The function will print the value of the global message variable:% python>>> import changer>>> changer.printer( )First versionKeeping the interpreter active, now edit the module file in another window:...modify changer.py without stopping <strong>Python</strong>...% vi changer.pyChange the global message variable, as well as the printer function body:message = "After editing"def printer( ):print 'reloaded:', messageThen, return to the <strong>Python</strong> window, and reload the module to fetch the new code.Notice in the following interaction that importing the module again has no effect; weget the original message, even though the file’s been changed. We have to call reloadin order to get the new version:...back to the <strong>Python</strong> interpreter/program...>>> import changer>>> changer.printer( ) # No effect: uses loaded moduleFirst versionReloading Modules | 411

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

Saved successfully!

Ooh no, something went wrong!