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.

In simple terms, every file of <strong>Python</strong> source code whose name ends in a .py extensionis a module. Other files can access the items a module defines by importing thatmodule; import operations essentially load another file, and grant access to that file’scontents. The contents of a module are made available to the outside world throughits attributes (a term I’ll define in the next section).This module-based services model turns out to be the core idea behind programarchitecture in <strong>Python</strong>. Larger programs usually take the form of multiple modulefiles, which import tools from other module files. One of the modules is designatedas the main or top-level file, and is the one launched to start the entire program.We’ll delve into such architectural issues in more detail later in this book. This chapteris mostly interested in the fact that import operations run the code in a file that isbeing loaded as a final step. Because of this, importing a file is yet another way tolaunch it.For instance, if you start an interactive session (in IDLE, from a command line, orotherwise), you can run the script4.py file you created earlier with a simple import:D:\LP3E\Examples> c:\python25\python>>> import script4win321267650600228229401496703205376This works, but only once per session (really, process), by default. After the firstimport, later imports do nothing, even if you change and save the module’s sourcefile again in another window:>>> import script4>>> import script4This is by design; imports are too expensive an operation to repeat more than onceper program run. As you’ll learn in Chapter 18, imports must find files, compile tobyte code, and run the code.If you really want to force <strong>Python</strong> to run the file again in the same session (without stoppingand restarting the session), you need to instead call the built-in reload function:>>> reload(script4)win3265536>>>The reload function loads and runs the current version of your file’s code if you’vechanged it in another window. This allows you to edit and pick up new code on thefly within the current <strong>Python</strong> interactive session. In this session, for example, the secondprint statement in script4.py was changed in another window to print 2**16between the time of the first import and the reload call.46 | Chapter 3: How You Run Programs

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

Saved successfully!

Ooh no, something went wrong!