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.

from threenames import a, b, c # Copy multiple names>>> b, c('parrot', 'sketch')The results here are printed in parentheses because they are really tuples (a kind ofobject covered in the next part of this book).Once you start coding modules with multiple names like this, the built-in dir functionstarts to come in handy. You can use it to fetch a list of the names availableinside a module:>>> dir(threenames)['_ _builtins_ _', '_ _doc_ _', '_ _file_ _', '_ _name_ _', 'a', 'b', 'c']When the dir function is called with the name of an imported module passed inparentheses like this, it returns all the attributes inside that module. Some of thenames it returns are names you get “for free”: names with leading and trailing doubleunderscores are built-in names that are always predefined by <strong>Python</strong>, and thathave special meaning to the interpreter. The variables our code defined by assignment—a,b, and c—show up last in the dir result.Modules and namespacesModule imports are a way to run files of code, but, as we’ll discuss later in the book,modules are also the largest program structure in <strong>Python</strong> programs. In general,<strong>Python</strong> programs are composed of multiple module files, linked together by importstatements. Each module file is a self-contained package of variables—that is, anamespace. One module file cannot see the names defined in another file unless itexplicitly imports that other file, so modules serve to minimize name collisions inyour code—because each file is a self-contained namespace, the names in one filecannot clash with those in another, even if they are spelled the same way.In fact, as you’ll see, modules are one of a handful of ways that <strong>Python</strong> goes to greatlengths to package your variables into compartments to avoid name clashes. We’lldiscuss modules and other namespace constructs (including classes and functionscopes) further later in the book. For now, modules will come in handy as a way torun your code many times without having to retype it.import and reload Usage NotesFor some reason, once people find out about running files using import and reload,many tend to focus on this alone and forget about other launch options that alwaysrun the current version of the code (e.g., icon clicks, IDLE menu options, and systemcommand lines). This can quickly lead to confusion—you need to rememberwhen you’ve imported to know if you can reload, you need to remember to useparentheses when you call reload (only), and you need to remember to use reload inthe first place to get the current version of your code to run.Module Imports and Reloads | 49

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

Saved successfully!

Ooh no, something went wrong!