id
int64
0
25.6k
text
stringlengths
0
4.59k
600
casesyou can witness the effect of program change nearly as fast as you can type it of coursedevelopment cycle turnaround is only one aspect of python' ease of use it also provides deliberately simple syntax and powerful built-in tools in factsome have gone so far as to call python executable pseudocode because it eliminates much of the complexity in other toolspython programs are simplersmallerand more flexible than equivalent programs in other popular languages it' relatively easy to learn this brings us to the point of this bookespecially when compared to other widely used programming languagesthe core python language is remarkably easy to learn in factif you're an experienced programmeryou can expect to be coding small-scale python programs in matter of daysand may be able to pick up some limited portions of the language in just hours--though you shouldn' expect to become an expert quite that fast (despite what you may have heard from marketing departments!naturallymastering any topic as substantial as today' python is not trivialand we'll devote the rest of this book to this task but the true investment required to master python is worthwhile--in the endyou'll gain programming skills that apply to nearly every computer application domain moreovermost find python' learning curve to be much gentler than that of other programming tools that' good news for professional developers seeking to learn the language to use on the jobas well as for end users of systems that expose python layer for customization or control todaymany systems rely on the fact that end users can learn enough python to tailor their python customization code onsitewith little or no support moreoverpython has spawned large group of users who program for fun instead of careerand may never need full-scale software development skills although python does have advanced programming toolsits core language essentials will still seem relatively simple to beginners and gurus alike it' named after monty python okthis isn' quite technical strengthbut it does seem to be surprisingly well-kept secret in the python world that wish to expose up front despite all the reptiles on python books and iconsthe truth is that python is named after the british comedy group monty python--makers of the bbc comedy series monty python' flying circus and handful of later full-length filmsincluding monty python and the holy grailthat are still widely popular today python' original creator was fan of monty pythonas are many software developers (indeedthere seems to be sort of symmetry between the two fields python & session
601
the traditional "fooand "barfor generic variable names become "spamand "eggsin the python world the occasional "brian,"ni,and "shrubberylikewise owe their appearances to this namesake it even impacts the python community at largesome events at python conferences are regularly billed as "the spanish inquisition all of this isof coursevery funny if you are familiar with the showsbut less so otherwise you don' need to be familiar with monty python' work to make sense of examples that borrow references from itincluding many you will see in this bookbut at least you now know their root (hey-- 've warned you how does python stack up to language xfinallyto place it in the context of what you may already knowpeople sometimes compare python to languages such as perltcland java this section summarizes common consensus in this department want to note up front that ' not fan of winning by disparaging the competition-it doesn' work in the long runand that' not the goal here moreoverthis is not zero sum game--most programmers will use many languages over their careers neverthelessprogramming tools present choices and tradeoffs that merit consideration after allif python didn' offer something over its alternativesit would never have been used in the first place we talked about performance tradeoffs earlierso here we'll focus on functionality while other languages are also useful tools to know and usemany people find that pythonis more powerful than tcl python' strong support for "programming in the largemakes it applicable to the development of larger systemsand its library of application tools is broader is more readable than perl python has clear syntax and simplecoherent design this in turn makes python more reusable and maintainableand helps reduce program bugs is simpler and easier to use than java and cpython is scripting languagebut java and cboth inherit much of the complexity and syntax of larger oop systems languages like +is simpler and easier to use than +python code is simpler than the equivalent +and often one-third to one-fifth as largethough as scripting languagepython sometimes serves different roles is simpler and higher-level than python' detachment from underlying hardware architecture makes code less complexbetter structuredand more approachable than cc++' progenitor how does python stack up to language
602
is richer language that is used more widelyand its open source nature means it is not controlled by single company is more readable and general-purpose than php python is used to construct websites toobut it is also applied to nearly every other computer domainfrom robotics to movie animation and gaming is more powerful and general-purpose than javascript python has larger toolsetand is not as tightly bound to web development it' also used for scientific modelinginstrumentationand more is more readable and established than ruby python syntax is less clutteredespecially in nontrivial codeand its oop is fully optional for users and projects to which it may not apply is more mature and broadly focused than lua python' larger feature set and more extensive library support give it wider scope than luaan embedded "gluelanguage like tcl is less esoteric than smalltalklispand prolog python has the dynamic flavor of languages like thesebut also has traditional syntax accessible to both developers and end users of customizable systems especially for programs that do more than scan text filesand that might have to be read in the future by others (or by you!)many people find that python fits the bill better than any other scripting or programming language available today furthermoreunless your application requires peak performancepython is often viable alternative to systems development languages such as cc++and javapython code can often achieve the same goalsbut will be much less difficult to writedebugand maintain of courseyour author has been card-carrying python evangelist since so take these comments as you may (and other languagesadvocatesmileage may vary arbitrarilythey dohoweverreflect the common experience of many developers who have taken time to explore what python has to offer summary and that concludes the "hypeportion of this book in this we've explored some of the reasons that people pick python for their programming tasks we've also seen how it is applied and looked at representative sample of who is using it today my goal is to teach pythonthoughnot to sell it the best way to judge language is to see it in actionso the rest of this book focuses entirely on the language details we've glossed over here the next two begin our technical introduction to the language in themwe'll explore ways to run python programspeek at python' byte code execution modeland introduce the basics of module files for saving code the goal will be to give you python & session
603
won' really start programming per se until but make sure you have handle on the startup details before moving on test your knowledgequiz in this edition of the bookwe will be closing each with quick open-book quiz about the material presented herein to help you review the key concepts the answers for these quizzes appear immediately after the questionsand you are encouraged to read the answers once you've taken crack at the questions yourselfas they sometimes give useful context in addition to these end-of-quizzesyou'll find lab exercises at the end of each part of the bookdesigned to help you start coding python on your own for nowhere' your first quiz good luckand be sure to refer back to this material as needed what are the six main reasons that people choose to use python name four notable companies or organizations using python today why might you not want to use python in an application what can you do with python what' the significance of the python import this statement why does "spamshow up in so many python examples in books and on the web what is your favorite colortest your knowledgeanswers how did you dohere are the answers came up withthough there may be multiple solutions to some quiz questions againeven if you're sure of your answeri encourage you to look at mine for additional context see the text for more details if any of these responses don' make sense to you software qualitydeveloper productivityprogram portabilitysupport librariescomponent integrationand simple enjoyment of thesethe quality and productivity themes seem to be the main reasons that people choose to use python googleindustrial light magicccp gamesjet propulsion labsmayaesriand many more almost every organization doing software development uses python in some fashionwhether for long-term strategic product development or for short-term tactical tasks such as testing and system administration python' main downside is performanceit won' run as quickly as fully compiled languages like and +on the other handit' quick enough for most applicationsand typical python code runs at close to speed anyhow because it invokes test your knowledgeanswers
604
linked-in code in the interpreter if speed is criticalcompiled extensions are available for number-crunching parts of an application you can use python for nearly anything you can do with computerfrom website development and gaming to robotics and spacecraft control this was mentioned in footnoteimport this triggers an easter egg inside python that displays some of the design philosophies underlying the language you'll learn how to run this statement in the next "spamis reference from famous monty python skit in which people trying to order food in cafeteria are drowned out by chorus of vikings singing about spam ohand it' also common variable name in python scripts blue noyellow(see the prior answer python is engineeringnot art when python first emerged on the software scene in the early sit spawned what is now something of classic conflict between its proponents and those of another popular scripting languageperl personallyi think the debate is tired and unwarranted today--developers are smart enough to draw their own conclusions stillthis is one of the most common topics ' asked about on the training roadand underscores one of the main reasons people choose to use pythonit seems fitting to say few brief words about it here the short story is thisyou can do everything in python that you can in perlbut you can read your code after you do it that' it--their domains largely overlapbut python is more focused on producing readable code for manythe enhanced readability of python translates to better code reusability and maintainabilitymaking python better choice for programs that will not be written once and thrown away perl code is easy to writebut can be difficult to read given that most software has lifespan much longer than its initial creationmany see python as the more effective tool the somewhat longer story reflects the backgrounds of the designers of the two languages python originated with mathematician by trainingwho seems to have naturally produced an orthogonal language with high degree of uniformity and coherence perl was spawned by linguistwho created programming tool closer to natural languagewith its context sensitivities and wide variability as well-known perl motto statesthere' more than one way to do it given this mindsetboth the perl language and its user community have historically encouraged untethered freedom of expression when writing code one person' perl code can be radically different from another' in factwriting uniquetricky code is often source of pride among perl users but as anyone who has done any substantial code maintenance should be able to attestfreedom of expression is great for artbut lousy for engineering in engineeringwe need minimal feature set and predictability in engineeringfreedom of expression can lead to maintenance nightmares as more than one perl user has confided to methe result of too much freedom is often code that is much easier to rewrite from scratch than to modify this is clearly less than ideal python & session
605
themselvesthe prospect of someone else changing their work later doesn' enter into it this is critical difference between art and engineering when people write softwarethey are not writing it for themselves in factthey are not even writing primarily for the computer rathergood programmers know that code is written for the next human being who has to read it in order to maintain or reuse it if that person cannot understand the codeit' all but useless in realistic development scenario in other wordsprogramming is not about being clever and obscure--it' about how clearly your program communicates its purpose this readability focus is where many people find that python most clearly differentiates itself from other scripting languages because python' syntax model almost forces the creation of readable codepython programs lend themselves more directly to the full software development cycle and because python emphasizes ideas such as limited interactionscode uniformityand feature consistencyit more directly fosters code that can be used long after it is first written in the long runpython' focus on code quality in itself boosts programmer productivityas well as programmer satisfaction python programmers can be wildly creativetooof courseand as we'll seethe language does offer multiple solutions for some tasks-sometimes even more than it should todayan issue we'll confront head-on in this book too in factthis sidebar can also be read as cautionary talequality turns out to be fragile stateone that depends as much on people as on technology python has historically encouraged good engineering in ways that other scripting languages often did notbut the rest of the quality story is up to you at leastthat' some of the common consensus among many people who have adopted python you should judge such claims for yourselfof courseby learning what python has to offer to help you get startedlet' move on to the next test your knowledgeanswers
606
how python runs programs this and the next take quick look at program execution--how you launch codeand how python runs it in this we'll study how the python interpreter executes programs in general will then show you how to get your own programs up and running startup details are inherently platform-specificand some of the material in these two may not apply to the platform you work onso more advanced readers should feel free to skip parts not relevant to their intended use likewisereaders who have used similar tools in the past and prefer to get to the meat of the language quickly may want to file some of these away as "for future reference for the rest of uslet' take brief look at the way that python will run our codebefore we learn how to write it introducing the python interpreter so fari've mostly been talking about python as programming language butas currently implementedit' also software package called an interpreter an interpreter is kind of program that executes other programs when you write python programthe python interpreter reads your program and carries out the instructions it contains in effectthe interpreter is layer of software logic between your code and the computer hardware on your machine when the python package is installed on your machineit generates number of components--minimallyan interpreter and support library depending on how you use itthe python interpreter may take the form of an executable programor set of libraries linked into another program depending on which flavor of python you runthe interpreter itself may be implemented as programa set of java classesor something else whatever form it takesthe python code you write must always be run by this interpreter and to enable thatyou must install python interpreter on your computer
607
windows users fetch and run self-installing executable file that puts python on their machines simply double-click and say yes or next at all prompts linux and mac os users probably already have usable python preinstalled on their computers--it' standard component on these platforms today some linux and mac os users (and most unix userscompile python from its full source code distribution package linux users can also find rpm filesand mac os users can find various macspecific installation packages other platforms have installation techniques relevant to those platforms for instancepython is available on cell phonestabletsgame consolesand ipodsbut installation details vary widely python itself may be fetched from the downloads page on its main websitepython org it may also be found through various other distribution channels keep in mind that you should always check to see whether python is already present before installing it if you're working on windows and earlieryou'll usually find python in the start menuas captured in figure - we'll discuss the menu options shown here in the next on unix and linuxpython probably lives in your /usr directory tree because installation details are so platform-specificwe'll postpone the rest of this story here for more details on the installation processconsult appendix for the purposes of this and the nexti'll assume that you've got python ready to go program execution what it means to write and run python script depends on whether you look at these tasks as programmeror as python interpreter both views offer important perspectives on python programming the programmer' view in its simplest forma python program is just text file containing python statements for examplethe following filenamed script pyis one of the simplest python scripts could dream upbut it passes for fully functional python programprint('hello world'print( * this file contains two python print statementswhich simply print string (the text in quotesand numeric expression result ( to the power to the output stream don' worry about the syntax of this code yet--for this we're interested only how python runs programs
608
button menu this can vary across releasesbut idle starts development guiand python starts simple interactive session also here are the standard manuals and the pydoc documentation engine (module docssee and appendix for pointers on windows and other platforms in getting it to run 'll explain the print statementand why you can raise to the power in python without overflowingin the next parts of this book you can create such file of statements with any text editor you like by conventionpython program files are given names that end in pytechnicallythis naming scheme is required only for files that are "imported"-- term clarified in the next -but most python files have py names for consistency after you've typed these statements into text fileyou must tell python to execute the file--which simply means to run all the statements in the file from top to bottomone after another as you'll see in the next you can launch python program files by shell command linesby clicking their iconsfrom within idesand with other standard techniques if all goes wellwhen you execute the fileyou'll see the results of the two print statements show up somewhere on your computer--by defaultusually in the same window you were in when you ran the programprogram execution
609
for examplehere' what happened when ran this script from command prompt window' command line on windows laptopto make sure it didn' have any silly typosc:\codepython script py hello world see for the full story on this processespecially if you're new to programmingwe'll get into all the gory details of writing and launching programs there for our purposes herewe've just run python script that prints string and number we probably won' win any programming awards with this codebut it' enough to capture the basics of program execution python' view the brief description in the prior section is fairly standard for scripting languagesand it' usually all that most python programmers need to know you type code into text filesand you run those files through the interpreter under the hoodthougha bit more happens when you tell python to "go although knowledge of python internals is not strictly required for python programminga basic understanding of the runtime structure of python can help you grasp the bigger picture of program execution when you instruct python to run your scriptthere are few steps that python carries out before your code actually starts crunching away specificallyit' first compiled to something called "byte codeand then routed to something called "virtual machine byte code compilation internallyand almost completely hidden from youwhen you execute program python first compiles your source code (the statements in your fileinto format known as byte code compilation is simply translation stepand byte code is lower-levelplatform-independent representation of your source code roughlypython translates each of your source statements into group of byte code instructions by decomposing them into individual steps this byte code translation is performed to speed execution --byte code can be run much more quickly than the original source code statements in your text file you'll notice that the prior paragraph said that this is almost completely hidden from you if the python process has write access on your machineit will store the byte code of your programs in files that end with pyc extension (pycmeans compiled pysourceprior to python you will see these files show up on your computer after you've run few programs alongside the corresponding source code files--that isin the same directories for instanceyou'll notice script pyc after importing script py how python runs programs
610
__pycache__ located in the directory where your source files resideand in files whose names identify the python version that created them ( script cpython- pycthe new __pycache__ subdirectory helps to avoid clutterand the new naming convention for byte code files prevents different python versions installed on the same computer from overwriting each other' saved byte code we'll study these byte code file models in more detail in though they are automatic and irrelevant to most python programsand are free to vary among the alternative python implementations described ahead in both modelspython saves byte code like this as startup speed optimization the next time you run your programpython will load the pyc files and skip the compilation stepas long as you haven' changed your source code since the byte code was last savedand aren' running with different python than the one that created the byte code it works like thissource changespython automatically checks the last-modified timestamps of source and byte code files to know when it must recompile--if you edit and resave your source codebyte code is automatically re-created the next time your program is run python versionsimports also check to see if the file must be recompiled because it was created by different python versionusing either "magicversion number in the byte code file itself in and earlieror the information present in byte code filenames in and later the result is that both source code changes and differing python version numbers will trigger new byte code file if python cannot write the byte code files to your machineyour program still works--the byte code is generated in memory and simply discarded on program exit howeverbecause pyc files speed startup timeyou'll want to make sure they are written for larger programs byte code files are also one way to ship python programs--python is happy to run program if all it can find are pyc fileseven if the original py source files are absent (see "frozen binarieson page for another shipping option finallykeep in mind that byte code is saved in files only for files that are importednot for the top-level files of program that are only run as scripts (strictly speakingit' an import optimizationwe'll explore import basics in and take deeper look at imports in part moreovera given file is only imported (and possibly compiledonce per program runand byte code is also never saved for code typed at the interactive prompt-- programming mode we'll learn about in the python virtual machine (pvmonce your program has been compiled to byte code (or the byte code has been loaded from existing pyc files)it is shipped off for execution to something generally known as the python virtual machine (pvmfor the more acronym-inclined among youthe program execution
611
codewhich is then run by the python virtual machine your code is automatically compiledbut then it is interpreted pvm sounds more impressive than it isreallyit' not separate programand it need not be installed by itself in factthe pvm is just big code loop that iterates through your byte code instructionsone by oneto carry out their operations the pvm is the runtime engine of pythonit' always present as part of the python systemand it' the component that truly runs your scripts technicallyit' just the last step of what is called the "python interpreter figure - illustrates the runtime structure described here keep in mind that all of this complexity is deliberately hidden from python programmers byte code compilation is automaticand the pvm is just part of the python system that you have installed on your machine againprogrammers simply code and run files of statementsand python handles the logistics of running them performance implications readers with background in fully compiled languages such as and +might notice few differences in the python model for one thingthere is usually no build or "makestep in python workcode runs immediately after it is written for anotherpython byte code is not binary machine code ( instructions for an intel or arm chipbyte code is python-specific representation this is why some python code may not run as fast as or +codeas described in --the pvm loopnot the cpu chipstill must interpret the byte codeand byte code instructions require more work than cpu instructions on the other handunlike in classic interpretersthere is still an internal compile step--python does not need to reanalyze and reparse each source statement' text repeatedly the net effect is that pure python code runs at speeds somewhere between those of traditional compiled language and traditional interpreted language see for more on python performance tradeoffs development implications another ramification of python' execution model is that there is really no distinction between the development and execution environments that isthe systems that compile and execute your source code are really one and the same this similarity may have how python runs programs
612
but in pythonthe compiler is always present at runtime and is part of the system that runs programs this makes for much more rapid development cycle there is no need to precompile and link before execution may beginsimply type and run the code this also adds much more dynamic flavor to the language--it is possibleand often very convenientfor python programs to construct and execute other python programs at runtime the eval and exec built-insfor instanceaccept and run strings containing python program code this structure is also why python lends itself to product customization--because python code can be changed on the flyusers can modify the python parts of system onsite without needing to have or compile the entire system' code at more fundamental levelkeep in mind that all we really have in python is runtime-there is no initial compile-time phase at alland everything happens as the program is running this even includes operations such as the creation of functions and classes and the linkage of modules such events occur before execution in more static languagesbut happen as programs execute in python as we'll seethis makes for much more dynamic programming experience than that to which some readers may be accustomed execution model variations now that we've studied the internal execution flow described in the prior sectioni should note that it reflects the standard implementation of python today but is not really requirement of the python language itself because of thatthe execution model is prone to changing with time in factthere are already few systems that modify the picture in figure - somewhat before moving onlet' briefly explore the most prominent of these variations python implementation alternatives strictly speakingas this book edition is being writtenthere are at least five implementations of the python language--cpythonjythonironpythonstacklessand pypy although there is much cross-fertilization of ideas and work between these pythonseach is separately installed software systemwith its own developers and user base other potential candidates here include the cython and shed skin systemsbut they are discussed later as optimization tools because they do not implement the standard python language (the former is python/ mixand the latter is implicitly statically typedin briefcpython is the standard implementationand the system that most readers will wish to use (if you're not surethis probably includes youthis is also the version used in this bookthough the core python language presented here is almost entirely the same in the alternatives all the other python implementations have specific purexecution model variations
613
implement the same python language but execute programs in different ways for examplepypy is drop-in replacement for cpythonwhich can run most programs much quicker similarlyjython and ironpython are completely independent implementations of python that compile python source for different runtime architecturesto provide direct access to java and net components it is also possible to access java and net software from standard cpython programs--jpype and python for net systemsfor instanceallow standard cpython code to call out to java and net components jython and ironpython offer more complete solutionsby providing full implementations of the python language here' quick rundown on the most prominent python implementations available today cpythonthe standard the originaland standardimplementation of python is usually called cpython when you want to contrast it with the other options (and just plain "pythonotherwisethis name comes from the fact that it is coded in portable ansi language code this is the python that you fetch from enthought distributionsand have automatically on most linux and mac os machines if you've found preinstalled version of python on your machineit' probably cpythonunless your company or organization is using python in more specialized ways unless you want to script java or net applications with python or find the benefits of stackless or pypy compellingyou probably want to use the standard cpython system because it is the reference implementation of the languageit tends to run the fastestbe the most completeand be more up-to-date and robust than the alternative systems figure - reflects cpython' runtime architecture jythonpython for java the jython system (originally known as jpythonis an alternative implementation of the python languagetargeted for integration with the java programming language jython consists of java classes that compile python source code to java byte code and then route the resulting byte code to the java virtual machine (jvmprogrammers still code python statements in py text files as usualthe jython system essentially just replaces the rightmost two bubbles in figure - with java-based equivalents jython' goal is to allow python code to script java applicationsmuch as cpython allows python to script and +components its integration with java is remarkably seamless because python code is translated to java byte codeit looks and feels like true java program at runtime jython scripts can serve as web applets and servletsbuild java-based guisand so on moreoverjython includes integration support that allows python code to import and use java classes as though they were coded in pythonand how python runs programs
614
less robust than cpythonthoughit is usually seen as tool of interest primarily to java developers looking for scripting language to serve as frontend to java code see jython' website ironpythonpython for net third implementation of pythonand newer than both cpython and jythonironpython is designed to allow python programs to integrate with applications coded to work with microsoft' net framework for windowsas well as the mono open source equivalent for linux net and its cprogramming language runtime system are designed to be language-neutral object communication layerin the spirit of microsoft' earlier com model ironpython allows python programs to act as both client and server componentsgain accessibility both to and from other net languagesand leverage net technologies such as the silverlight framework from their python code by implementationironpython is very much like jython (andin factwas developed by the same creator)--it replaces the last two bubbles in figure - with equivalents for execution in the net environment also like jythonironpython has special focus --it is primarily of interest to developers integrating python with net components formerly developed by microsoft and now an open source projectironpython might also be able to take advantage of some important optimization tools for better performance for more detailsconsult with web search stacklesspython for concurrency still other schemes for running python programs have more focused goals for examplethe stackless python system is an enhanced version and reimplementation of the standard cpython language oriented toward concurrency because it does not save state on the language call stackstackless python can make python easier to port to small stack architecturesprovides efficient multiprocessing optionsand fosters novel programming structures such as coroutines among other thingsthe microthreads that stackless adds to python are an efficient and lightweight alternative to python' standard multitasking tools such as threads and processesand promise better program structuremore readable codeand increased programmer productivity ccp gamesthe creator of eve onlineis well-known stackless python userand compelling python user success story in general try http//stackless com for more information pypypython for speed the pypy system is another standard cpython reimplementationfocused on performance it provides fast python implementation with jit (just-in-timecompilerprovides tools for "sandboxmodel that can run untrusted code in secure environexecution model variations
615
and its microthreads to support massive concurrency pypy is the successor to the original psyco jitdescribed aheadand subsumes it with complete python implementation built for speed jit is really just an extension to the pvm--the rightmost bubble in figure - --that translates portions of your byte code all the way to binary machine code for faster execution it does this as your program is runningnot in prerun compile stepand is able to created type-specific machine code for the dynamic python language by keeping track of the data types of the objects your program processes by replacing portions of your byte code this wayyour program runs faster and faster as it is executing in additionsome python programs may also take up less memory under pypy at this writingpypy supports python code (not yet xand runs on intel (ia- and platforms (including windowslinuxand recent macs)with arm and ppc support under development it runs most cpython codethough extension modules must generally be recompiledand pypy has some minor but subtle language differencesincluding garbage collection semantics that obviate some common coding patterns for instanceits non-reference-count scheme means that temporary files may not close and flush output buffers immediatelyand may require manual close calls in some cases in returnyour code may run much quicker pypy currently claims speedup over cpython across range of benchmark programs (per casesits ability to take advantage of dynamic optimization opportunities can make python code as quick as codeand occasionally faster this is especially true for heavily algorithmic or numeric programswhich might otherwise be recoded in for instancein one simple benchmark we'll see in pypy today clocks in at faster than cpython and faster than cpython though other benchmarks will varysuch speedups may be compelling advantage in many domainsperhaps even more so than leading-edge language features just as importantmemory space is also optimized in pypy--in the case of one posted benchmarkrequiring mb and completing in secondscompared to cpython' mb and seconds pypy' tool chain is also general enough to support additional languagesincluding pyrologa prolog interpreter written in python using the pypy translator search for pypy' website for more pypy currently lives at search may also prove fruitful over time for an overview of its current performancealso see how python runs programs
616
for the arm processorand still python -only implementation per its beta release notes"pypy is very compliant python interpreteralmost drop-in replacement for cpython it' fast due to its integrated tracing jit compiler this release supports machines running linux / mac os or windows it also supports arm machines running linux the claims seem accurate using the timing tools we'll study in pypy is often an order of magnitude (factor of faster than cpython and on tests 've runand sometimes even better this is despite the fact that pypy is -bit build on my windows test machinewhile cpython is faster -bit compile naturally the only benchmark that truly matters is your own codeand there are cases where cpython wins the racepypy' file iteratorsfor instancemay clock in slower today stillgiven pypy' focus on performance over language mutationand especially its support for the numeric domainmany today see pypy as an important path for python if you write cpu-intensive codepypy deserves your attention execution optimization tools cpython and most of the alternatives of the prior section all implement the python language in similar waysby compiling source code to byte code and executing the byte code on an appropriate virtual machine some systemssuch as the cython hybridthe shed skin +translatorand the just-in-time compilers in pypy and psyco instead attempt to optimize the basic execution model these systems are not required knowledge at this point in your python careerbut quick look at their place in the execution model might help demystify the model in general cythona python/ hybrid the cython system (based on work done by the pyrex projectis hybrid language that combines python code with the ability to call functions and use type declarations for variablesparametersand class attributes cython code can be compiled to code that uses the python/ apiwhich may then be compiled completely though not completely compatible with standard pythoncython can be useful both for wrapping external libraries and for coding efficient extensions for python see org for current status and details shed skina python-to- +translator shed skin is an emerging system that takes different approach to python program execution--it attempts to translate python source code to +codewhich your computer' +compiler then compiles to machine code as suchit represents platformneutral approach to running python code execution model variations
617
python to codeand it limits python programs to an implicit statically typed constraint that is typical of most programs but is technically not normal pythonso we won' go into further detail here initial resultsthoughshow that it has the potential to outperform both standard python and psyco-like extensions in terms of execution speed search the web for details on the project' current status psycothe original just-in-time compiler the psyco system is not another python implementationbut rather component that extends the byte code execution model to make programs run faster todaypsyco is something of an ex-projectit is still available for separate downloadbut has fallen out of date with python' evolutionand is no longer actively maintained insteadits ideas have been incorporated into the more complete pypy system described earlier stillthe ongoing importance of the ideas psyco explored makes them worth quick look in terms of figure - psyco is an enhancement to the pvm that collects and uses type information while the program runs to translate portions of the program' byte code all the way down to true binary machine code for faster execution psyco accomplishes this translation without requiring changes to the code or separate compilation step during development roughlywhile your program runspsyco collects information about the kinds of objects being passed aroundthat information can be used to generate highly efficient machine code tailored for those object types once generatedthe machine code then replaces the corresponding part of the original byte code to speed your program' overall execution the result is that with psycoyour program becomes quicker over time as it runs in ideal casessome python code may become as fast as compiled code under psyco because this translation from byte code happens at program runtimepsyco is known as just-in-time compiler psyco is different from the jit compilers some readers may have seen for the java languagethough reallypsyco is specializing jit compiler-it generates machine code tailored to the data types that your program actually uses for exampleif part of your program uses different data types at different timespsyco may generate different version of machine code to support each different type combination psyco was shown to speed some python code dramatically according to its web pagepsyco provides " to speed-upstypically xwith an unmodified python interpreter and unmodified source codejust dynamically loadable extension module of equal significancethe largest speedups are realized for algorithmic code written in pure python--exactly the sort of code you might normally migrate to to optimize for more on psycosearch the web or see its successor--the pypy project described previously how python runs programs
618
sometimes when people ask for "realpython compilerwhat they're really seeking is simply way to generate standalone binary executables from their python programs this is more packaging and shipping idea than an execution-flow conceptbut it' somewhat related with the help of third-party tools that you can fetch off the webit is possible to turn your python programs into true executablesknown as frozen binaries in the python world these programs can be run without requiring python installation frozen binaries bundle together the byte code of your program filesalong with the pvm (interpreterand any python support files your program needsinto single package there are some variations on this themebut the end result can be single binary executable program ( an exe file on windowsthat can easily be shipped to customers in figure - it is as though the two rightmost bubbles--byte code and pvm--are merged into single componenta frozen binary file todaya variety of systems are capable of generating frozen binarieswhich vary in platforms and featurespy exe for windows onlybut with broad windows supportpyinstallerwhich is similar to py exe but also works on linux and mac os and is capable of generating self-installing binariespy app for creating mac os applicationsfreezethe originaland cx_freezewhich offers both python and cross-platform support you may have to fetch these tools separately from python itselfbut they are freely available these tools are also constantly evolvingso consult of these systemspy exe can freeze standalone programs that use the tkinterpmwwxpythonand pygtk gui librariesprograms that use the pygame game programming toolkitwin com client programsand more frozen binaries are not the same as the output of true compiler--they run byte code through virtual machine henceapart from possible startup improvementfrozen binaries run at the same speed as the original source files frozen binaries are also not generally small (they contain pvm)but by current standards they are not unusually large either because python is embedded in the frozen binarythoughit does not have to be installed on the receiving end to run your program moreoverbecause your code is embedded in the frozen binaryit is more effectively hidden from recipients this single file-packaging scheme is especially appealing to developers of commercial software for instancea python-coded user interface program based on the tkinter toolkit can be frozen into an executable file and shipped as self-contained program on cd or on the web end users do not need to install (or even have to know aboutpython to run the shipped program execution model variations
619
finallynote that the runtime execution model sketched here is really an artifact of the current implementation of pythonnot of the language itself for instanceit' not impossible that fulltraditional compiler for translating python source code to machine code may appear during the shelf life of this book (although the fact that one has not in over two decades makes this seem unlikely!new byte code formats and implementation variants may also be adopted in the future for instancethe ongoing parrot project aims to provide common byte code formatvirtual machineand optimization techniques for variety of programming languagesincluding python python' own pvm runs python code more efficiently than parrot (as famously demonstrated by pie challenge at software conference--search the web for details)but it' unclear how parrot will evolve in relation to python specifically see the former unladen swallow project--an open source project developed by google engineers--sought to make standard python faster by factor of at least and fast enough to replace the language in many contexts this was an optimization branch of cpython (specifically python )intended to be compatible yet faster by virtue of adding jit to standard python as write this in this project seems to have drawn to close (per its withdrawn python pepit was "going the way of the norwegian blue"stillits lessons gained may be leveraged in other formssearch the web for breaking developments although future implementation schemes may alter the runtime structure of python somewhatit seems likely that the byte code compiler will still be the standard for some time to come the portability and runtime flexibility of byte code are important features of many python systems moreoveradding type constraint declarations to support static compilation would likely break much of the flexibilityconcisenesssimplicityand overall spirit of python coding due to python' highly dynamic natureany future implementation will likely retain many artifacts of the current pvm summary this introduced the execution model of python--how python runs your programs--and explored some common variations on that modeljust-in-time compilers and the like although you don' really need to come to grips with python internals to write python scriptsa passing acquaintance with this topics will help you truly understand how your programs run once you start coding them in the next you'll start actually running some code of your own firstthoughhere' the usual quiz how python runs programs
620
what is the python interpreter what is source code what is byte code what is the pvm name two or more variations on python' standard execution model how are cpythonjythonand ironpython different what are stackless and pypytest your knowledgeanswers the python interpreter is program that runs the python programs you write source code is the statements you write for your program--it consists of text in text files that normally end with py extension byte code is the lower-level form of your program after python compiles it python automatically stores byte code in files with pyc extension the pvm is the python virtual machine--the runtime engine of python that interprets your compiled byte code psycoshed skinand frozen binaries are all variations on the execution model in additionthe alternative implementations of python named in the next two answers modify the model in some fashion as well--by replacing byte code and vmsor by adding tools and jits cpython is the standard implementation of the language jython and ironpython implement python programs for use in java and net environmentsrespectivelythey are alternative compilers for python stackless is an enhanced version of python aimed at concurrencyand pypy is reimplementation of python targeted at speed pypy is also the successor to psycoand incorporates the jit concepts that psyco pioneered test your knowledgeanswers
621
how you run programs okit' time to start running some code now that you have handle on the program execution modelyou're finally ready to start some real python programming at this pointi'll assume that you have python installed on your computerif you don'tsee the start of the prior and appendix for installation and configuration hints on various platforms our goal here is to learn how to run python program code there are multiple ways to tell python to execute the code you type this discusses all the program launching techniques in common use today along the wayyou'll learn how to both type code interactivelyand how to save it in files to be run as often as you like in variety of wayswith system command linesicon clicksmodule importsexec callsmenu options in the idle guiand more as for the previous if you have prior programming experience and are anxious to start digging into python itselfyou may want to skim this and move on to but don' skip this early coverage of preliminaries and conventionsits overview of debugging techniquesor its first look at module imports-- topic essential to understanding python' program architecturewhich we won' revisit until later part also encourage you to see the sections on idle and other idesso you'll know what tools are available when you start developing more sophisticated python programs the interactive prompt this section gets us started with interactive coding basics because it' our first look at running codewe also cover some preliminaries heresuch as setting up working directory and the system pathso be sure to read this section first if you're relatively new to programming this section also explains some conventions used throughout the bookso most readers should probably take at least quick look here
622
perhaps the simplest way to run python programs is to type them at python' interactive command linesometimes called the interactive prompt there are variety of ways to start this command linein an idefrom system consoleand so on assuming the interpreter is installed as an executable program on your systemthe most platformneutral way to start an interactive interpreter session is usually just to type python at your operating system' promptwithout any arguments for examplepython python ( :bd afb ebf sep : : [msc bit type "help""copyright""creditsor "licensefor more information ^ typing the word "pythonat your system shell prompt like this begins an interactive python sessionthe "%character at the start of this listing stands for generic system prompt in this book--it' not input that you type yourself on windowsa ctrl- gets you out of this sessionon unixtry ctrl- instead the notion of system shell prompt is genericbut exactly how you access it varies by platformon windowsyou can type python in dos console window-- program named cmd exe and usually known as command prompt for more details on starting this programsee this sidebar "where is command prompt on windows?on page on mac os xyou can start python interactive interpreter by double-clicking on applications-utilities-terminaland then typing python in the window that opens up on linux (and other unixes)you might type this command in shell or terminal window (for instancein an xterm or console running shell such as ksh or cshother systems may use similar or platform-specific devices on handheld devicesfor exampleyou might click the python icon in the home or application window to launch an interactive session on most platformsyou can start the interactive prompt in additional ways that don' require typing commandbut they vary per platform even more widelyon windows and earlierbesides typing python in shell windowyou can also begin similar interactive sessions by starting the idle gui (discussed later)or by selecting the "python (command line)menu option from the start button menu for pythonas shown in figure - in both spawn python interactive prompt with the same functionality obtained with "pythoncommand on windows you don' have start button (at least as write this)but there are other ways to get to the tools described in the prior bulletincluding tilessearchfile explorerand the "all appsinterface on the start screen see appendix for more pointers on this platform how you run programs
623
typing commandsbut they're too specific to get into heresee your system' documentation for details anytime you see the promptyou're in an interactive python interpreter session-you can type any python statement or expression here and run it immediately we will in momentbut first we need to get few startup details sorted out to make sure all readers are set to go where is command prompt on windowsso how do you start the command-line interface on windowssome windows readers already knowbut unix developers and beginners may notit' not as prominent as terminal or console windows on unix systems here are some pointers on finding your command promptwhich vary slightly per windows version on windows and earlierthis is usually found in the accessories section of the start-all programs menuor you can run it by typing cmd in the start-run dialog box or the start menu' search entry field you can drag out desktop shortcut to get to it quicker if desired on windows you can access command prompt in the menu opened by right-clicking on the preview in the screen' lower-left cornerin the windows system section of the "all appsdisplay reached by right-clicking your start screenor by typing cmd or command prompt in the input field of the search charm pulled down from the screen' upper-right corner there are probably additional routesand touch screens offer similar access and if you want to forget all thatpin it to your desktop taskbar for easy access next time around these procedures are prone to vary over timeand possibly even per computer and user ' trying to avoid making this book on windowsthoughso 'll cut this topic short here when in doubttry the system help interface (whose usage may differ as much as the tools it provides help for! note to any unix users reading this sidebar who may be starting to feel like fish out of wateryou may also be interested in the cygwin systemwhich brings full unix command prompt to windows see appendix for more pointers the system path when we typed python in the last section to start an interactive sessionwe relied on the fact that the system located the python program for us on its program search path depending on your python version and platformif you have not set your system' path environment variable to include python' install directoryyou may need to replace the word "pythonwith the full path to the python executable on your machine on unixlinuxand similarsomething like /usr/local/bin/python or /usr/bin/python will often suffice on windowstry typing :\python \python (for version )the interactive prompt
624
python ( :bd afb ebf sep : : [msc bit type "help""copyright""creditsor "licensefor more information ^ alternativelyyou can run "cdchange-directory command to go to python' install directory before typing python--try the cd :\python command on windowsfor examplec:\codecd :\python :\python python python ( :bd afb ebf sep : : [msc bit type "help""copyright""creditsor "licensefor more information ^ but you'll probably want to set your path eventuallyso simple "pythonsuffices if you don' know what path is or how to set itsee appendix --it covers environment variables like this whose usage varies per platformas well as python command-line arguments we won' be using much in this book the short story for windows userssee the advanced settings in the system entry of your control panel if you're using python and laterthis is now automatic on windowsas the next section explains new windows options in pathlauncher the foregoing section and much of this at large describe the generic state of play for all and pythons prior to version starting with python the windows installer has an option to automatically add python ' directory to your system pathif enabled in the installer' windows if you use this optionyou won' need to type directory path or issue "cdto run python commands as in the prior section be sure to select this option during the install if you want itas it' currently disabled by default more dramaticallypython for windows ships with and automatically installs the new windows launcher-- system that comes with new executable programspy with console and pyw withoutthat are placed in directories on your system pathand so may be run out of the box without any path configurationschange-directory commandsor directory path prefixesc:\codepy python ( :bd afb ebf sep : : [msc bit type "help""copyright""creditsor "licensefor more information ^ :\codepy - python (defaultapr : : [msc bit (amd )type "help""copyright""creditsor "licensefor more information ^ :\codepy - python (defaultjun : : [msc bit (amd ) how you run programs
625
^ as shown in the last two commands herethese executables also accept python version numbers on the command line (and in unix-style #lines at the top of scriptsas discussed later)and are associated to open python files when clicked just like the original python executable--which is still available and works as beforebut is somewhat superseded by the launcher' new programs the launcher is standard part of python and is available standalone for use with other versions we'll see more on this new launcher in this and later including brief look at its #line support here howeverbecause it is of interest only to windows usersand even for this group is present only in or where installed separatelyi've collected almost all of the details about the launcher in appendix if you'll be working on windows under python or lateri suggest taking brief detour to that appendix nowas it provides an alternativeand in some ways betterway to run python command lines and scripts at base levellauncher users can type py instead of python in most of the system commands shown in this bookand may avoid some configuration steps especially on computers with multiple python versionsthoughthe new launcher gives you more explicit control over which python runs your code where to runcode directories now that 've started showing you how to run codei want to say few words up front about where to run code to keep things simplein this and book at large ' going to be running code from working directory ( folderi've created on my windows computer called :\code-- subdirectory at the top of my main drive that' where 'll start most interactive sessionsand where 'll be both saving and running most script files this also means the files that examples will create will mostly show up in this directory if you'll be working alongyou should probably do something similar before we get started here are some pointers if you need help getting set up with working directory on your computeron windowsyou can make your working code directory in file explorer or command prompt window in file explorerlook for new foldersee the file menuor try right-click in command prompttype and run mkdir commandusually after you cd to your desired parent directory ( cd \and mkdir codeyour working directory can be located wherever you like and called whatever you wishand doesn' have to be :\code ( chose this name because it' short in promptsbut running out of one directory will help you keep track of your work and simplify some tasks for more windows hintssee this sidebar on command promptas well as appendix the interactive prompt
626
on unix-based systems (including mac os and linux)your working directory might be in /usr/home and be created by mkdir command in shell window or file explorer gui specific to your platformbut the same concepts apply the cygwin unix-like system for windows is similar toothough your directory names may vary (/home and /cygdrive/ are candidatesyou can store your code in python' install directory too ( :\python on windowsto simplify some command lines before setting pathbut you probably shouldn' --this is for python itselfand your files may not survive move or uninstall once you've made your working directoryalways start there to work along with the examples in this book the prompts in this book that show the directory that ' running code in will reflect my windows laptop' working directorywhen you see \codeor %think the location and name of your own directory what not to typeprompts and comments speaking of promptsthis book sometimes shows system prompts as generic %and sometimes in full :\codewindows form the former is meant to be platform agnostic (and derives from earlier editionsuse of linux)and the latter is used in windowsspecific contexts also add space after system prompts just for readability in this book when usedthe character at the start of system command line stands for the system' promptwhatever that may be on your machine for instanceon my machine stands for :\codein windows command promptand just in my cygwn install to beginnersdon' type the character (or the :\code system prompt it sometimes stands foryou see in this book' interaction listings yourself--this is text the system prints type just the text after these system prompts similarlydo not type the and characters shown at the start of lines in interpreter interaction listings--these are prompts that python displays automatically as visual guides for interactive code entry type just the text after these python prompts for instancethe prompt is used for continuation lines in some shellsbut doesn' appear in idleand shows up in some but not all of this book' listingsdon' type it yourself if it' absent in your interface to help you remember thisuser inputs are shown in bold in this bookand prompts are not in some systems these prompts may differ (for instancethe pypy performancefocused implementation described in uses four-character and )but the same rules apply also keep in mind that commands typed after these system and python prompts are meant to be run immediatelyand are not generally to be saved in the source files we will be creatingwe'll see why this distinction matters ahead in the same veinyou normally don' need to type text that starts with character in listings in this book--as you'll learnthese are commentsnot executable code except when is used to introduce directive at the top of script for unix or the python how you run programs
627
the launcher later in this and in appendix bif you're working alonginteractive listings will drop most continuation prompts as of to aid cut-and-paste of larger code such as functions and classes from ebooks or otheruntil thenpaste or type one line at time and omit the prompts at least initiallyit' important to type code manuallyto get feel for syntax details and errors some examples will be listed either by themselves or in named files available in the book' examples package (per the preface)and we'll switch between listing formats oftenwhen in doubtif you see ""it means the code is being typed interactively running code interactively with those preliminaries out of the waylet' move on to typing some actual code however it' startedthe python interactive session begins by printing two lines of informational text giving the python version number and few hints shown earlier (which 'll omit from most of this book' examples to save space)then prompts for input with when it' waiting for you to type new python statement or expression when working interactivelythe results of your code are displayed below the input lines after you press the enter key for instancehere are the results of two python print statements (print is really function call in python xbut not in xso the parentheses here are required in only)python print('hello world!'hello worldprint( * there it is--we've just run some python code (were you expecting the spanish inquisition?don' worry about the details of the print statements shown here yetwe'll start digging into syntax in the next in shortthey print python string and an integeras shown by the output lines that appear after each input line ( * means raised to the power in pythonwhen coding interactively like thisyou can type as many python commands as you likeeach is run immediately after it' entered moreoverbecause the interactive session automatically prints the results of expressions you typeyou don' usually need to say "printexplicitly at this promptlumberjack 'okaylumberjack 'okay * the interactive prompt
628
use ctrl- (on unixor ctrl- (on windowsto exit herethe first line saves value by assigning it to variable (lumberjack)which is created by the assignmentand the last two lines typed are expressions (lumberjack and * )whose results are displayed automatically againto exit an interactive session like this and return to your system shell prompttype ctrl- on unix-like machinesand ctrl- on windows in the idle gui discussed latereither type ctrl- or simply close the window notice the italicized note about this on the right side of this listing (staring with "#herei'll use these throughout to add remarks about what is being illustratedbut you don' need to type this text yourself in factjust like system and python promptsyou shouldn' type this when it' on system command linethe "#part is taken as comment by python but may be an error at system prompt nowwe didn' do much in this session' code--just typed some python print and assignment statementsalong with few expressionswhich we'll study in detail later the main thing to notice is that the interpreter executes the code entered on each line immediatelywhen the enter key is pressed for examplewhen we typed the first print statement at the promptthe output ( python stringwas echoed back right away there was no need to create source code fileand no need to run the code through compiler and linker firstas you' normally do when using language such as or +as you'll see in later you can also run multiline statements at the interactive promptsuch statement runs immediately after you've entered all of its lines and pressed enter twice to add blank line why the interactive promptthe interactive prompt runs code and echoes results as you gobut it doesn' save your code in file although this means you won' do the bulk of your coding in interactive sessionsthe interactive prompt turns out to be great place to both experiment with the language and test program files on the fly experimenting because code is executed immediatelythe interactive prompt is perfect place to experiment with the language and will be used often in this book to demonstrate smaller examples in factthis is the first rule of thumb to rememberif you're ever in doubt about how piece of python code worksfire up the interactive command line and try it out to see what happens for instancesuppose you're reading python program' code and you come across an expression like 'spam! whose meaning you don' understand at this pointyou can spend minutes wading through manualsbooksand the web to try to figure out what the code doesor you can simply run it interactively how you run programs
629
'spam! 'spam!spam!spam!spam!spam!spam!spam!spam!learning by trying the immediate feedback you receive at the interactive prompt is often the quickest way to deduce what piece of code does hereit' clear that it does string repetitionin python means multiply for numbersbut repeat for strings--it' like concatenating string to itself repeatedly (more on strings in chances are good that you won' break anything by experimenting this way--at leastnot yet to do real damagelike deleting files and running shell commandsyou must really tryby importing modules explicitly (you also need to know more about python' system interfaces in general before you will become that dangerous!straight python code is almost always safe to run for instancewatch what happens when you make mistake at the interactive promptx traceback (most recent call last)file ""line in nameerrorname 'xis not defined making mistakes in pythonusing variable before it has been assigned value is always an error-otherwiseif names were filled in with defaultssome errors might go undetected this means you must initial counters to zero before you can add to themmust initial lists before extending themand so onyou don' declare variablesbut they must be assigned before you can fetch their values we'll learn more about that laterthe important point here is that you don' crash python or your computer when you make mistake this way insteadyou get meaningful error message pointing out the mistake and the line of code that made itand you can continue on in your session or script in factonce you get comfortable with pythonits error messages may often provide as much debugging support as you'll need (you'll learn more about debugging options in the sidebar "debugging python codeon page testing besides serving as tool for experimenting while you're learning the languagethe interactive interpreter is also an ideal place to test code you've written in files you can import your module files interactively and run tests on the tools they define by typing calls at the interactive prompt on the fly for instancethe following tests function in precoded module that ships with python in its standard library (it prints the name of the directory you're currently working inwith doubled-up backslash that stands for just one)but you can do the same once you start writing module files of your ownimport os os getcwd(' :\\codetesting on the fly the interactive prompt
630
type calls to linked-in functionsexercise java classes under jythonand more partly because of its interactive naturepython supports an experimental and exploratory programming style you'll find convenient when getting started although python programmers also test with in-file code (and we'll learn ways to make this simple later in the book)for manythe interactive prompt is still their first line of testing defense usage notesthe interactive prompt although the interactive prompt is simple to usethere are few tips that beginners should keep in mind ' including lists of common mistakes like the following in this for referencebut they might also spare you from few headaches if you read them up fronttype python commands only first of allremember that you can only type python code at python' promptnot system commands there are ways to run system commands from within python code ( with os system)but they are not as direct as simply typing the commands themselves print statements are required only in files because the interactive interpreter automatically prints the results of expressionsyou do not need to type complete print statements interactively this is nice featurebut it tends to confuse users when they move on to writing code in fileswithin code fileyou must use print statements to see your output because expression results are not automatically echoed rememberyou must say print in filesbut it' optional interactively don' indent at the interactive prompt (yetwhen typing python programseither interactively or into text filebe sure to start all your unnested statements in column (that isall the way to the leftif you don'tpython may print "syntaxerrormessagebecause blank space to the left of your code is taken to be indentation that groups nested statements until all statements you write will be unnestedso this includes everything for now remembera leading space generates an error messageso don' start with space or tab at the interactive prompt unless it' nested code watch out for prompt changes for compound statements we won' meet compound (multilinestatements until and not in earnest until but as previewyou should know that when typing lines and beyond of compound statement interactivelythe prompt may change in the simple shell window interfacethe interactive prompt changes to instead of for lines and beyondin the idle gui interfacelines after the first are instead automatically indented you'll see why this matters in for nowif you happen to come across prompt or blank line when entering your codeit probably means that you've somehow confused interactive python into thinking you're typing multiline how you run programs
631
main prompt the and prompt strings can also be changed (they are available in the built-in module sys)but 'll assume they have not been in the book' example listings terminate compound statements at the interactive prompt with blank line at the interactive promptinserting blank line (by hitting the enter key at the start of lineis necessary to tell interactive python that you're done typing the multiline statement that isyou must press enter twice to make compound statement run by contrastblank lines are not required in files and are simply ignored if present if you don' press enter twice at the end of compound statement when working interactivelyyou'll appear to be stuck in limbo statebecause the interactive interpreter will do nothing at all--it' waiting for you to press enter againthe interactive prompt runs one statement at time at the interactive promptyou must run one statement to completion before typing another this is natural for simple statementsbecause pressing the enter key runs the statement entered for compound statementsthoughremember that you must submit blank line to terminate the statement and make it run before you can type the next statement entering multiline statements at the risk of repeating myselfi've received multiple emails from readers who' gotten burned by the last two pointsso they probably merit emphasis 'll introduce multiline ( compoundstatements in the next and we'll explore their syntax more formally later in this book because their behavior differs slightly in files and at the interactive promptthoughtwo cautions are in order here firstbe sure to terminate multiline compound statements like for loops and if tests at the interactive prompt with blank line in other wordsyou must press the enter key twiceto terminate the whole multiline statement and then make it run for example (pun not intended)for in 'spam'print(xpress enter twice here to make this loop run you don' need the blank line after compound statements in script filethoughthis is required only at the interactive prompt in fileblank lines are not required and are simply ignored when presentat the interactive promptthey terminate multiline statements reminderthe continuation line prompt in the preceding is printed by python automatically as visual guideit may not appear in your interface ( idle)and is sometimes omitted by this bookbut do not type it yourself if it' absent also bear in mind that the interactive prompt runs just one statement at timeyou must press enter twice to run loop or other multiline statement before you can type the next statementthe interactive prompt
632
print(xprint('done'file ""line print('done'syntaxerrorinvalid syntax press enter twice before new statement this means you can' cut and paste multiple lines of code into the interactive promptunless the code includes blank lines after each compound statement such code is better run in file--which brings us to the next section' topic system command lines and files although the interactive prompt is great for experimenting and testingit has one big disadvantageprograms you type there go away as soon as the python interpreter executes them because the code you type interactively is never stored in fileyou can' run it again without retyping it from scratch cut-and-paste and command recall can help some herebut not muchespecially when you start writing larger programs to cut and paste code from an interactive sessionyou would have to edit out python promptsprogram outputsand so on--not exactly modern software development methodologyto save programs permanentlyyou need to write your code in fileswhich are usually known as modules modules are simply text files containing python statements once they are codedyou can ask the python interpreter to execute the statements in such file any number of timesand in variety of ways--by system command linesby file icon clicksby options in the idle user interfaceand more regardless of how it is runpython executes all the code in module file from top to bottom each time you run the file terminology in this domain can vary somewhat for instancemodule files are often referred to as programs in python--that isa program is considered to be series of precoded statements stored in file for repeated execution module files that are run directly are also sometimes called scripts--an informal term usually meaning top-level program file some reserve the term "modulefor file imported from another fileand "scriptfor the main file of programwe generally will heretoo (though you'll have to stay tuned for more on the meaning of "top-level,importsand main files later in this whatever you call themthe next few sections explore ways to run code typed into module files in this sectionyou'll learn how to run files in the most basic wayby listing their names in python command line entered at your computer' system prompt though it might seem primitive to some--and can often be avoided altogether by using gui like idlediscussed later--for many programmers system shell command-line windowtogether with text editor windowconstitutes as much of an how you run programs
633
control over programs first script let' get started open your favorite text editor ( vinotepador the idle editor)type the following statements into new text file named script pyand save it in your working code directory that you set up earliera first python script import sys print(sys platformprint( * 'spam!print( load library module raise to power string repetition this file is our first official python script (not counting the two-liner in you shouldn' worry too much about this file' codebut as brief descriptionthis fileimports python module (libraries of additional tools)to fetch the name of the platform runs three print function callsto display the script' results uses variable named xcreated when it' assignedto hold onto string object applies various object operations that we'll begin studying in the next the sys platform here is just string that identifies the kind of computer you're working onit lives in standard python module called syswhich you must import to load (againmore on imports laterfor colori've also added some formal python comments here--the text after the characters mentioned these earlierbut should be more formal now that they're showing up in scripts comments can show up on lines by themselvesor to the right of code on line the text after is simply ignored as human-readable comment and is not considered part of the statement' syntax if you're copying this codeyou can ignore the commentsthey are just informative in this bookwe usually use different formatting style to make comments more visually distinctivebut they'll appear as normal text in your code againdon' focus on the syntax of the code in this file for nowwe'll learn about all of it later the main point to notice is that you've typed this code into filerather than at the interactive prompt in the processyou've coded fully functional python script notice that the module file is called script py as for all top-level filesit could also be called simply scriptbut files of code you want to import into client have to end with py suffix we'll study imports later in this because you may want to import them in the futureit' good idea to use py suffixes for most python files that you code alsosome text editors detect python files by their py suffixif the suffix is not presentyou may not get features like syntax colorization and automatic indentation system command lines and files
634
once you've saved this text fileyou can ask python to run it by listing its full filename as the first argument to python command like the following typed at the system shell prompt (don' type this at python' interactive promptand read on to the next paragraph if this doesn' work right away for you)python script py win spam!spam!spam!spam!spam!spam!spam!spamagainyou can type such system shell command in whatever your system provides for command-line entry-- windows command prompt windowan xterm windowor similar but be sure to run this in the same working directory where you've saved your script file ("cdthere first if needed)and be sure to run this at the system promptnot python' "prompt also remember to replace the command' word "pythonwith full directory path as we did before if your path setting is not configuredthough this isn' required for the "pywindows launcher programand may not be required in and later another note to beginnersdo not type any of the preceding text in the script py source file you created in the prior section this text is system command and program outputnot program code the first line here is the shell command used to run the source fileand the lines following it are the results produced by the source file' print statements and againremember that the stands for the system prompt--don' type it yourself (not to nagbut it' remarkably common early mistakeif all works as plannedthis shell command makes python run the code in this file line by lineand you will see the output of the script' three print statements--the name of the underlying platform as known python raised to the power and the result of the same string repetition expression we saw earlier (againmore on the meaning of the last two of these in if all didn' work as plannedyou'll get an error message--make sure you've entered the code in your file exactly as shownand try again the next section has additional options and pointers on this processand we'll talk about debugging options in the sidebar "debugging python codeon page but at this point in the book your best bet is probably rote imitation and if all else failsyou might also try running under the idle gui discussed ahead-- tool that sugarcoats some launching detailsthough sometimes at the expense of the more explicit control you have when using command lines you can also fetch the code examples off the web if copying grows too tedious or errorpronethough typing some code initially will help you learn to avoid syntax errors see the preface for details on how to obtain the book' example files how you run programs
635
because this scheme uses shell command lines to start python programsall the usual shell syntax applies for instanceyou can route the printed output of python script to file to save it for later use or inspection by using special shell syntaxpython script py saveit txt in this casethe three output lines shown in the prior run are stored in the file saveit txt instead of being printed this is generally known as stream redirectionit works for input and output text and is available on windows and unix-like systems this is nice for testingas you can write programs that watch for changes in other programsoutputs it also has little to do with pythonthough (python simply supports it)so we will skip further details on shell redirection syntax here if you are working on windows platformthis example works the samebut the system prompt is normally different as described earlierc:\codepython script py win spam!spam!spam!spam!spam!spam!spam!spamas usualif you haven' set your path environment variable to include the full directory path to pythonbe sure to include this in your commandor run change-directory command to go to the path firstc:\codec:\python \python script py win spam!spam!spam!spam!spam!spam!spam!spamalternativelyif you're using the windows launcher new in python (described earlier) py command will have the same effectbut does not require directory path or path settingsand allows you to specify python version numbers on the command line tooc:\codepy - script py win spam!spam!spam!spam!spam!spam!spam!spamon all recent versions of windowsyou can also type just the name of your scriptand omit the name of python itself because newer windows systems use the windows registry ( filename associationsto find program with which to run fileyou don' need to name "pythonor "pyon the command line explicitly to run py file the prior commandfor examplecould be simplified to the following on most windows machinesand will automatically be run by python prior to and by py in and later--just as though you had clicked on the file' icon in explorer (more on this option ahead) :\codescript py system command lines and files
636
from the one in which you are working for examplethe following system command linerun from :\otherassumes python is in your system path but runs file located elsewherec:\codecd :\other :\otherpython :\code\script py if your path doesn' include python' directoryyou're not using the windows launcher' py programand neither python nor your script file is in the directory you're working inuse full paths for bothd:\otherc:\python \python :\code\script py usage notescommand lines and files running program files from system command lines is fairly straightforward launch optionespecially if you are familiar with command lines in general from prior work it' also perhaps the most portable way to run python programs since nearly every computer has some notion of command line and directory structure for newcomersthoughhere are few pointers about common beginner traps that might help you avoid some frustrationbeware of automatic extensions on windows and idle if you use the notepad program to code program files on windowsbe careful to pick the type all files when it comes time to save your fileand give the file py suffix explicitly otherwisenotepad will save your file with txt extension ( as script py txt)making it difficult to use in some schemesit won' be importablefor example worsewindows hides file extensions by defaultso unless you have changed your view options you may not even notice that you've coded text file and not python file the file' icon may give this away--if it doesn' have snake of some sort on ityou may have trouble uncolored code in idle and files that open to edit instead of run when clicked are other symptoms of this problem microsoft word similarly adds doc extension by defaultmuch worseit adds formatting characters that are not legal python syntax as rule of thumbalways pick all files when saving under windowsor use more programmer-friendly text editor such as idle idle does not even add py suffix automatically-- feature some programmers tend to likebut some users do not use file extensions and directory paths at system promptsbut not for imports don' forget to type the full name of your file in system command lines-that isuse python script py rather than python script by contrastpython' import statementswhich we'll meet later in this omit both the py file suffix and the directory path ( import script this may seem trivialbut confusing these two is common mistake how you run programs
637
file search rules do not apply because of thatyou must include both the py extension andif necessarythe full directory path leading to the file you wish to run for instanceto run file that resides in different directory from the one in which you are workingyou would typically list its full path ( python :\tests \spam pywithin python codehoweveryou can just say import spam and rely on the python module search path to locate your fileas described later use print statements in files yeswe've already been over thisbut it is such common mistake that it' worth repeating at least once here unlike in interactive codingyou generally must use print statements to see output from program files if you don' see any outputmake sure you've said "printin your file print statements are not required in an interactive sessionsince python automatically echoes expression resultsprints don' hurt herebut are superfluous typing unix-style executable scripts#our next launching technique is really specialized form of the priorwhichdespite this section' titlecan apply to program files run on both unix and windows today since it has its roots on unixlet' begin this story there unix script basics if you are going to use python on unixlinuxor unix-like systemyou can also turn files of python code into executable programsmuch as you would for programs coded in shell language such as csh or ksh such files are usually called executable scripts in simple termsunix-style executable scripts are just normal text files containing python statementsbut with two special propertiestheir first line is special scripts usually start with line that begins with the characters #(often called "hash bangor "shebang")followed by the path to the python interpreter on your machine they usually have executable privileges script files are usually marked as executable to tell the operating system that they may be run as top-level programs on unix systemsa command such as chmod + file py usually does the trick let' look at an example for unix-like systems use your text editor again to create file of python code called brian#!/usr/local/bin/python print('the bright side 'of life 'means concatenate for strings the special line at the top of the file tells the system where the python interpreter lives technicallythe first line is python comment as mentioned earlierall comments in python programs start with and span to the end of the linethey are place to insert extra information for human readers of your code but when comment such as the unix-style executable scripts#
638
it to find an interpreter for running the program code in the rest of the file alsonote that this file is called simply brianwithout the py suffix used for the module file earlier adding py to the name wouldn' hurt (and might help you remember that this is python program file)but because you don' plan on letting other modules import the code in this filethe name of the file is irrelevant if you give the file executable privileges with chmod + brian shell commandyou can run it from the operating system shell as though it were binary program (for the followingeither make sure the current directoryis in your system path settingor run this with /brian)brian the bright side of life the unix env lookup trick on some unix systemsyou can avoid hardcoding the path to the python interpreter in your script file by writing the special first-line comment like this#!/usr/bin/env python script goes here when coded this waythe env program locates the python interpreter according to your system search path settings (in most unix shellsby looking in all the directories listed in your path environment variablethis scheme can be more portableas you don' need to hardcode python install path in the first line of all your scripts that wayif your scripts ever move to new machineor your python ever moves to new locationyou must update just pathnot all your scripts provided you have access to env everywhereyour scripts will run no matter where python lives on your system in factthis env form is generally recommended today over even something as generic as /usr/bin/pythonbecause some platforms may install python elsewhere of coursethis assumes that env lives in the same place everywhere (on some machinesit may be in /sbin/binor elsewhere)if notall portability bets are offthe python windows launcher#comes to windows note for windows users running python and earlierthe method described here is unix trickand it may not work on your platform not to worryjust use the basic command-line technique explored earlier list the file' name on an explicit python command line: :\codepython brian the bright side of life in this caseyou don' need the special #comment at the top (although python just ignores it if it' present)and the file doesn' need to be given executable privileges in factif you want to run files portably between unix and microsoft windowsyour life how you run programs
639
if you're using python or laterthoughor have its windows launcher installed separatelyit turns out that unix-style #lines do mean something on windows too besides offering the py executable described earlierthe new windows launcher mentioned earlier attempts to parse #lines to determine which python version to launch to run your script' code moreoverit allows you to give the version number in full or partial formsand recognizes most common unix patterns for this lineincluding the /usr/bin/env form the launcher' #parsing mechanism is applied when you run scripts from command lines with the py programand when you click python file icons (in which case py is run implicitly by filename associationsunlike unixyou do not need to mark files with executable privileges for this to work on windowsbecause filename associations achieve similar results for examplethe first of the following is run by python and the second by (without an explicit numberthe launcher defaults to unless you set py_python environment variable) :\codetype robin py #!/usr/bin/python print('run''away' :\codepy robin py run awayc:\codetype robin py #!python print 'run''away morec:\codepy robin py run away more function run file per #line version statement run file per #line version this works in addition to passing versions on command lines--we saw this briefly earlier for starting the interactive promptbut it works the same when launching script filec:\codepy - robin py run awayrun per command-line argument the net effect is that the launcher allows python versions to be specified on both perfile and per-command basisby using #lines and command-line argumentsrespec as we discussed when exploring command linesall recent windows versions also let you type just the name of py file at the system command line--they use the registry to determine that the file should be opened with python ( typing brian py is equivalent to typing python brian pythis command-line mode is similar in spirit to the unix #!though it is system-wide on windowsnot per-file it also requires an explicit py extensionfilename associations won' work without it some programs may actually interpret and use first #line on windows much like on unix (including python ' windows launcher)but the system shell on windows itself simply ignores it unix-style executable scripts#
640
or later on windows or may in the futurei recommend side trip to the full launcher story in appendix if you haven' made one already clicking file icons if you're not fan of command linesyou can generally avoid them by launching python scripts with file icon clicksdevelopment guisand other schemes that vary per platform let' take quick look at the first of these alternatives here icon-click basics icon clicks are supported on most platforms in one form or another here' rundown of how these might be structured on your computerwindows icon clicks on windowsthe registry makes opening files with icon clicks easy when installedpython uses windows filename associations to automatically register itself to be the program that opens python program files when they are clicked because of thatit is possible to launch the python programs you write by simply clicking (or double-clickingon their file icons with your mouse cursor specificallya clicked file will be run by one of two python programsdepending on its extension and the python you're running in pythons and earlierpy files are run by python exe with console (command promptwindowand pyw files are run by pythonw exe files without console byte code files are also run by these programs if clicked per appendix bin python and later (and where it' installed separately)the new window' launchers' py exe and pyw exe programs serve the same rolesopening py and pyw filesrespectively non-windows icon clicks on non-windows systemsyou will probably be able to perform similar featbut the iconsfile explorer navigation schemesand more may differ slightly on mac os xfor instanceyou might use pythonlauncher in the macpython (or python mfolder of your applications folder to run by clicking in finder on some linux and other unix systemsyou may need to register the py extension with your file explorer guimake your script executable using the #line scheme of the preceding sectionor associate the file mime type with an application or command by editing filesinstalling programsor using other tools see your file explorer' documentation for more details in other wordsicon clicks generally work as you' expect for your platformbut be sure to see the platform usage documentation "python setup and usagein python' standard manual set for more details as needed how you run programs
641
to illustratelet' keep using the script we wrote earlierscript pyrepeated here to minimize page flippinga first python script import sys print(sys platformprint( * 'spam!print( load library module raise to power string repetition as we've seenyou can always run this file from system command linec:\codepython script py win spam!spam!spam!spam!spam!spam!spam!spamhowevericon clicks allow you to run the file without any typing at all to do soyou have to find this file' icon on your computer on windows you might right-click the screen' lower-left corner to open file explorer on earlier windowsyou can select computer (or my computer in xpin your start button' menu there are additional ways to open file exploreronce you dowork your way down on the drive to your working directory at this pointyou should have file explorer window similar to that captured in figure - (windows is being used herenotice how the icons for python files show upsource files have white backgrounds on windows byte code files show with black backgrounds per the prior created the byte code file in this figure by importing in python and later instead store byte code files in the __pycache__ subdirectory also shown herewhich created by importing in too you will normally want to click (or otherwise runthe white source code files in order to pick up your most recent changesnot the byte code files--python won' check the source code file for changes if you launch byte code directly to launch the file heresimply click on the icon for script py the input trick on windows unfortunatelyon windowsthe result of clicking on file icon may not be incredibly satisfying in factas it isthis example script might generate perplexing "flashwhen clicked--not exactly the sort of feedback that budding python programmers usually hope forthis is not bugbut has to do with the way the windows version of python handles printed output by defaultpython generates pop-up black dos console window (command promptto serve as clicked file' input and output if script just prints and exitswellit just clicking file icons
642
automatically be run with double-click of the mouse (though you might not see printed output or error messages this wayprints and exits--the console window appearsand text is printed therebut the console window closes and disappears on program exit unless you are very fastor your machine is very slowyou won' get to see your output at all although this is normal behaviorit' probably not what you had in mind luckilyit' easy to work around this if you need your script' output to stick around when you launch it with an icon clicksimply put call to the built-in input function at the very bottom of the script in (in use the name raw_input insteadsee the note aheadfor examplea first python script import sys print(sys platformprint( * 'spam!print( input(load library module raise to power string repetition <=added in generalinput reads and returns the next line of standard inputwaiting if there is none yet available the net effect in this context will be to pause the scriptthereby keeping the output window shown in figure - open until you press the enter key now that 've shown you this trickkeep in mind that it is usually only required for windowsand then only if your script prints text and exits and only if you will launch the script by clicking its file icon you should add this call to the bottom of your toplevel files if and only if all of these three conditions apply there is no reason to add this call in any other contextssuch as scripts you'll run in command lines or the idle gui (unless you're unreasonably fond of pressing your computer' enter key! that may sound obviousbut it' been another common mistake in live classes how you run programs
643
if you include an input call at the very end of the script but you only need to do so in this one contextbefore we move aheadnote that the input call applied here is the input counterpart of using the print function (and statementfor outputs it is the simplest way to read user inputand it is more general than this example implies for instanceinputoptionally accepts string that will be printed as prompt ( input('press enter to exit')returns to your script line of text read as string ( nextinput input()supports input stream redirections at the system shell level ( python spam py input txt)just as the print statement does for output we'll use input in more advanced ways later in this textfor instance will apply it in an interactive loop for nowit will help you see the output of simple scripts that you click to launch version skew noteif you are working in python xuse raw_input(instead of input(in this code the former was renamed to the latter in python technically has an input function toobut it also evaluates strings as though they are program code typed into scriptand so will not work in this context (an empty string is an errorpython ' input (and ' raw_inputsimply returns the entered text as character stringunevaluated to simulate ' input in xuse eval(input()be awarethoughthat because this runs the entered text as though it were program codethis may have security implications that we'll largely converselyit is also possible to completely suppress the pop-up console window ( command promptfor clicked files on windows when you don' want to see printed text files whose names end in pyw extension will display only windows constructed by your scriptnot the default console window pyw files are simply py source files that have this special operational behavior on windows they are mostly used for python-coded user interfaces that build windows of their ownoften in conjunction with various techniques for saving printed output and errors to files as implied earlierpython achieves this when it is installed by associating special executable (pythonw exe in and earlier and pyw exe as of to open pyw files when clicked clicking file icons
644
textif you don'tstick to just plain input in and raw_input in other icon-click limitations even with the prior section' input trickclicking file icons is not without its perils you also may not get to see python error messages if your script generates an errorthe error message text is written to the pop-up console window--which then immediately disappearsworseadding an input call to your file will not help this time because your script will likely abort long before it reaches this call in other wordsyou won' be able to tell what went wrong when we discuss exceptions later in this bookyou'll learn that it is possible to write code to interceptprocessand recover from errors so that they do not terminate your programs watch for the discussion of the try statement later in this book for an alternative way to keep the console window from closing on errors we'll also learn how to redirect printed text to files for later inspection when we study print operations barring such support in your codethougherrors and prints disappear for clicked programs because of these limitationsit is probably best to view icon clicks as way to launch programs after they have been debuggedor have been instrumented to write their output to file and catch and process any important errors especially when you're starting outi recommend using other techniques--such as system command lines and idle (discussed further in the section "the idle user interfaceon page )--so that you can see generated error messages and view your normal output without resorting to extra coding module imports and reloads so fari've been talking about "importing moduleswithout really explaining what this term means we'll study modules and larger program architecture in depth in part vbut because imports are also way to launch programsthis section will introduce enough module basics to get you started import and reload basics in simple termsevery file of python source code whose name ends in py extension is module no special code or syntax is required to make file moduleany such file will do other files can access the items module defines by importing that module --import operations essentially load another file and grant access to that file' contents the contents of module are made available to the outside world through its attributes ( term 'll define in the next section how you run programs
645
import tools from other module files one of the modules is designated as the main or top-level fileor "script"--the file launched to start the entire programwhich runs line by line as usual below this levelit' all modules importing modules we'll delve into such architectural issues in more detail later in this book this is mostly interested in the fact that import operations run the code in file that is being loaded as final step because of thisimporting file is yet another way to launch it for instanceif you start an interactive session (from system command line or otherwise)you can run the script py file you created earlier with simple import (be sure to delete the input line you added in the prior section firstor you'll need to press enter for no reason) :\codec:\python \python import script win spam!spam!spam!spam!spam!spam!spam!spamthis worksbut only once per session (reallyprocess-- program runby default after the first importlater imports do nothingeven if you change and save the module' source file again in another windowchange script py in text edit window to print * import script import script this is by designimports are too expensive an operation to repeat more than once per fileper program run as you'll learn in imports must find filescompile them to byte codeand run the code if you really want to force python to run the file again in the same session without stopping and restarting the sessionyou need to instead call the reload function available in the imp standard library module (this function is also simple built-in in python xbut not in )from imp import reload must load from module in (onlyreload(script win spam!spam!spam!spam!spam!spam!spam!spamthe from statement here simply copies name out of module (more on this soonthe reload function itself loads and runs the current version of your file' codepicking up changes if you've modified and saved it in another window module imports and reloads
646
interactive session in this sessionfor examplethe second print statement in script py was changed in another window to print * between the time of the first import and the reload call--hence the different result the reload function expects the name of an already loaded module objectso you have to have successfully imported module once before you reload it (if the import reported an erroryou can' yet reload and must import againnotice that reload also expects parentheses around the module object namewhereas import does not reload is function that is calledand import is statement that' why you must pass the module name to reload as an argument in parenthesesand that' why you get back an extra output line when reloading--the last output line is just the display representation of the reload call' return valuea python module object we'll learn more about using functions in general in for nowwhen you hear "function,remember that parentheses are required to run call version skew notepython moved the reload built-in function to the imp standard library module it still reloads files as beforebut you must import it in order to use it in xrun an import imp and use imp reload( )or run from imp import reload and use reload( )as shown here we'll discuss import and from statements in the next sectionand more formally later in this book if you are working in python xreload is available as built-in functionso no import is required in python and reload is available in both forms--built-in and module function--to aid the transition to in other wordsreloading is still available in xbut an extra line of code is required to fetch the reload call the move in was likely motivated in part by some well-known issues involving reload and from statements that we'll encounter in the next section in shortnames loaded with from are not directly updated by reloadbut names accessed with an import statement are if your names don' seem to change after reloadtry using import and mod ule attribute name references instead the grander module storyattributes imports and reloads provide natural program launch option because import operations execute files as last step in the broader scheme of thingsthoughmodules serve the role of libraries of toolsas you'll learn in detail in part the basic idea is straightforwardthougha module is mostly just package of variable namesknown as namespaceand the names within that package are called attributes an attribute is simply variable name that is attached to specific object (like modulein more concrete termsimporters gain access to all the names assigned at the top level of module' file these names are usually assigned to tools exported by the module how you run programs
647
and other programs externallya module file' names can be fetched with two python statementsimport and fromas well as the reload call to illustrateuse text editor to create one-line python module file called myfile py in your working directorywith the following contentstitle "the meaning of lifethis may be one of the world' simplest python modules (it contains single assignment statement)but it' enough to illustrate the point when this file is importedits code is run to generate the module' attribute that isthe assignment statement creates variable and module attribute named title you can access this module' title attribute in other components in two different ways firstyou can load the module as whole with an import statementand then qualify the module name with the attribute name to fetch it (note that we're letting the interpreter print automatically here)python import myfile myfile title 'the meaning of lifestart python run fileload module as whole use its attribute namesto qualify in generalthe dot expression syntax object attribute lets you fetch any attribute attached to any objectand is one of the most common operations in python code herewe've used it to access the string variable title inside the module myfile--in other wordsmyfile title alternativelyyou can fetch (reallycopynames out of module with from statementspython from myfile import title title 'the meaning of lifestart python run filecopy its names use name directlyno need to qualify as you'll see in more detail laterfrom is just like an importwith an extra assignment to names in the importing component technicallyfrom copies module' attributessuch that they become simple variables in the recipient--thusyou can simply refer to the imported string this time as title ( variableinstead of myfile title (an attribute reference whether you use import or from to invoke an import operationthe statements in the module file myfile py are executedand the importing component (herethe interactive promptgains access to names assigned at the top level of the file there' only one such name in this simple example--the variable titleassigned to string--but the notice that import and from both list the name of the module file as simply myfile without its py extension suffix as you'll learn in part vwhen python looks for the actual fileit knows to include the suffix in its search procedure againyou must include the py suffix in system shell command linesbut not in import statements module imports and reloads
648
classes in your modulessuch objects become reusable software components that can be accessed by name from one or more client modules in practicemodule files usually define more than one name to be used in and outside the files here' an example that defines threea 'deadb 'parrotc 'sketchprint(abcdefine three attributes exported to other files also used in this file (in xprint abcthis filethreenames pyassigns three variablesand so generates three attributes for the outside world it also uses its own three variables in print statementas we see when we run this as top-level file (in python print differs slightlyso omit its outer parenthesis to match the output here exactlywatch for more complete explanation of this in )python threenames py dead parrot sketch all of this file' code runs as usual the first time it is imported elsewhereby either an import or from clients of this file that use import get module with attributeswhile clients that use from get copies of the file' namespython import threenames dead parrot sketch threenames bthreenames ('parrot''sketch'from threenames import abc bc ('parrot''sketch'grab the whole moduleit runs here access its attributes copy multiple names out the results here are printed in parentheses because they are really tuples-- kind of object created by the comma in the inputs (and covered in the next part of this book--that you can safely ignore for now once you start coding modules with multiple names like thisthe built-in dir function starts to come in handy--you can use it to fetch list of all the names available inside module the following returns python list of strings in square brackets (we'll start studying lists in the next dir(threenames['__builtins__''__doc__''__file__''__name__''__package__'' '' '' 'the contents of this list have been edited here because they vary per python version the point to notice here is that when the dir function is called with the name of an imported module in parentheses like thisit returns all the attributes inside that module some of the names it returns are names you get "for free"names with leading and trailing double underscores (__x__are built-in names that are always predefined by how you run programs
649
point in this book the variables our code defined by assignment--aband --show up last in the dir result modules and namespaces module imports are way to run files of codebutas we'll expand on later in the bookmodules are also the largest program structure in python programsand one of the first key concepts in the language as we've seenpython programs are composed of multiple module files linked together by import statementsand each module file is package of variables--that isa namespace just as importantlyeach module is self-contained namespaceone module file cannot see the names defined in another file unless it explicitly imports that other file because of thismodules serve to minimize name collisions in your code--because each file is self-contained namespacethe names in one file cannot clash with those in anothereven if they are spelled the same way in factas you'll seemodules are one of handful of ways that python goes to great lengths to package your variables into compartments to avoid name clashes we'll discuss modules and other namespace constructs--including local scopes defined by classes and functions--further later in the book for nowmodules will come in handy as way to run your code many times without having to retype itand will prevent your file' names from accidentally replacing each other import versus fromi should point out that the from statement in sense defeats the namespace partitioning purpose of modules--because the from copies variables from one file to anotherit can cause same-named variables in the importing file to be overwrittenand won' warn you if it does this essentially collapses namespaces togetherat least in terms of the copied variables because of thissome recommend always using import instead of from won' go that farthoughnot only does from involve less typing (an asset at the interactive prompt)but its purported problem is relatively rare in practice besidesthis is something you control by listing the variables you want in the fromas long as you understand that they'll be assigned to values in the target modulethis is no more dangerous than coding assignment statements--another feature you'll probably want to useusage notesimport and reload for some reasononce people find out about running files using import and reloadmany tend to focus on this alone and forget about other launch options that always run the current version of the code ( icon clicksidle menu optionsand system command linesthis approach can quickly lead to confusionthough--you need to module imports and reloads
650
use parentheses when you call reload (only)and you need to remember to use reload in the first place to get the current version of your code to run moreoverreloads aren' transitive--reloading module reloads that module onlynot any modules it may import--so you sometimes have to reload multiple files because of these complications (and others we'll explore laterincluding the reloadfrom issue mentioned briefly in prior note in this it' generally good idea to avoid the temptation to launch by imports and reloads for now the idle run-run module menu option described in the next sectionfor exampleprovides simpler and less error-prone way to run your filesand always runs the current version of your code system shell command lines offer similar benefits you don' need to use reload if you use any of these other techniques in additionyou may run into trouble if you use modules in unusual ways at this point in the book for instanceif you want to import module file that is stored in directory other than the one you're working inyou'll have to skip ahead to and learn about the module search path for nowif you must importtry to keep all your files in the directory you are working in to avoid complications that saidimports and reloads have proven to be popular testing technique in python classesand you may prefer using this approach too as usualthoughif you find yourself running into wallstop running into wallusing exec to run module files strictly speakingthere are more ways to run code stored in module files than have yet been presented here for instancethe exec(open('module py'read()built-in function call is another way to launch files from the interactive prompt without having to import and later reload each such exec runs the current version of the code read from filewithout requiring later reloads (script py is as we left it after reload in the prior section)python exec(open('script py'read()win spam!spam!spam!spam!spam!spam!spam!spamchange script py in text edit window to print * exec(open('script py'read() if you're too curious to waitthe short story is that python searches for imported modules in every directory listed in sys path-- python list of directory name strings in the sys modulewhich is initialized from pythonpath environment variableplus set of standard directories if you want to import from directory other than the one you are working inthat directory must generally be listed in your pythonpath setting for more detailssee and appendix how you run programs
651
spam!spam!spam!spam!spam!spam!spam!spamthe exec call has an effect similar to an importbut it doesn' actually import the module --by defaulteach time you call exec this way it runs the file' code anewas though you had pasted it in at the place where exec is called because of thatexec does not require module reloads after file changes--it skips the normal module import logic on the downsidebecause it works as if you've pasted code into the place where it is calledexeclike the from statement mentioned earlierhas the potential to silently overwrite variables you may currently be using for exampleour script py assigns to variable named if that name is also being used in the place where exec is calledthe name' value is replacedx exec(open('script py'read()same output 'spam!code run in this namespace by default its assignments can overwrite names here by contrastthe basic import statement runs the file only once per processand it makes the file separate module namespace so that its assignments will not change variables in your scope the price you pay for the namespace partitioning of modules is the need to reload after changes version skew notepython also includes an execfile('module py'built-in functionin addition to allowing the form exec(open('mod ule py'))which both automatically read the file' content both of these are equivalent to the exec(open('module py'read()formwhich is more complex but runs in both and unfortunatelyneither of these two simpler forms is available in xwhich means you must understand both files and their read methods to fully understand this technique today (this seems to be case of aesthetics trouncing practicality in xin factthe exec form in involves so much typing that the best advice may simply be not to do it-it' usually easier to launch files by typing system shell command lines or by using the idle menu options described in the next section for more on the file interfaces used by the exec formsee for more on exec and its cohortseval and compilesee and the idle user interface so farwe've seen how to run python code with the interactive promptsystem command linesunix-style scriptsicon clicksmodule importsand exec calls if you're looking for something bit more visualidle provides graphical user interface for the idle user interface
652
is usually referred to as an integrated development environment (ide)because it binds together various development tasks into single view in shortidle is desktop gui that lets you editrunbrowseand debug python programsall from single interface it runs portably on most python platformsincluding microsoft windowsx windows (for linuxunixand unix-like platforms)and the mac os (both classic and os xfor manyidle represents an easy-to-use alternative to typing command linesa less problem-prone alternative to clicking on iconsand great way for newcomers to get started editing and running code you'll sacrifice some control in the bargainbut this typically becomes important later in your python career idle startup details most readers should be able to use idle immediatelyas it is standard component on mac os and most linux installations todayand is installed automatically with standard python on windows because platforms specifics varythoughi need to give few pointers before we open the gui technicallyidle is python program that uses the standard library' tkinter gui toolkit (named tkinter in python xto build its windows this makes idle portable --it works the same on all major desktop platforms--but it also means that you'll need to have tkinter support in your python to use idle this support is standard on windowsmacsand linuxbut it comes with few caveats on some systemsand startup can vary per platform here are few platform-specific tipson windows and earlieridle is easy to start--it' always present after python installand has an entry in the start button menu for python in windows and earlier (see figure - shown previouslyyou can also select it by right-clicking on python program iconand launch it by clicking on the icon for the files idle pyw or idle py located in the idlelib subdirectory of python' lib directory in this modeidle is clickable python script that lives in :\python \lib\idlelibc:\python \lib\idlelibor similarwhich you can drag out to shortcut for oneclick access if desired on windows look for idle in your start tilesby search for "idle,by browsing your "all appsstart screen displayor by using file explorer to find the idle py file mentioned earlier you may want shortcut hereas you have no start button menu in desktop mode (at least todaysee appendix for more pointerson mac os everything required for idle is present as standard components in your operating system idle should be available to launch in applications under the macpython (or python mprogram folder one note heresome os ver idle is officially corruption of idebut it' really named in honor of monty python member eric idle see if you're not sure why how you run programs
653
on linux idle is also usually present as standard component today it might take the form of an idle executable or script in your pathtype this in shell to check on some machinesit may require an install (see appendix for pointers)and on others you may need to launch idle' top-level script from command line or icon clickrun the file idle py located in the idlelib subdirectory of python' /usr/lib directory (run find for the exact locationbecause idle is just python script on the module search path in the standard libraryyou can also generally run it on any platform and from any directory by typing the following in system command shell window ( in command prompt on windows)though you'll have to see appendix for more on python' - flagand part for more on the package syntax required here (blind trust will suffice at this point in the book) :\codepython - idlelib idle run idle py in package on module path for more on install issues and usage notes for windows and other platformsbe sure to see both appendix as well as the notes for your platform in "python setup and usagein python' standard manuals idle basic usage let' jump into an example figure - shows the scene after you start idle on windows the python shell window that opens initially is the main windowwhich runs an interactive session (notice the promptthis works like all interactive sessions --code you type here is run immediately after you type it--and serves as testing and experimenting tool idle uses familiar menus with keyboard shortcuts for most of its operations to make new script file under idleuse file-newin the main shell windowselect the file pull-down menuand pick new to open new text edit window where you can typesaveand run your file' code use file-open instead to open new text edit window displaying an existing file' code to edit and run although it may not show up fully in this book' graphicsidle uses syntax-directed colorization for the code typed in both the main window and all text edit windows-keywords are one colorliterals are anotherand so on this helps give you better picture of the components in your code (and can even help you spot mistakes--runon strings are all one colorfor exampleto run file of code that you are editing in idleuse run-run module in that file' text edit window that isselect the file' text edit windowopen that window' run pull-down menuand choose the run module option listed there (or use the equivalent keyboard shortcutgiven in the menupython will let you know that you need to save the idle user interface
654
windows use the file menu to begin (new windowor change (open source fileuse the text edit window' run menu to run the code in that window (run moduleyour file first if you've changed it since it was opened or last saved and forgot to save your changes-- common mistake when you're knee-deep in coding when run this waythe output of your script and any error messages it may generate show up back in the main interactive window (the python shell windowin figure - for examplethe three lines after the "restartline near the middle of the window reflect an execution of our script py file opened in separate edit window the "restartmessage tells us that the user-code process was restarted to run the edited script and serves to separate script output (it does not appear if idle is started without user-code subprocess--more on this mode in momentidle usability features like most guisthe best way to learn idle may be to test-drive it for yourselfbut some key usage points seem to be less than obvious for exampleif you want to repeat prior commands in idle' main interactive windowyou can use the alt- key combination to scroll backward through the command historyand alt- to scroll forward (on some macstry ctrl- and ctrl- insteadyour prior commands will be recalled and displayedand may be edited and rerun how you run programs
655
pressing enter to insert their text at the input promptor using standard cut-and-paste operationsthough these techniques tend to involve more steps (and can sometimes be triggered accidentallyoutside idleyou may be able to recall commands in an interactive session with the arrow keys on windows besides command history and syntax colorizationidle has additional usability features such asauto-indent and unindent for python code in the editor (backspace goes back one levelword auto-completion while typinginvoked by tab press balloon help pop ups for function call when you type its opening "(pop-up selection lists of object attributes when you type after an object' name and either pause or press tab some of these may not work on every platformand some can be configured or disabled if you find that their defaults get in the way of your personal coding style advanced idle tools besides the basic edit and run functions and the prior section' usability toolsidle provides more advanced featuresincluding point-and-click program graphical debugger and an object browser the idle debugger is enabled via the debug menu and the object browser via the file menu the browser allows you to navigate through the module search path to files and objects in filesclicking on file or object opens the corresponding source in text edit window you initiate idle debugging by selecting the debug-debugger menu option in the main window and then starting your script by selecting the run-run module option in the text edit windowonce the debugger is enabledyou can set breakpoints in your code that stop its execution by right-clicking on lines in the text edit windowsshow variable valuesand so on you can also watch program execution when debugging-the current line of code is noted as you step through your code for simpler debugging operationsyou can also right-click with your mouse on the text of an error message to quickly jump to the line of code where the error occurred-- trick that makes it simple and fast to repair and run again in additionidle' text editor offers large collection of programmer-friendly toolsincluding advanced text and file search operations we won' cover here because idle uses intuitive gui interactionsyou should experiment with the system live to get feel for its other tools the idle user interface
656
idle is freeeasy to useportableand automatically available on most platforms generally recommend it to python newcomers because it simplifies some startup details and does not assume prior experience with system command lines howeverit is somewhat limited compared to more advanced commercial idesand may seem heavier than command line to some to help you avoid some common pitfallshere is list of issues that idle beginners should bear in mindyou must add pyexplicitly when saving your files mentioned this when talking about files in generalbut it' common idle stumbling blockespecially for windows users idle does not automatically add py extension to filenames when files are saved be careful to type the py extension yourself when saving file for the first time if you don'twhile you will be able to run your file from idle (and system command lines)you will not be able to import it either interactively or from other modules run scripts by selecting run-run module in text edit windowsnot by interactive imports and reloads earlier in this we saw that it' possible to run file by importing it interactively howeverthis scheme can grow complex because it requires you to manually reload files after changes by contrastusing the run-run module menu option in idle always runs the most current version of your filejust like running it using system shell command line idle also prompts you to save your file firstif needed (another common mistake outside idleyou need to reload only modules being tested interactively like system shell command linesidle' run-run module menu option always runs the current version of both the top-level file and any modules it imports because of thisrun-run module eliminates common confusions surrounding imports you need to reload only modules that you are importing and testing interactively in idle if you choose to use the import and reload technique instead of run-run moduleremember that you can use the alt- /alt- key combinations to recall prior commands you can customize idle to change the text fonts and colors in idleselect the configure option in the options menu of any idle window you can also customize key combination actionsindentation settingsautocompletionsand moresee idle' help pull-down menu for more hints there is currently no clear-screen option in idle this seems to be frequent request (perhaps because it' an option available in similar ides)and it might be added eventually todaythoughthere is no way to clear the interactive window' text if you want the window' text to go awayyou can either press and hold the enter keyor type python loop to print series of blank lines (nobody really uses the latter techniqueof coursebut it sounds more high-tech than pressing the enter key! how you run programs
657
idle is python/tkinter programit can hang if you use it to run certain types of advanced python/tkinter programs this has become less of an issue in more recent versions of idle that run user code in one process and the idle gui itself in anotherbut some programs (especially those that use multithreadingmight still hang the gui even just calling the tkinter quit function in your codethe normal way to exit gui programmay be enough to cause your program' gui to hang if run in idle (destroy may be better here onlyyour code may not exhibit such problemsbut as rule of thumbit' always safe to use idle to edit gui programs but launch them using other optionssuch as icon clicks or system command lines when in doubtif your code fails in idletry it outside the gui if connection errors arisetry starting idle in single-process mode this issue appears to have gone away in recent pythonsbut may still impact readers using older versions because idle requires communication between its separate user and gui processesit can sometimes have trouble starting up on certain platforms (notablyit fails to start occasionally on some windows machinesdue to firewall software that blocks connectionsif you run into such connection errorsit' always possible to start idle with system command line that forces it to run in single-process mode without user-code subprocess and therefore avoids communication issuesits - command-line flag forces this mode on windowsfor examplestart command prompt window and run the system command line idle py - from within the directory :\python \lib\idlelib (cd there first if neededa python - idlelib idle - command works from anywhere (see appendix for -mbeware of some idle usability features idle does much to make life easier for beginnersbut some of its tricks won' apply outside the idle gui for instanceidle runs your scripts in its own interactive namespaceso variables in your code show up automatically in the idle interactive session--you don' always need to run import commands to access names at the top level of files you've already run this can be handybut it can also be confusingbecause outside the idle environment names must always be imported from files explicitly to be used when you run file of codeidle also automatically changes to that file' directory and adds it to the module import search path-- handy feature that allows you to use files and import modules there without search path settingsbut also something that won' work the same when you run files outside idle it' ok to use such featuresbut don' forget that they are idle behaviornot python behavior other ides because idle is freeportableand standard part of pythonit' nice first development tool to become familiar with if you want to use an ide at all againi recommend other ides
658
that you use idle for this book' exercises if you're just starting outunless you are already familiar with and prefer command-line-based development mode there arehowevera handful of alternative ides for python developerssome of which are substantially more powerful and robust than idle apart from idlehere are some of python' most commonly used ideseclipse and pydev eclipse is an advanced open source ide gui originally developed as java ideeclipse also supports python development when you install the pydev (or similarplug-in eclipse is popular and powerful option for python developmentand it goes well beyond idle' feature set it includes support for code completionsyntax highlightingsyntax analysisrefactoringdebuggingand more its downsides are that it is large system to install and may require shareware extensions for some features (this may vary over timestillwhen you are ready to graduate from idlethe eclipse/pydev combination is worth your attention komodo full-featured development environment gui for python (and other languages)komodo includes standard syntax coloringtext editingdebuggingand other features in additionkomodo offers many advanced features that idle does notincluding project filessource-control integrationand regular-expression debugging at this writingkomodo is not freebut see the web for its current status-it is available at activepython distribution package mentioned in appendix netbeans ide for python netbeans is powerful open source development environment gui with support for many advanced features for python developerscode completionautomatic indentation and code colorizationeditor hintscode foldingrefactoringdebuggingcode coverage and testingprojectsand more it may be used to develop both cpython and jython code like eclipsenetbeans requires installation steps beyond those of the included idle guibut it is seen by many as more than worth the effort search the web for the latest information and links pythonwin pythonwin is free windows-only ide for python that ships as part of activestate' activepython distribution (and may also be fetched separately from www python org resourcesit is roughly like idlewith handful of useful windows-specific extensions addedfor examplepythonwin has support for com objects todayidle is probably more advanced than pythonwin (for instanceidle' dual-process architecture often prevents it from hanginghoweverpythonwin still offers tools for windows developers that idle does not see www activestate com for more information wingvisual studioand others other ides are popular among python developers tooincluding the mostly commercial wing idemicrosoft visual studio via plug-inand pycharmpyscrip how you run programs
659
more will undoubtedly appear over time in factalmost every programmer-friendly text editor has some sort of support for python development these dayswhether it be preinstalled or fetched separately emacs and vimfor instancehave substantial python support ide choices are often subjectiveso encourage you to browse to find tools that fit your development style and goals for more informationsee the resources available at search for "python editorstoday leads you to wiki page that maintains information about dozens of ide and text-editor options for python programming other launch options at this pointwe've seen how to run code typed interactivelyand how to launch code saved in files in variety of ways--system command linesicon clicksimports and execsguis like idleand more that covers most of the techniques in common useand enough to run the code you'll see in this book there are additional ways to run python codethoughmost of which have special or narrow roles for completeness and referencethe next few sections take quick look at some of these embedding calls in some specialized domainspython code may be run automatically by an enclosing system in such caseswe say that the python programs are embedded in ( run byanother program the python code itself may be entered into text filestored in databasefetched from an html pageparsed from an xml documentand so on but from an operational perspectiveanother system--not you--may tell python to run the code you've created such an embedded execution mode is commonly used to support end-user customization-- game programfor instancemight allow for play modifications by running user-accessible embedded python code at strategic points in time users can modify this type of system by providing or changing python code because python code is interpretedthere is no need to recompile the entire system to incorporate the change (see for more on how python code is runin this modethe enclosing system that runs your code might be written in cc++or even java when the jython system is used as an exampleit' possible to create and run strings of python code from program by calling functions in the python runtime api ( set of services exported by the libraries created when python is compiled on your machine)#include other launch options
660
pyrun_simplestring(" 'brave 'sir robin'")/this is cnot python /but it runs python code in this code snippeta program coded in the language embeds the python interpreter by linking in its librariesand passes it python assignment statement string to run programs may also gain access to python modules and objects and process or execute them using other python api tools this book isn' about python/ integrationbut you should be aware thatdepending on how your organization plans to use pythonyou may or may not be the one who actually starts the python programs you create regardlessyou can usually still use the interactive and file-based launching techniques described here to test code in isolation from those enclosing systems that may eventually use it frozen binary executables frozen binary executablesdescribed in are packages that combine your program' byte code and the python interpreter into single executable program this approach enables python programs to be launched in the same ways that you would launch any other executable program (icon clickscommand linesetc while this option works well for delivery of productsit is not really intended for use during program developmentyou normally freeze just before shipping (after development is finishedsee the prior for more on this option text editor launch options as mentioned previouslyalthough they're not full-blown ide guismost programmer-friendly text editors have support for editingand possibly runningpython programs such support may be built in or fetchable on the web for instanceif you are familiar with the emacs text editoryou can do all your python editing and launching from inside that text editor see the text editor resources page at org/editors for more detailsor search the web for the phrase "python editors still other launch options depending on your platformthere may be additional ways that you can start python programs for instanceon some macintosh systems you may be able to drag python program file icons onto the python interpreter icon to make them executeand on some windows systems you can always start python scripts with the run option in the start menu additionallythe python standard library has utilities that allow python programs to be started by other python programs in separate processes ( os popen see programming python ( 'reillyfor more details on embedding python in / +the embedding api can call python functions directlyload modulesand more alsonote that the jython system allows java programs to invoke python code using java-based api ( python interpreter class how you run programs
661
(for instancea web page might invoke script on server)howeverthese are beyond the scope of the present future possibilitiesthis reflects current practicebut much of the material is both platformand time-specific indeedmany of the execution and launch details presented arose during the shelf life of this book' various editions as with program execution optionsit' not impossible that new program launch options may arise over time new operating systemsand new versions of existing systemsmay also provide execution techniques beyond those outlined here in generalbecause python keeps pace with such changesyou should be able to launch python programs in whatever way makes sense for the machines you useboth now and in the future--be that by swiping on tablet pcs and smartphonesgrabbing icons in virtual realityor shouting script' name over your coworkersconversations implementation changes may also impact launch schemes somewhat ( full compiler could produce normal executables that are launched much like frozen binaries todayif knew what the future truly heldthoughi would probably be talking to stockbroker instead of writing these wordswhich option should usewith all these optionstrue beginners might naturally askwhich one is best for mein generalyou should give the idle interface try if you are just getting started with python it provides user-friendly gui environment and hides some of the underlying configuration details it also comes with platform-neutral text editor for coding your scriptsand it' standard and free part of the python system ifon the other handyou are an experienced programmeryou might be more comfortable with simply the text editor of your choice in one windowand another window for launching the programs you edit via system command lines and icon clicks (in factthis is how develop python programsbut have unix-biased distant pastbecause the choice of development environments is very subjectivei can' offer much more in the way of universal guidelines in generalwhatever environment you like to use will be the best for you to use debugging python code naturallynone of my readers or students ever have bugs in their code (insert smiley here)but for less fortunate friends of yours who mayhere' quick review of the strategies commonly used by real-world python programmers to debug codefor you to refer to as you start coding in earnestwhich option should use
662
code--but when you make mistake in python programyou get very useful and readable error message (you'll get to see some soonif you haven' alreadyif you already know pythonand especially for your own codethis is often enough --read the error messageand go fix the tagged line and file for manythis is debugging in python it may not always be ideal for larger systems you didn' writethough insert print statements probably the main way that python programmers debug their code (and the way that debug python codeis to insert print statements and run again because python runs immediately after changesthis is usually the quickest way to get more information than error messages provide the print statements don' have to be sophisticated-- simple " am hereor display of variable values is usually enough to provide the context you need just remember to delete or comment out ( add beforethe debugging prints before you ship your codeuse ide gui debuggers for larger systems you didn' writeand for beginners who want to trace code in more detailmost python development guis have some sort of point-and-click debugging support idle has debugger toobut it doesn' appear to be used very often in practice--perhaps because it has no command lineor perhaps because adding print statements is usually quicker than setting up gui debugging session to learn moresee idle' helpor simply try it on your ownits basic interface is described in the section "advanced idle toolson page other idessuch as eclipsenetbeanskomodoand wing ideoffer advanced point-and-click debuggers as wellsee their documentation if you use them use the pdb command-line debugger for ultimate controlpython comes with source code debugger named pdbavailable as module in python' standard library in pdbyou type commands to step line by linedisplay variablesset and clear breakpointscontinue to breakpoint or errorand so on you can launch pdb interactively by importing itor as top-level script either waybecause you can type commands to control the sessionit provides powerful debugging tool pdb also includes postmortem function (pdb pm()that you can run after an exception occursto get information from the time of the error see the python library manual and for more details on pdband appendix for an example or running pdb as script with python' - command argument use python' - command-line argument short of adding prints or running under pdbyou can still see what went wrong on errors if you run your script from command line and pass - argument between python and the name of your script ( python - py)python will enter into its interactive interpreter mode (the promptwhen your script exitswhether it ends successfully or runs into an error at this pointyou can print the final values of variables to get more details about what happened in your code because they are in the top-level namespace you can also then import and run the pdb debugger for even more contextits postmortem mode will let you inspect the latest error if your script failed appendix also shows - in action how you run programs
663
tools in the open source domainincluding support for multithreaded programsembedded codeand process attachment the winpdb systemfor exampleis standalone debugger with advanced debugging support and cross-platform gui and console interfaces these options will become more important as we start writing larger scripts probably the best news on the debugging frontthoughis that errors are detected and reported in pythonrather than passing silently or crashing the system altogether in facterrors themselves are well-defined mechanism known as exceptionswhich you can catch and process (more on exceptions in part viimaking mistakes is never funof coursebut take it from someone who recalls when debugging meant getting out hex calculator and poring over piles of memory dump printoutspython' debugging support makes errors much less painful than they might otherwise be summary in this we've looked at common ways to launch python programsby running code typed interactivelyand by running code stored in files with system command linesfile icon clicksmodule importsexec callsand ide guis such as idle we've covered lot of pragmatic startup territory here this goal was to equip you with enough information to enable you to start writing some codewhich you'll do in the next part of the book therewe will start exploring the python language itselfbeginning with its core data types--the objects that are the subjects of your programs firstthoughtake the usual quiz to exercise what you've learned here because this is the last in this part of the bookit' followed with set of more complete exercises that test your mastery of this entire part' topics for help with the latter set of problemsor just for refresherbe sure to turn to appendix after you've given the exercises try test your knowledgequiz how can you start an interactive interpreter session where do you type system command line to launch script file name four or more ways to run the code saved in script file name two pitfalls related to clicking file icons on windows why might you need to reload module how do you run script from within idle name two pitfalls related to using idle what is namespaceand how does it relate to module filestest your knowledgequiz
664
you can start an interactive session on windows and earlier by clicking your start buttonpicking the all programs optionclicking the python entryand selecting the "python (command line)menu option you can also achieve the same effect on windows and other platforms by typing python as system command line in your system' console window ( command prompt window on windowsanother alternative is to launch idleas its main python shell window is an interactive session depending on your platform and pythonif you have not set your system' path variable to find pythonyou may need to cd to where python is installedor type its full directory path instead of just python ( :\python \python on windowsunless you're using the launcher you type system command lines in whatever your platform provides as system consolea command prompt window on windowsan xterm or terminal window on unixlinuxand mac os xand so on you type this at the system' promptnot at the python interactive interpreter' "prompt--be careful not to confuse these prompts code in script (reallymodulefile can be run with system command linesfile icon clicksimports and reloadsthe exec built-in functionand ide gui selections such as idle' run-run module menu option on unixthey can also be run as executables with the #trickand some platforms support more specialized launching techniques ( drag and dropin additionsome text editors have unique ways to run python codesome python programs are provided as standalone "frozen binaryexecutablesand some systems use python code in embedded modewhere it is run automatically by an enclosing program written in language like cc++or java the latter technique is usually done to provide user customization layer scripts that print and then exit cause the output file to disappear immediatelybefore you can view the output (which is why the input trick comes in handy)error messages generated by your script also appear in an output window that closes before you can examine its contents (which is one reason that system command lines and ides such as idle are better for most development python imports (loadsa module only once per processby defaultso if you've changed its source code and want to run the new version without stopping and restarting pythonyou'll have to reload it you must import module at least once before you can reload it running files of code from system shell command linevia an icon clickor via an ide such as idle generally makes this nonissueas those launch schemes usually run the current version of the source code file each time within the text edit window of the file you wish to runselect the window' run-run module menu option this runs the window' source code as top-level script file and displays its output back in the interactive python shell window how you run programs
665
perform multithreading (an advanced technique beyond this book' scopealsoidle has some usability features that can burn you once you leave the idle guia script' variables are automatically imported to the interactive scope in idle and working directories are changed when you run filefor instancebut python itself does not take such steps in general namespace is just package of variables ( namesit takes the form of an object with attributes in python each module file is automatically namespace-that isa package of variables reflecting the assignments made at the top level of the file namespaces help avoid name collisions in python programsbecause each module file is self-contained namespacefiles must explicitly import other files in order to use their names test your knowledgepart exercises it' time to start doing little coding on your own this first exercise session is fairly simplebut it' designed to make sure you're ready to work along with the rest of the bookand few of its questions hint at topics to come in later be sure to check part in appendix for the answersthe exercises and their solutions sometimes contain supplemental information not discussed in the main textso you should take peek at the solutions even if you manage to answer all the questions on your own interaction using system command lineidleor any other method that works on your platformstart the python interactive command line prompt)and type the expression "hello world!(including the quotesthe string should be echoed back to you the purpose of this exercise is to get your environment configured to run python in some scenariosyou may need to first run cd shell commandtype the full path to the python executableor add its path to your path environment variable if desiredyou can set path in your cshrc or kshrc file to make python permanently available on unix systemson windowsthe environment variable gui is usually what you want for this see appendix for help with environment variable settings programs with the text editor of your choicewrite simple module file containing the single statement print('hello module world!'and store it as module py nowrun this file by using any launch option you likerunning it in idleclicking on its file iconpassing it to the python interpreter on the system shell' command line ( python module py)built-in exec callsimports and reloadsand so on in factexperiment by running your file with as many of the launch techniques discussed in this as you can which technique seems easiest(there is no right answer to thisof course modules start the python interactive command line promptand import the module you wrote in exercise try moving the file to different directory and importing it again from its original directory ( run python in the original ditest your knowledgepart exercises
666
code file in the original directoryor something similar in __pycache__ subdirectory there? scripts if your platform supports itadd the #line to the top of your module py module filegive the file executable privilegesand run it directly as an executable what does the first line need to contain#usually only has meaning on unixlinuxand unix-like platforms such as mac os xif you're working on windowsinstead try running your file by listing just its name in command prompt window without the word "pythonbefore it (this works on recent versions of windows)via the start-run dialog boxor similar if you are using python or the windows launcher that installs with itexperiment with changing your script' #line to launch different python versions you may have installed on your computer (or equivalentlywork through the tutorial in appendix errors and debugging experiment with typing mathematical expressions and assignments at the python interactive command line along the waytype the expressions * and and reference an undefined variable name as we did early on in this what happensyou may not know it yetbut when you make mistakeyou're doing exception processinga topic we'll explore in depth in part vii as you'll learn thereyou are technically triggering what' known as the default exception handler--logic that prints standard error message if you do not catch an errorthe default handler does and prints the standard error message in response exceptions are also bound up with the notion of debugging in python when you're first starting outpython' default error messages on exceptions will probably provide as much error-handling support as you need--they give the cause of the erroras well as showing the lines in your code that were active when the error occurred for more about debuggingsee the sidebar "debugging python codeon page breaks and cycles at the python command linetypel [ append(ll make -item list append as single item to itself print la cyclic/circular object what happensin all recent versions of pythonyou'll see strange output that we'll describe in the solutions appendixand which will make more sense when we study references in the next part of the book if you're using python version older than ctrl- key combination will probably help on most platforms why do you think your version of python responds the way it does for this codeif you do have python older than release ( hopefully rare scenario today!)make sure your machine can stop program with ctrl- key combination of some sort before running this testor you may be waiting long time how you run programs
667
library and the structure of the documentation set it takes at least this long to become familiar with the locations of major topics in the manual setonce you've done thisit' easy to find what you need you can find this manual via the python start button entry on some windowsin the python docs option on the help pulldown menu in idleor online at more words to say about the manuals and other documentation sources available (including pydoc and the help functionin if you still have timego explore the python websiteas well as its pypi third-party extension repository especially check out the python org (search pagesthey can be crucial resources test your knowledgepart exercises
668
types and operations
669
introducing python object types this begins our tour of the python language in an informal sensein python we do things with stuff "thingstake the form of operations like addition and concatenationand "stuffrefers to the objects on which we perform those operations in this part of the bookour focus is on that stuffand the things our programs can do with it somewhat more formallyin pythondata takes the form of objects--either built-in objects that python providesor objects we create using python classes or external language tools such as extension libraries although we'll firm up this definition laterobjects are essentially just pieces of memorywith values and sets of associated operations as we'll seeeverything is an object in python script even simple numbers qualifywith values ( )and supported operations (additionsubtractionand so onbecause objects are also the most fundamental notion in python programmingwe'll start this with survey of python' built-in object types later provide second pass that fills in details we'll gloss over in this survey hereour goal is brief tour to introduce the basics the python conceptual hierarchy before we get to the codelet' first establish clear picture of how this fits into the overall python picture from more concrete perspectivepython programs can be decomposed into modulesstatementsexpressionsand objectsas follows programs are composed of modules modules contain statements statements contain expressions expressions create and process objects pardon my formality ' computer scientist
670
this part' begin at the bottom--exploring both built-in objects and the expressions you can code to use them we'll move on to study statements in the next part of the bookthough we will find that they largely exist to manage the objects we'll meet here moreoverby the time we reach classes in the oop part of this bookwe'll discover that they allow us to define new object types of our ownby both using and emulating the object types we will explore here because of all thisbuilt-in objects are mandatory point of embarkation for all python journeys traditional introductions to programming often stress its three pillars of sequence ("do thisthen that")selection ("do this if that is true")and repetition ("do this many times"python has tools in all three categoriesalong with some for definition--of functions and classes these themes may help you organize your thinking early onbut they are bit artificial and simplistic expressions such as comprehensionsfor exampleare both repetition and selectionsome of these terms have other meanings in pythonand many later concepts won' seem to fit this mold at all in pythonthe more strongly unifying principle is objectsand what we can do with them to see whyread on why use built-in typesif you've used lower-level languages such as or ++you know that much of your work centers on implementing objects--also known as data structures--to represent the components in your application' domain you need to lay out memory structuresmanage memory allocationimplement search and access routinesand so on these chores are about as tedious (and error-proneas they soundand they usually distract from your program' real goals in typical python programsmost of this grunt work goes away because python provides powerful object types as an intrinsic part of the languagethere' usually no need to code object implementations before you start solving problems in factunless you have need for special processing that built-in types don' provideyou're almost always better off using built-in object instead of implementing your own here are some reasons whybuilt-in objects make programs easy to write for simple tasksbuilt-in types are often all you need to represent the structure of problem domains because you get powerful tools such as collections (listsand search tables (dictionariesfor freeyou can use them immediately you can get lot of work done with python' builtin object types alone built-in objects are components of extensions for more complex tasksyou may need to provide your own objects using python classes or language inter introducing python object types
671
are often built on top of built-in types such as lists and dictionaries for instancea stack data structure may be implemented as class that manages or customizes built-in list built-in objects are often more efficient than custom data structures python' built-in types employ already optimized data structure algorithms that are implemented in for speed although you can write similar object types on your ownyou'll usually be hard-pressed to get the level of performance built-in object types provide built-in objects are standard part of the language in some wayspython borrows both from languages that rely on built-in tools ( lispand languages that rely on the programmer to provide tool implementations or frameworks of their own ( ++although you can implement unique object types in pythonyou don' need to do so just to get started moreoverbecause python' built-ins are standardthey're always the sameproprietary frameworkson the other handtend to differ from site to site in other wordsnot only do built-in object types make programming easierbut they're also more powerful and efficient than most of what can be created from scratch regardless of whether you implement new object typesbuilt-in objects form the core of every python program python' core data types table - previews python' built-in object types and some of the syntax used to code their literals--that isthe expressions that generate these objects some of these types will probably seem familiar if you've used other languagesfor instancenumbers and strings represent numeric and textual valuesrespectivelyand file objects provide an interface for processing real files stored on your computer to some readersthoughthe object types in table - may be more general and powerful than what you are accustomed to for instanceyou'll find that lists and dictionaries alone are powerful data representation tools that obviate most of the work you do to support collections and searching in lower-level languages in shortlists provide ordered collections of other objectswhile dictionaries store objects by keyboth lists and dictionaries may be nestedcan grow and shrink on demandand may contain objects of any type in this bookthe term literal simply means an expression whose syntax generates an object--sometimes also called constant note that the term "constantdoes not imply objects or variables that can never be changed ( this term is unrelated to ++' const or python' "immutable"-- topic explored in the section "immutabilityon page python' core data types
672
object type example literals/creation numbers + decimal()fraction(strings 'spam'"bob' " ' \ ' 'sp\xc mlists [ [ 'three'] ]list(range( )dictionaries {'food''spam''taste''yum'}dict(hours= tuples ( 'spam' ' ')tuple('spam')namedtuple files open('eggs txt')open( ' :\ham bin''wb'sets set('abc'){' '' '' 'other core types booleanstypesnone program unit types functionsmodulesclasses (part ivpart vpart viimplementation-related types compiled codestack tracebacks (part ivpart viialso shown in table - program units such as functionsmodulesand classes--which we'll meet in later parts of this book--are objects in python toothey are created with statements and expressions such as defclassimportand lambda and may be passed around scripts freelystored within other objectsand so on python also provides set of implementation-related types such as compiled code objectswhich are generally of interest to tool builders more than application developerswe'll explore these in later parts toothough in less depth due to their specialized roles despite its titletable - isn' really completebecause everything we process in python programs is kind of object for instancewhen we perform text pattern matching in pythonwe create pattern objectsand when we perform network scriptingwe use socket objects these other kinds of objects are generally created by importing and using functions in library modules--for examplein the re and socket modules for patterns and sockets--and have behavior all their own we usually call the other object types in table - core data typesthoughbecause they are effectively built into the python language--that isthere is specific expression syntax for generating most of them for instancewhen you run the following code with characters surrounded by quotes'spamyou aretechnically speakingrunning literal expression that generates and returns new string object there is specific python language syntax to make this object similarlyan expression wrapped in square brackets makes listone in curly braces makes dictionaryand so on even thoughas we'll seethere are no type declarations in pythonthe syntax of the expressions you run determines the types of objects you create and use in factobject-generation expressions like those in table - are generally where types originate in the python language introducing python object types
673
you can perform only string operations on string and list operations on list in formal termsthis means that python is dynamically typeda model that keeps track of types for you automatically instead of requiring declaration codebut it is also strongly typeda constraint that means you can perform on an object only operations that are valid for its type we'll study each of the object types in table - in detail in upcoming before digging into the detailsthoughlet' begin by taking quick look at python' core objects in action the rest of this provides preview of the operations we'll explore in more depth in the that follow don' expect to find the full story here--the goal of this is just to whet your appetite and introduce some key ideas stillthe best way to get started is to get startedso let' jump right into some real code numbers if you've done any programming or scripting in the pastsome of the object types in table - will probably seem familiar even if you haven'tnumbers are fairly straightforward python' core objects set includes the usual suspectsintegers that have no fractional partfloating-point numbers that doand more exotic types--complex numbers with imaginary partsdecimals with fixed precisionrationals with numerator and denominatorand full-featured sets built-in numbers are enough to represent most numeric quantities--from your age to your bank balance--but more types are available as third-party add-ons although it offers some fancier optionspython' basic number types arewellbasic numbers in python support the normal mathematical operations for instancethe plus sign (+performs additiona star (*is used for multiplicationand two stars (**are used for exponentiation integer addition floating-point multiplication * to the power again notice the last result herepython ' integer type automatically provides extra precision for large numbers like this when needed (in xa separate long integer type handles numbers too large for the normal integer type in similar waysyou canfor instancecompute to the power , , as an integer in pythonbut you probably shouldn' try to print the result--with more than , digitsyou may be waiting awhilelen(str( * ) how many digits in really big numbernumbers
674
to string of digits with the built-in str functionand then getting the length of the resulting string with len the end result is the number of digits str and len work on many object typesmore on both as we move along on pythons prior to and once you start experimenting with floating-point numbersyou're likely to stumble across something that may look bit odd at first glance print( repras code (pythons and struser-friendly the first result isn' bugit' display issue it turns out that there are two ways to print every object in python--with full precision (as in the first result shown here)and in user-friendly form (as in the secondformallythe first form is known as an object' as-code reprand the second is its user-friendly str in older pythonsthe floating-point repr sometimes displays more precision than you might expect the difference can also matter when we step up to using classes for nowif something looks oddtry showing it with print built-in function call statement better yetupgrade to python and the latest xwhere floating-point numbers display themselves more intelligentlyusually with fewer extraneous digits--since this book is based on pythons and this is the display form 'll be showing throughout this book for floating-point numbers repras code (pythons > and besides expressionsthere are handful of useful numeric modules that ship with python--modules are just packages of additional tools that we import to useimport math math pi math sqrt( the math module contains more advanced numeric tools as functionswhile the ran dom module performs random-number generation and random selections (herefrom python list coded in square brackets--an ordered collection of other objects to be introduced later in this import random random random( random choice([ ] python also includes more exotic numeric objects--such as complexfixed-precisionand rational numbersas well as sets and booleans--and the third-party open source introducing python object types
675
numberswe'll defer discussion of these types until later in this and book so farwe've been using python much like simple calculatorto do better justice to its built-in typeslet' move on to explore strings strings strings are used to record both textual information (your namefor instanceas well as arbitrary collections of bytes (such as an image file' contentsthey are our first example of what in python we call sequence-- positionally ordered collection of other objects sequences maintain left-to-right order among the items they containtheir items are stored and fetched by their relative positions strictly speakingstrings are sequences of one-character stringsothermore general sequence types include lists and tuplescovered later sequence operations as sequencesstrings support operations that assume positional ordering among items for exampleif we have four-character string coded inside quotes (usually of the single variety)we can verify its length with the built-in len function and fetch its components with indexing expressionss 'spamlen( [ 'ss[ 'pmake -character stringand assign it to name length the first item in sindexing by zero-based position the second item from the left in pythonindexes are coded as offsets from the frontand so start from the first item is at index the second is at index and so on notice how we assign the string to variable named here we'll go into detail on how this works later (especially in )but python variables never need to be declared ahead of time variable is created when you assign it valuemay be assigned any type of objectand is replaced with its value when it shows up in an expression it must also have been previously assigned by the time you use its value for the purposes of this it' enough to know that we need to assign an object to variable in order to save it for later use in pythonwe can also index backwardfrom the end--positive indexes count from the leftand negative indexes count back from the rights[- 'ms[- 'athe last item from the end in the second-to-last item from the end strings
676
operations are equivalent (though the first is easier to code and less easy to get wrong) [- 'ms[len( )- 'mthe last item in negative indexingthe hard way notice that we can use an arbitrary expression in the square bracketsnot just hardcoded number literal--anywhere that python expects valuewe can use literala variableor any expression we wish python' syntax is completely general this way in addition to simple positional indexingsequences also support more general form of indexing known as slicingwhich is way to extract an entire section (slicein single step for examples 'spams[ : 'paa -character string slice of from offsets through (not probably the easiest way to think of slices is that they are way to extract an entire column from string in single step their general formx[ : ]means "give me everything in from offset up to but not including offset the result is returned in new object the second of the preceding operationsfor instancegives us all the characters in string from offsets through (that is through as new string the effect is to slice or "parse outthe two characters in the middle in slicethe left bound defaults to zeroand the right bound defaults to the length of the sequence being sliced this leads to some common usage variationss[ :'pams 'spams[ : 'spas[: 'spas[:- 'spas[:'spameverything past the first ( :len( ) itself hasn' changed everything but the last same as [ : everything but the last againbut simpler ( :- all of as top-level copy ( :len( )note in the second-to-last command how negative offsets can be used to give bounds for slicestooand how the last operation effectively copies the entire string as you'll learn laterthere is no reason to copy stringbut this form can be useful for sequences like lists finallyas sequencesstrings also support concatenation with the plus sign (joining two strings into new stringand repetition (making new string by repeating another) 'spam introducing python object types
677
concatenation 'spamxyzs is unchanged 'spams repetition 'spamspamspamspamspamspamspamspamnotice that the plus sign (+means different things for different objectsaddition for numbersand concatenation for strings this is general property of python that we'll call polymorphism later in the book--in sumthe meaning of an operation depends on the objects being operated on as you'll see when we study dynamic typingthis polymorphism property accounts for much of the conciseness and flexibility of python code because types aren' constraineda python-coded operation can normally work on many different types of objects automaticallyas long as they support compatible interface (like the operation herethis turns out to be huge idea in pythonyou'll learn more about it later on our tour immutability also notice in the prior examples that we were not changing the original string with any of the operations we ran on it every string operation is defined to produce new string as its resultbecause strings are immutable in python--they cannot be changed in place after they are created in other wordsyou can never overwrite the values of immutable objects for exampleyou can' change string by assigning to one of its positionsbut you can always build new one and assign it to the same name because python cleans up old objects as you go (as you'll see later)this isn' as inefficient as it may sounds 'spams[ 'zimmutable objects cannot be changed error text omitted typeerror'strobject does not support item assignment 'zs[ : 'zpambut we can run expressions to make new objects every object in python is classified as either immutable (unchangeableor not in terms of the core typesnumbersstringsand tuples are immutablelistsdictionariesand sets are not--they can be changed in place freelyas can most new objects you'll code with classes this distinction turns out to be crucial in python workin ways that we can' yet fully explore among other thingsimmutability can be used to guarantee that an object remains constant throughout your programmutable objectsvalues can be changed at any time and place (and whether you expect it or notstrings
678
list of individual characters and join it back together with nothing betweenor use the newer bytearray type available in pythons and laters 'shrubberyl list(sl [' '' '' '' '' '' '' '' '' ' [ ' 'join( 'scrubberyexpand to listchange it in place join with empty delimiter bytes/list hybrid (ahead'bneeded in xnot [iord(cworks here too bytearray( 'spam' extend( 'eggs' bytearray( 'spameggs' decode('spameggstranslate to normal string the bytearray supports in-place changes for textbut only for text whose characters are all at most -bits wide ( asciiall other strings are still immutable--bytear ray is distinct hybrid of immutable bytes strings (whose bsyntax is required in and optional in xand mutable lists (coded and displayed in [])and we have to learn more about both these and unicode text to fully grasp this code type-specific methods every string operation we've studied so far is really sequence operation--that isthese operations will work on other sequences in python as wellincluding lists and tuples in addition to generic sequence operationsthoughstrings also have operations all their ownavailable as methods--functions that are attached to and act upon specific objectwhich are triggered with call expression for examplethe string find method is the basic substring search operation (it returns the offset of the passed-in substringor - if it is not present)and the string replace method performs global searches and replacementsboth act on the subject that they are attached to and called froms 'spams find('pa' 'spams replace('pa''xyz''sxyzms 'spamfind the offset of substring in replace occurrences of string in with another againdespite the names of these string methodswe are not changing the original strings herebut creating new strings as the results--because strings are immutablethis is the only way this can work string methods are the first line of text-processing introducing python object types
679
simple form of parsing)perform case conversionstest the content of the string (digitslettersand so on)and strip whitespace characters off the ends of the stringline 'aaa,bbb,ccccc,ddline split(','['aaa''bbb''ccccc''dd' 'spams upper('spams isalpha(true split on delimiter into list of substrings upperand lowercase conversions content testsisalphaisdigitetc line 'aaa,bbb,ccccc,dd\nline rstrip(remove whitespace characters on the right side 'aaa,bbb,ccccc,ddline rstrip(split(','combine two operations ['aaa''bbb''ccccc''dd'notice the last command here--it strips before it splits because python runs from left to rightmaking temporary result along the way strings also support an advanced substitution operation known as formattingavailable as both an expression (the originaland string method call (new as of and )the second of these allows you to omit relative argument value numbers as of and '%seggsand % ('spam''spam!''spameggsand spam!formatting expression (all'{ }eggsand { }format('spam''spam!''spameggsand spam!formatting method ( + +'{}eggsand {}format('spam''spam!''spameggsand spam!numbers optional ( + +formatting is rich with featureswhich we'll postpone discussing until later in this bookand which tend to matter most when you must generate numeric reports'{: }format( ' , ' %+ ( - ' - separatorsdecimal digits digitspaddingsigns one note herealthough sequence operations are genericmethods are not--although some types share some method namesstring method operations generally work only on stringsand nothing else as rule of thumbpython' toolset is layeredgeneric operations that span multiple types show up as built-in functions or expressions ( len( ) [ ])but type-specific operations are method calls ( astring upper()finding the tools you need among all these categories will become more natural as you use python morebut the next section gives few tips you can use right now strings
680
the methods introduced in the prior section are representativebut smallsample of what is available for string objects in generalthis book is not exhaustive in its look at object methods for more detailsyou can always call the built-in dir function this function lists variables assigned in the caller' scope when called with no argumentmore usefullyit returns list of all the attributes available for any object passed to it because methods are function attributesthey will show up in this list assuming is still the stringhere are its attributes on python (python varies slightly)dir( ['__add__''__class__''__contains__''__delattr__''__dir__''__doc__''__eq__''__format__''__ge__''__getattribute__''__getitem__''__getnewargs__''__gt__''__hash__''__init__''__iter__''__le__''__len__''__lt__''__mod__''__mul__''__ne__''__new__''__reduce__''__reduce_ex__''__repr__''__rmod__''__rmul__''__setattr__''__sizeof__''__str__''__subclasshook__''capitalize''casefold''center''count''encode''endswith''expandtabs''find''format''format_map''index''isalnum''isalpha''isdecimal''isdigit''isidentifier''islower''isnumeric''isprintable''isspace''istitle''isupper''join''ljust''lower''lstrip''maketrans''partition''replace''rfind''rindex''rjust''rpartition''rsplit''rstrip''split''splitlines''startswith''strip''swapcase''title''translate''upper''zfill'you probably won' care about the names with double underscores in this list until later in the bookwhen we study operator overloading in classes--they represent the implementation of the string object and are available to support customization the __add__ method of stringsfor exampleis what really performs concatenationpython maps the first of the following to the second internallythough you shouldn' usually use the second form yourself (it' less intuitiveand might even run slower) 'ni!'spamni! __add__('ni!''spamni!in generalleading and trailing double underscores is the naming pattern python uses for implementation details the names without the underscores in this list are the callable methods on string objects the dir function simply gives the methodsnames to ask what they doyou can pass them to the help functionhelp( replacehelp on built-in function replacereplaces replace(oldnew[count]-str return copy of with all occurrences of substring old replaced by new if the optional argument count is givenonly the first count occurrences are replaced introducing python object types
681
as pydoc-- tool for extracting documentation from objects later in the bookyou'll see that pydoc can also render its reports in html format for display on web browser you can also ask for help on an entire string ( help( ))but you may get more or less help than you want to see--information about every string method in older pythonsand probably no help at all in newer versions because strings are treated specially it' generally better to ask about specific method both dir and help also accept as arguments either real object (like our string )or the name of data type (like strlistand dictthe latter form returns the same list for dir but shows full type details for helpand allows you to ask about specific method via type name ( help on str replacefor more detailsyou can also consult python' standard library reference manual or commercially published reference booksbut dir and help are the first level of documentation in python other ways to code strings so farwe've looked at the string object' sequence operations and type-specific methods python also provides variety of ways for us to code stringswhich we'll explore in greater depth later for instancespecial characters can be represented as backslash escape sequenceswhich python displays in \xnn hexadecimal escape notationunless they represent printable characterss ' \nb\tclen( \ is end-of-line\ is tab each stands for just one character ord('\ ' \ is byte with the binary value in ascii ' \ \ clen( ' \ \ \ binary zero bytedoes not terminate string non-printables are displayed as \xnn hex escapes python allows strings to be enclosed in single or double quote characters--they mean the same thing but allow the other type of quote to be embedded with an escape (most programmers prefer single quotesit also allows multiline string literals enclosed in triple quotes (single or double)--when this form is usedall the lines are concatenated togetherand end-of-line characters are added where line breaks appear this is minor syntactic conveniencebut it' useful for embedding things like multiline htmlxmlor json code in python scriptand stubbing out lines of code temporarily--just add three quotes above and belowmsg ""aaaaaaaaaaaaa strings
682
cccccccccccccc ""msg '\naaaaaaaaaaaaa\nbbb\'\'\'bbbbbbbbbb""bbbbbbb\'bbbb\ncccccccccccccc\npython also supports raw string literal that turns off the backslash escape mechanism such literals start with the letter and are useful for strings like directory paths on windows ( ' :\text\new'unicode strings python' strings also come with full unicode support required for processing text in internationalized character sets characters in the japanese and russian alphabetsfor exampleare outside the ascii set such non-ascii text can show up in web pagesemailsguisjsonxmlor elsewhere when it doeshandling it well requires unicode support python has such support built inbut the form of its unicode support varies per python lineand is one of their most prominent differences in python xthe normal str string handles unicode text (including asciiwhich is just simple kind of unicode) distinct bytes string type represents raw byte values (including media and encoded text)and unicode literals are supported in and later for compatibility (they are treated the same as normal str strings)'sp\xc 'spamb' \ cb' \ cu'sp\ 'spam xnormal str strings are unicode text bytes strings are byte-based data the unicode literal works in +just str in python xthe normal str string handles both -bit character strings (including ascii textand raw byte valuesa distinct unicode string type represents unicode textand bytes literals are supported in and later for compatibility (they are treated the same as normal str strings)print 'sp\xc mspam ' \ ' \ cb' \ ' \ xunicode strings are distinct type normal str strings contain byte-based text/data the bytes literal works in +just str formallyin both and xnon-unicode strings are sequences of -bit bytes that print with ascii characters when possibleand unicode strings are sequences of unicode code points--identifying numbers for characterswhich do not necessarily map to single bytes when encoded to files or stored in memory in factthe notion of bytes doesn' apply to unicodesome encodings include character code points too large for byteand even simple -bit ascii text is not stored one byte per character under some encodings and memory storage schemes introducing python object types
683
'spam'spamencode('utf ' 'spam'spamencode('utf ' '\xff\xfes\ \ \ \ characters may be or bytes in memory encoded to bytes in utf- in files but encoded to bytes in utf- both and also support the bytearray string type we met earlierwhich is essentially bytes string ( str in xthat supports most of the list object' in-place mutable change operations both and also support coding non-ascii characters with \ hexadecimal and short \ and long \ unicode escapesas well as file-wide encodings declared in program source files here' our non-ascii character coded three ways in (add leading "uand say "printto see the same in )'sp\xc \ \ 'spaaamwhat these values mean and how they are used differs between text stringswhich are the normal string in and unicode in xand byte stringswhich are bytes in and the normal string in all these escapes can be used to embed actual unicode code-point ordinal-value integers in text strings by contrastbyte strings use only \ hexadecimal escapes to embed the encoded form of textnot its decoded code point values--encoded bytes are the same as code pointsonly for some encodings and characters'\ ''\ encode('latin ') '\xa decode('latin '('ps' '\xa ''ps'as notable differencepython allows its normal and unicode strings to be mixed in expressions as long as the normal string is all asciiin contrastpython has tighter model that never allows its normal and byte strings to mix without explicit conversionu'xb'yu' 'yworks in (where is optional and ignoredworks in xu'xyu'xb'yu' 'yfails in (where is optional and ignoredworks in 'xy'xb'ydecode('xencode( 'yworks in if decode bytes to str'xyworks in if encode str to bytesb'xyapart from these string typesunicode processing mostly reduces to transferring text data to and from files--text is encoded to bytes when stored in fileand decoded into characters ( code pointswhen read back into memory once it is loadedwe usually process text as strings in decoded form only because of this modelthoughfiles are also content-specific in xtext files implement named encodings and accept and return str stringsbut binary files instead deal in strings
684
special codecs module handles unicode and represents content with the unicode type we'll meet unicode again in the files coverage later in this but save the rest of the unicode story for later in this book it crops up briefly in example in conjunction with currency symbolsbut for the most part is postponed until this book' advanced topics part unicode is crucial in some domainsbut many programmers can get by with just passing acquaintance if your data is all ascii textthe string and file stories are largely the same in and and if you're new to programmingyou can safely defer most unicode details until you've mastered string basics pattern matching one point worth noting before we move on is that none of the string object' own methods support pattern-based text processing text pattern matching is an advanced tool outside this book' scopebut readers with backgrounds in other scripting languages may be interested to know that to do pattern matching in pythonwe import module called re this module has analogous calls for searchingsplittingand replacementbut because we can use patterns to specify substringswe can be much more generalimport re match re match('hello\ ]**)world''hello match group( 'python python world'this example searches for substring that begins with the word "hello,followed by zero or more tabs or spacesfollowed by arbitrary characters to be saved as matched groupterminated by the word "world if such substring is foundportions of the substring matched by parts of the pattern enclosed in parentheses are available as groups the following patternfor examplepicks out three groups separated by slashesand is similar to splitting by an alternatives patternmatch re match('[/:]*)[/:]*)[/:]*)''/usr/home:lumberjack'match groups(('usr''home''lumberjack're split('[/:]''/usr/home/lumberjack'['''usr''home''lumberjack'pattern matching is an advanced text-processing tool by itselfbut there is also support in python for even more advanced text and language processingincluding xml and html parsing and natural language analysis we'll see additional brief examples of patterns and xml parsing at the end of but 've already said enough about strings for this tutorialso let' move on to the next type introducing python object types
685
the python list object is the most general sequence provided by the language lists are positionally ordered collections of arbitrarily typed objectsand they have no fixed size they are also mutable--unlike stringslists can be modified in place by assignment to offsets as well as variety of list method calls accordinglythey provide very flexible tool for representing arbitrary collections--lists of files in folderemployees in companyemails in your inboxand so on sequence operations because they are sequenceslists support all the sequence operations we discussed for stringsthe only difference is that the results are usually lists instead of strings for instancegiven three-item listl [ 'spam' len( list of three different-type objects number of items in the list we can indexsliceand so onjust as for stringsl[ [:- [ 'spam'indexing by position slicing list returns new list [ concat/repeat make new lists too [ 'spam' [ 'spam' 'spam' [ 'spam' we're not changing the original list type-specific operations python' lists may be reminiscent of arrays in other languagesbut they tend to be more powerful for one thingthey have no fixed type constraint--the list we just looked atfor examplecontains three objects of completely different types (an integera stringand floating-point numberfurtherlists have no fixed size that isthey can grow and shrink on demandin response to list-specific operationsl append('ni' [ 'spam' 'ni'growingadd object at end of list pop( [ 'spam''ni'shrinkingdelete an item in the middle "del [ ]deletes from list too lists
686
pop method (or an equivalent del statementthen removes an item at given offsetcausing the list to shrink other list methods insert an item at an arbitrary position (insert)remove given item by value (remove)add multiple items at the end (extend)and so on because lists are mutablemost list methods also change the list object in placeinstead of creating new onem ['bb''aa''cc' sort( ['aa''bb''cc' reverse( ['cc''bb''aa'the list sort method herefor exampleorders the list in ascending fashion by defaultand reverse reverses it--in both casesthe methods modify the list directly bounds checking although lists have no fixed sizepython still doesn' allow us to reference items that are not present indexing off the end of list is always mistakebut so is assigning off the endl [ 'spam''ni' [ error text omitted indexerrorlist index out of range [ error text omitted indexerrorlist assignment index out of range this is intentionalas it' usually an error to try to assign off the end of list (and particularly nasty one in the languagewhich doesn' do as much error checking as pythonrather than silently growing the list in responsepython reports an error to grow listwe call list methods such as append instead nesting one nice feature of python' core data types is that they support arbitrary nesting--we can nest them in any combinationand as deeply as we like for examplewe can have list that contains dictionarywhich contains another listand so on one immediate application of this feature is to represent matrixesor "multidimensional arraysin python list with nested lists will do the job for basic applications (you'll get continuation-line prompts on lines and of the following in some interfacesbut not in idle) introducing python object types
687
matrixas nested lists [ ]code can span lines if bracketed [ ] [[ ][ ][ ]herewe've coded list that contains three other lists the effect is to represent matrix of numbers such structure can be accessed in variety of waysm[ [ get row [ ][ get row then get item within the row the first operation here fetches the entire second rowand the second grabs the third item within that row (it runs left to rightlike the earlier string strip and splitstringing together index operations takes us deeper and deeper into our nested-object structure comprehensions in addition to sequence operations and list methodspython includes more advanced operation known as list comprehension expressionwhich turns out to be powerful way to process structures like our matrix supposefor instancethat we need to extract the second column of our sample matrix it' easy to grab rows by simple indexing because the matrix is stored by rowsbut it' almost as easy to get column with list comprehensioncol [row[ for row in mcol [ collect the items in column [[ ][ ][ ]the matrix is unchanged list comprehensions derive from set notationthey are way to build new list by running an expression on each item in sequenceone at timefrom left to right list comprehensions are coded in square brackets (to tip you off to the fact that they make listand are composed of an expression and looping construct that share variable name (rowherethe preceding list comprehension means basically what it says"give me row[ for each row in matrix min new list the result is new list containing column of the matrix list comprehensions can be more complex in practice this matrix structure works for small-scale tasksbut for more serious number crunching you will probably want to use one of the numeric extensions to pythonsuch as the open source numpy and scipy systems such tools can store and process large matrixes much more efficiently than our nested list structure numpy has been said to turn python into the equivalent of free and more powerful version of the matlab systemand organizations such as nasalos alamosjpland many others use this tool for scientific and financial tasks search the web for more details lists
688
[ add to each item in column [row[ for row in if row[ = filter out odd items [ the first operation herefor instanceadds to each item as it is collectedand the second uses an if clause to filter odd numbers out of the result using the modulus expression (remainder of divisionlist comprehensions make new lists of resultsbut they can be used to iterate over any iterable object-- term we'll flesh out later in this preview herefor instancewe use list comprehensions to step over hardcoded list of coordinates and stringdiag [ [ ][ifor in [ ]diag [ collect diagonal from matrix doubles [ for in 'spam'doubles ['ss''pp''aa''mm'repeat characters in string these expressions can also be used to collect multiple valuesas long as we wrap those values in nested collection the following illustrates using range-- built-in that generates successive integersand requires surrounding list to display all its values in only ( makes physical list all at once)list(range( )[ list(range(- )[- - - (list(required in - to + by (need list(in [[ * * for in range( )multiple values"iffilters [[ ][ ][ ][ ][[xx for in range(- if [[ ][ ][ ]as you can probably telllist comprehensionsand relatives like the map and filter built-in functionsare too involved to cover more formally in this preview the main point of this brief introduction is to illustrate that python includes both simple and advanced tools in its arsenal list comprehensions are an optional featurebut they tend to be very useful in practice and often provide substantial processing speed advantage they also work on any type that is sequence in pythonas well as some types that are not you'll hear much more about them later in this book as previewthoughyou'll find that in recent pythonscomprehension syntax has been generalized for other rolesit' not just for making lists today for exampleenclosing comprehension in parentheses can also be used to create generators that produce results on demand to illustratethe sum built-in sums items in sequence--in this examplesumming all items in our matrix' rows on requestg (sum(rowfor row in mnext( introducing python object types create generator of row sums iter(gnot required here
689
next( next( run the iteration protocol next(the map built-in can do similar workby generating the results of running items through functionone at time and on request like rangewrapping it in list forces it to return all its values in python xthis isn' needed in where map makes list of results all at once insteadand is not needed in other contexts that iterate automaticallyunless multiple scans or list-like behavior is also requiredlist(map(summ)[ map sum over items in in python and xcomprehension syntax can also be used to create sets and dictionaries{sum(rowfor row in { create set of row sums { sum( [ ]for in range( ){ creates key/value table of row sums in factlistssetsdictionariesand generators can all be built with comprehensions in and [ord(xfor in 'spaam'list of character ordinals [ {ord(xfor in 'spaam'sets remove duplicates { {xord(xfor in 'spaam'dictionary keys are unique {' ' ' ' ' ' ' ' (ord(xfor in 'spaam'generator of values at dab to understand objects like generatorssetsand dictionariesthoughwe must move ahead dictionaries python dictionaries are something completely different (monty python reference intended)--they are not sequences at allbut are instead known as mappings mappings are also collections of other objectsbut they store objects by key instead of by relative position in factmappings don' maintain any reliable left-to-right orderthey simply map keys to associated values dictionariesthe only mapping type in python' core objects setare also mutablelike liststhey may be changed in place and can grow and shrink on demand also like liststhey are flexible tool for representing collectionsbut their more mnemonic keys are better suited when collection' items are named or labeled--fields of database recordfor example dictionaries
690
when written as literalsdictionaries are coded in curly braces and consist of series of "keyvaluepairs dictionaries are useful anytime we need to associate set of values with keys--to describe the properties of somethingfor instance as an exampleconsider the following three-item dictionary (with keys "food,"quantity,and "color,perhaps the details of hypothetical menu item?) {'food''spam''quantity' 'color''pink'we can index this dictionary by key to fetch and change the keysassociated values the dictionary index operation uses the same syntax as that used for sequencesbut the item in the square brackets is keynot relative positiond['food''spamfetch value of key 'foodd['quantity'+ add to 'quantityvalue {'color''pink''food''spam''quantity' although the curly-braces literal form does see useit is perhaps more common to see dictionaries built up in different ways (it' rare to know all your program' data before your program runsthe following codefor examplestarts with an empty dictionary and fills it out one key at time unlike out-of-bounds assignments in listswhich are forbiddenassignments to new dictionary keys create those keysd { ['name''bobd['job''devd['age' create keys by assignment {'age' 'job''dev''name''bob'print( ['name']bob herewe're effectively using dictionary keys as field names in record that describes someone in other applicationsdictionaries can also be used to replace searching operations--indexing dictionary by key is often the fastest way to code search in python as we'll learn laterwe can also make dictionaries by passing to the dict type name either keyword arguments ( special name=value syntax in function calls)or the result of zipping together sequences of keys and values obtained at runtime ( from filesboth the following make the same dictionary as the prior example and its equivalent {literal formthough the first tends to make for less typingbob dict(name='bob'job='dev'age= bob {'age' 'name''bob''job''dev' introducing python object types keywords
691
bob {'job''dev''name''bob''age' zipping notice how the left-to-right order of dictionary keys is scrambled mappings are not positionally orderedso unless you're luckythey'll come back in different order than you typed them the exact order may vary per pythonbut you shouldn' depend on itand shouldn' expect yours to match that in this book nesting revisited in the prior examplewe used dictionary to describe hypothetical personwith three keys supposethoughthat the information is more complex perhaps we need to record first name and last namealong with multiple job titles this leads to another application of python' object nesting in action the following dictionarycoded all at once as literalcaptures more structured informationrec {'name'{'first''bob''last''smith'}'jobs'['dev''mgr']'age' herewe again have three-key dictionary at the top (keys "name,"jobs,and "age")but the values have become more complexa nested dictionary for the name to support multiple partsand nested list for the jobs to support multiple roles and future expansion we can access the components of this structure much as we did for our listbased matrix earlierbut this time most indexes are dictionary keysnot list offsetsrec['name'{'last''smith''first''bob''nameis nested dictionary rec['name']['last''smithindex the nested dictionary rec['jobs'['dev''mgr'rec['jobs'][- 'mgr'jobsis nested list index the nested list rec['jobs'append('janitor'expand bob' job description in place rec {'age' 'jobs'['dev''mgr''janitor']'name'{'last''smith''first''bob'}notice how the last operation here expands the nested jobs list--because the jobs list is separate piece of memory from the dictionary that contains itit can grow and shrink freely (object memory layout will be discussed further later in this bookthe real reason for showing you this example is to demonstrate the flexibility of python' core data types as you can seenesting allows us to build up complex information structures directly and easily building similar structure in low-level language like would be tedious and require much more codewe would have to lay out and dictionaries
692
pythonthis is all automatic--running the expression creates the entire nested object structure for us in factthis is one of the main benefits of scripting languages like python just as importantlyin lower-level language we would have to be careful to clean up all of the object' space when we no longer need it in pythonwhen we lose the last reference to the object--by assigning its variable to something elsefor example--all of the memory space occupied by that object' structure is automatically cleaned up for usrec now the object' space is reclaimed technically speakingpython has feature known as garbage collection that cleans up unused memory as your program runs and frees you from having to manage such details in your code in standard python ( cpython)the space is reclaimed immediatelyas soon as the last reference to an object is removed we'll study how this works later in for nowit' enough to know that you can use objects freelywithout worrying about creating their space or cleaning up as you go also watch for record structure similar to the one we just coded in and where we'll use it to compare and contrast listsdictionariestuplesnamed tuplesand classes--an array of data structure options with tradeoffs we'll cover in full later missing keysif tests as mappingsdictionaries support accessing items by key onlywith the sorts of operations we've just seen in additionthoughthey also support type-specific operations with method calls that are useful in variety of common use cases for examplealthough we can assign to new key to expand dictionaryfetching nonexistent key is still mistaked {' ' ' ' ' ' two application notes here firstas previewthe rec record we just created really could be an actual database recordwhen we employ python' object persistence system--an easy way to store native python objects in simple files or access-by-key databaseswhich translates objects to and from serial byte streams automatically we won' go into details herebut watch for coverage of python' pickle and shelve persistence modules in and where we'll explore them in the context of filesan oop use caseclassesand changesrespectively secondif you are familiar with json (javascript object notation)--an emerging data-interchange format used for databases and network transfers--this example may also look curiously similarthough python' support for variablesarbitrary expressionsand changes can make its data structures more general python' json library module supports creating and parsing json textbut the translation to python objects is often trivial watch for json example that uses this record in when we study files for larger use casesee mongodbwhich stores data using language-neutral binary-encoded serialization of json-like documentsand its pymongo interface introducing python object types
693
[' ' {' ' ' ' ' ' ' ' assigning new keys grows dictionaries [' 'error text omitted keyerror'freferencing nonexistent key is an error this is what we want--it' usually programming error to fetch something that isn' really there but in some generic programswe can' always know what keys will be present when we write our code how do we handle such cases and avoid errorsone solution is to test ahead of time the dictionary in membership expression allows us to query the existence of key and branch on the result with python if statement in the followingbe sure to press enter twice to run the if interactively after typing its code (as explained in an empty line means "goat the interactive prompt)and just as for the earlier multiline dictionaries and liststhe prompt changes to on some interfaces for lines two and beyond'fin false if not 'fin dprint('missing'python' sole selection statement missing this book has more to say about the if statement in later but the form we're using here is straightforwardit consists of the word iffollowed by an expression that is interpreted as true or false resultfollowed by block of code to run if the test is true in its full formthe if statement can also have an else clause for default caseand one or more elif ("else if"clauses for other tests it' the main selection statement tool in pythonalong with both its ternary if/else expression cousin (which we'll meet in momentand the if comprehension filter lookalike we saw earlierit' the way we code the logic of choices and decisions in our scripts if you've used some other programming languages in the pastyou might be wondering how python knows when the if statement ends 'll explain python' syntax rules in depth in later but in shortif you have more than one action to run in statement blockyou simply indent all their statements the same way--this both promotes readable code and reduces the number of characters you have to typeif not 'fin dprint('missing'print('noreally 'statement blocks are indented missing noreally dictionaries
694
the dictionaries we createthe get methoda conditional index with defaultthe python has_key methodan in work-alike that is no longer available in xthe try statementa tool we'll first meet in that catches and recovers from exceptions altogetherand the if/else ternary (three-partexpressionwhich is essentially an if statement squeezed onto single line here are few examplesvalue get(' ' value value [' 'if 'xin else value index but with default if/else expression form we'll save the details on such alternatives until later for nowlet' turn to another dictionary method' role in common use case sorting keysfor loops as mentioned earlierbecause dictionaries are not sequencesthey don' maintain any dependable left-to-right order if we make dictionary and print it backits keys may come back in different order than that in which we typed themand may vary per python version and other variablesd {' ' ' ' ' ' {' ' ' ' ' ' what do we dothoughif we do need to impose an ordering on dictionary' itemsone common solution is to grab list of keys with the dictionary keys methodsort that with the list sort methodand then step through the result with python for loop (as for ifbe sure to press the enter key twice after coding the following for loopand omit the outer parenthesis in the print in python )ks list( keys()ks [' '' '' 'unordered keys list list in "viewin xuse list(ks sort(ks [' '' '' 'sorted keys list for key in ksprint(key'=>' [key]iterate though sorted keys <=press enter twice here ( printa = = = this is three-step processalthoughas we'll see in later in recent versions of python it can be done in one step with the newer sorted built-in function the introducing python object types
695
dictionary keys automaticallyd {' ' ' ' ' ' for key in sorted( )print(key'=>' [key] = = = besides showcasing dictionariesthis use case serves to introduce the python for loop the for loop is simple and efficient way to step through all the items in sequence and run block of code for each item in turn user-defined loop variable (keyhereis used to reference the current item each time through the net effect in our example is to print the unordered dictionary' keys and valuesin sorted-key order the for loopand its more general colleague the while loopare the main ways we code repetitive tasks as statements in our scripts reallythoughthe for looplike its relative the list comprehension introduced earlieris sequence operation it works on any object that is sequence andlike the list comprehensioneven on some things that are not herefor exampleit is stepping across the characters in stringprinting the uppercase version of each as it goesfor in 'spam'print( upper() python' while loop is more general sort of looping toolit' not limited to stepping across sequencesbut generally requires more code to do sox while print('spam!xx - spam!spam!spam!spamspam!spam!spamspam!spamspamwe'll discuss looping statementssyntaxand tools in depth later in the book firstthoughi need to confess that this section has not been as forthcoming as it might have been reallythe for loopand all its cohorts that step through objects from left to rightare not just sequence operationsthey are iterable operations--as the next section describes dictionaries
696
if the last section' for loop looks like the list comprehension expression introduced earlierit shouldboth are really general iteration tools in factboth will work on any iterable object that follows the iteration protocol--pervasive ideas in python that underlie all its iteration tools in nutshellan object is iterable if it is either physically stored sequence in memoryor an object that generates one item at time in the context of an iteration operation -- sort of "virtualsequence more formallyboth types of objects are considered iterable because they support the iteration protocol--they respond to the iter call with an object that advances in response to next calls and raises an exception when finished producing values the generator comprehension expression we saw earlier is such an objectits values aren' stored in memory all at oncebut are produced as requestedusually by iteration tools python file objects similarly iterate line by line when used by an iteration toolfile content isn' in listit' fetched on demand both are iterable objects in python- category that expands in to include core tools like range and map 'll have more to say about the iteration protocol later in this book for nowkeep in mind that every python tool that scans an object from left to right uses the iteration protocol this is why the sorted call used in the prior section works on the dictionary directly--we don' have to call the keys method to get sequence because dictionaries are iterable objectswith next that returns successive keys it may also help you to see that any list comprehension expressionsuch as this onewhich computes the squares of list of numberssquares [ * for in [ ]squares [ can always be coded as an equivalent for loop that builds the result list manually by appending as it goessquares [for in [ ]squares append( * this is what list comprehension does both run the iteration protocol internally squares [ both tools leverage the iteration protocol internally and produce the same result the list comprehensionthoughand related functional programming tools like map and filterwill often run faster than for loop today on some types of code (perhaps even twice as fast)-- property that could matter in your programs for large data sets having said thatthoughi should point out that performance measures are tricky business in python because it optimizes so muchand they may vary from release to release introducing python object types
697
about performance laterafter your program is workingand after you've proved that there is genuine performance concern more often than notyour code will be quick enough as it is if you do need to tweak code for performancethoughpython includes tools to help you outincluding the time and timeit modules for timing the speed of alternativesand the profile module for isolating bottlenecks you'll find more on these later in this book (see especially ' benchmarking case studyand in the python manuals for the sake of this previewlet' move ahead to the next core data type tuples the tuple object (pronounced "toopleor "tuhple,depending on whom you askis roughly like list that cannot be changed--tuples are sequenceslike listsbut they are immutablelike strings functionallythey're used to represent fixed collections of itemsthe components of specific calendar datefor instance syntacticallythey are normally coded in parentheses instead of square bracketsand they support arbitrary typesarbitrary nestingand the usual sequence operationst ( len( -item tuple length > ( ( concatenation [ indexingslicingand more tuples also have type-specific callable methods as of python and but not nearly as many as listst index( count( tuple methods appears at offset appears once the primary distinction for tuples is that they cannot be changed once created that isthey are immutable sequences (one-item tuples like the one here require trailing comma) [ tuples are immutable error text omitted typeerror'tupleobject does not support item assignment ( , [ : ( make new tuple for new value tuples
698
and shrink because they are immutable (the parentheses enclosing tuple' items can usually be omittedas done here) 'spam' [ [ [ ][ append( attributeerror'tupleobject has no attribute 'appendwhy tuplessowhy have type that is like listbut supports fewer operationsfranklytuples are not generally used as often as lists in practicebut their immutability is the whole point if you pass collection of objects around your program as listit can be changed anywhereif you use tupleit cannot that istuples provide sort of integrity constraint that is convenient in programs larger than those we'll write here we'll talk more about tuples later in the bookincluding an extension that builds upon them called named tuples for nowthoughlet' jump ahead to our last major core typethe file files file objects are python code' main interface to external files on your computer they can be used to read and write text memosaudio clipsexcel documentssaved email messagesand whatever else you happen to have stored on your machine files are core typebut they're something of an oddball--there is no specific literal syntax for creating them ratherto create file objectyou call the built-in open functionpassing in an external filename and an optional processing mode as strings for exampleto create text output fileyou would pass in its name and the 'wprocessing mode string to write dataf open('data txt'' ' write('hello\ ' write('world\ ' close(make new file in output mode ('wis writewrite strings of characters to it return number of items written in python close to flush output buffers to disk this creates file in the current directory and writes text to it (the filename can be full directory path if you need to access file elsewhere on your computerto read back what you just wrotereopen the file in 'rprocessing modefor reading text input --this is the default if you omit the mode in the call then read the file' content into stringand display it file' contents are always string in your scriptregardless of the type of data the file contains introducing python object types
699
text read(text 'hello\nworld\ ' (readis the default processing mode read entire file into string print(texthello world print interprets control characters text split(['hello''world'file content is always string other file object methods support additional features we don' have time to cover here for instancefile objects provide more ways of reading and writing (read accepts an optional maximum byte/character sizereadline reads one line at timeand so on)as well as other tools (seek moves to new file positionas we'll see laterthoughthe best way to read file today is to not read it at all--files provide an iterator that automatically reads line by line in for loops and other contextsfor line in open('data txt')print(linewe'll meet the full set of file methods later in this bookbut if you want quick preview nowrun dir call on any open file and help on any of the method names that come backdir(fmany names omitted 'buffer''close''closed''detach''encoding''errors''fileno''flush''isatty''line_buffering''mode''name''newlines''read''readable''readline''readlines''seek''seekable''tell''truncate''writable''write''writelines'help( seektry it and see binary bytes files the prior section' examples illustrate file basics that suffice for many roles technicallythoughthey rely on either the platform' unicode encoding default in python xor the -bit byte nature of files in python text files always encode strings in xand blindly write string content in this is irrelevant for the simple ascii data used previouslywhich maps to and from file bytes unchanged but for richer types of datafile interfaces can vary depending on both content and the python line you use as hinted when we met strings earlierpython draws sharp distinction between text and binary data in filestext files represent content as normal str strings and perform unicode encoding and decoding automatically when writing and reading datawhile binary files represent content as special bytes string and allow you to access file content unaltered python supports the same dichotomybut doesn' impose it as rigidlyand its tools differ files