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.

5. Package imports. Import your file from a package. Create a subdirectory calledmypkg nested in a directory on your module import search path, move themymod.py module file you created in exercise 1 or 3 into the new directory, andtry to import it with a package import of the form import mypkg.mymod.You’ll need to add an _ _init_ _.py file in the directory your module was movedto make this go, but it should work on all major <strong>Python</strong> platforms (that’s part ofthe reason <strong>Python</strong> uses “.” as a path separator). The package directory you createcan be simply a subdirectory of the one you’re working in; if it is, it will befound via the home directory component of the search path, and you won’t haveto configure your path. Add some code to your _ _init_ _.py, and see if it runs oneach import.6. Reloads. Experiment with module reloads: perform the tests in Chapter 19’schanger.py example, changing the called function’s message, and/or behaviorrepeatedly, without stopping the <strong>Python</strong> interpreter. Depending on your system,you might be able to edit changer in another window, or suspend the <strong>Python</strong>interpreter, and edit in the same window (on Unix, a Ctrl-Z key combinationusually suspends the current process, and an fg command later resumes it).7. Circular imports. * In the section on recursive import gotchas, importing recur1raised an error. But, if you restart <strong>Python</strong>, and import recur2 interactively, theerror doesn’t occur—test and see this for yourself. Why do you think it works toimport recur2, but not recur1? (Hint: <strong>Python</strong> stores new modules in the built-insys.modules table (a dictionary) before running their code; later imports fetch themodule from this table first, whether the module is “complete” yet or not.) Now,try running recur1 as a top-level script file: python recur1.py. Do you get thesame error that occurs when recur1 is imported interactively? Why? (Hint: whenmodules are run as programs, they aren’t imported, so this case has the sameeffect as importing recur2 interactively; recur2 is the first module imported.)What happens when you run recur2 as a script?* Note that circular imports are extremely rare in practice. In fact, this author has never coded or come acrossa circular import in a decade of <strong>Python</strong> coding. On the other hand, if you can understand why they are apotential problem, you know a lot about <strong>Python</strong>’s import semantics.Part V Exercises | 447

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

Saved successfully!

Ooh no, something went wrong!