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.

We’ve also provided self-test logic at the bottom of this module, which narcissisticallyimports and lists itself. Here’s the sort of output produced:C:\python> python mydir.py------------------------------name: mydir file: mydir.py------------------------------00) _ _file_ _ 01) _ _name_ _ 02) listing 03) _ _doc_ _ 04) _ _builtins_ _ 05) verbose 1------------------------------mydir has 6 names------------------------------We’ll meet getattr and its relatives again later. The point to notice here is that mydiris a program that lets you browse other programs. Because <strong>Python</strong> exposes its internals,you can process objects generically. *Module GotchasIn this section, we’ll take a look at the usual collection of boundary cases that makelife interesting for <strong>Python</strong> beginners. Some are so obscure that it was hard to comeup with examples, but most illustrate something important about the language.Statement Order Matters in Top-Level CodeWhen a module is first imported (or reloaded), <strong>Python</strong> executes its statements oneby one, from the top of the file to the bottom. This has a few subtle implicationsregarding forward references that are worth underscoring here:• Code at the top level of a module file (not nested in a function) runs as soon as<strong>Python</strong> reaches it during an import; because of that, it can’t reference namesassigned lower in the file.• Code inside a function body doesn’t run until the function is called; becausenames in a function aren’t resolved until the function actually runs, they canusually reference names anywhere in the file.* Tools such as mydir.listing can be preloaded into the interactive namespace by importing them in the filereferenced by the PYTHONSTARTUP environment variable. Because code in the startup file runs in the interactivenamespace (module _ _main_ _), importing common tools in the startup file can save you some typing. SeeAppendix A for more details.Module Gotchas | 437

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

Saved successfully!

Ooh no, something went wrong!