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.

import recur1Traceback (innermost last):File "", line 1, in ?File "recur1.py", line 2, in ?import recur2File "recur2.py", line 2, in ?from recur1 import YImportError: cannot import name Y# Error: "Y" not yet assigned<strong>Python</strong> avoids rerunning recur1’s statements when they are imported recursivelyfrom recur2 (or else the imports would send the script into an infinite loop), butrecur1’s namespace is incomplete when imported by recur2.The solution? Don’t use from in recursive imports (no, really!). <strong>Python</strong> won’t getstuck in a cycle if you do, but your programs will once again be dependent on theorder of the statements in the modules.There are two ways out of this gotcha:• You can usually eliminate import cycles like this by careful design—maximizingcohesion, and minimizing coupling are good first steps.• If you can’t break the cycles completely, postpone module name accesses byusing import and qualification (instead of from), or by running your froms eitherinside functions (instead of at the top level of the module), or near the bottom ofyour file to defer their execution.Chapter SummaryThis chapter surveyed some more advanced module-related concepts. We studieddata hiding techniques, enabling new language features with the _ _future_ _ module,the _ _name_ _ usage mode variable, package-relative import syntax, and more.We also explored and summarized module design issues, and looked at commonmistakes related to modules to help you avoid them in your code.The next chapter begins our look at <strong>Python</strong>’s object-oriented programming tool, theclass. Much of what we’ve covered in the last few chapters will apply there, too—classes live in modules, and are namespaces as well, but they add an extra componentto attribute lookup called “inheritance search.” As this is the last chapter in this partof the book, however, before we dive into that topic, be sure to work through thispart’s set of lab exercises. And, before that, here is this chapter’s quiz to review thetopics covered here.444 | Chapter 21: Advanced Module Topics

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

Saved successfully!

Ooh no, something went wrong!