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.

ChapterCHAPTER2121Advanced Module Topics 21This chapter concludes Part V with a collection of more advanced module-relatedtopics—relative import syntax, data hiding, the _ _future_ _ module, the _ _name_ _variable, sys.path changes, and so on—along with the standard set of gotchas andexercises related to what we’ve covered in this part of the book. Like functions, modulesare more effective when their interfaces are well defined, so this chapter alsobriefly reviews module design concepts, some of which we have explored in priorchapters.Despite the word “advanced” in this chapter’s title, some of the topics discussed here(such as the _ _name_ _ trick) are widely used, so be sure you take a look before movingon to classes in the next part of the book.Data Hiding in ModulesAs we’ve seen, a <strong>Python</strong> module exports all the names assigned at the top level of itsfile. There is no notion of declaring which names should and shouldn’t be visibleoutside the module. In fact, there’s no way to prevent a client from changing namesinside a module if it wants to.In <strong>Python</strong>, data hiding in modules is a convention, not a syntactical constraint. If youwant to break a module by trashing its names, you can, but fortunately, I’ve yet tomeet a programmer who would. Some purists object to this liberal attitude towarddata hiding, and claim that it means <strong>Python</strong> can’t implement encapsulation. However,encapsulation in <strong>Python</strong> is more about packaging than about restricting.Minimizing from * Damage: _X and _ _all_ _As a special case, you can prefix names with a single underscore (e.g., _X) to preventthem from being copied out when a client imports a module’s names with a from *statement. This really is intended only to minimize namespace pollution; because426

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

Saved successfully!

Ooh no, something went wrong!