id
int64
0
25.6k
text
stringlengths
0
4.59k
500
probably get an error messagebut it' worth checking to see if the version you want is already installed using homebrew to install python if you only have python installedor if you have an older version of python you can install the latest version of python using package called homebrew installing homebrew homebrew depends on apple' xcode packageso open terminal and run this commandxcode-select --install click through the confirmation dialogs that pop up (this may take whiledepending on the speed of your connectionnextinstall homebrewruby - "$(curl -fssl master/install)you can find this command on the front page of the homebrew site at the url note the - in this command tells ruby (the programming language homebrew is written into execute the code that' downloaded here you should only run commands like this from sources you trust to confirm that homebrew installed correctlyrun this commandbrew doctor your system is ready to brew this output means you're ready to install python packages through homebrew installing python to install the latest version of python enter the following commandbrew install python let' check which version was installed using this commandpython --version python installing python
501
python and you can use the python command to configure your text editor so it runs python programs with python instead of python python on windows python isn' usually included by default on windowsbut it' worth checking to see if it exists on the system open terminal window by rightclicking on your desktop while holding the shift keyand then select open command window here you can also enter command into the start menu in the terminal window that pops uprun the following commandpython --version python if you see output like thispython is already installedbut you still might want to install newer version if you see an error messageyou'll need to download and install python installing python on windows go to download the installerand when you run it make sure to check the add python to path option this will let you use the python command instead of having to enter your system' full path to pythonand you won' have to modify your system' environment variables manually after you've installed pythonissue the python --version command in new terminal window if it worksyou're done finding the python interpreter if the simple command python doesn' workyou'll need to tell windows where to find the python interpreter to find itopen your drive and find the folder with name starting with python (you might need to enter the word python in the windows explorer search bar to find the right folderopen the folderand look for file with the lowercase name python rightclick this file and choose propertiesyou'll see the path to this file under the heading location in the terminal windowuse the path to confirm the version you just installedc:\\python \python --version python appendix
502
it' annoying to type the full path each time you want to start python terminalso we'll add the path to the system so you can just use the command python if you already checked the add python to path box when installingyou can skip this step open your system' control panelchoose system and securityand then choose system click advanced system settings in the window that pops upclick environment variables in the box labeled system variableslook for variable called path click edit in the box that pops upclick in the box labeled variable value and use the right arrow key to scroll all the way to the right be careful not to overwrite the existing variableif you doclick cancel and try again add semicolon and the path to your python exe file to the existing variable%systemroot%\system \system \windowspowershell\ \; :\python close your terminal window and open new one this will load the new path variable into your terminal session now when you enter python --versionyou should see the version of python you just set in your path variable you can now start python terminal session by just entering python at command prompt python keywords and built-in functions python comes with its own set of keywords and built-in functions it' important to be aware of these when you're naming variables one challenge in programming is coming up with good variable nameswhich can be anything that' reasonably short and descriptive but you can' use any of python' keywordsand you shouldn' use the name of any of python' built-in functions because you'll overwrite the functions in this section we'll list python' keywords and built-in function namesso you'll know which names to avoid python keywords each of the following keywords has specific meaningand you'll see an error if you try to use them as variable name false none true and as assert break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield installing python
503
you won' get an error if you use one of the following readily available built-in functions as variable namebut you'll override the behavior of that functionabs(all(any(basestring(bin(bool(bytearray(callable(chr(classmethod(cmp(compile(complex(delattr(dict(dir(note appendix divmod(input(enumerate(int(eval(isinstance(execfile(issubclass(file(iter(filter(len(float(list(format(locals(frozenset(long(getattr(map(globals(max(hasattr(memoryview(hash(min(help(next(hex(object(id(oct(open(staticmethod(ord(str(pow(sum(print(super(property(tuple(range(type(raw_input(unichr(reduce(unicode(reload(vars(repr(xrange(reversed(zip(round(__import__(set(apply(setattr(buffer(slice(coerce(sorted(intern(in python print is keywordnot function alsounicode(is not available in python neither of these words should be used as variable name
504
edi programmers spend lot of time writingreadingand editing codeand using text editor that makes this work as efficient as possible is essential an efficient editor should highlight the structure of your code so you can catch common bugs as you're working it should also include automatic indentingmarkers to show appropriate line lengthand keyboard shortcuts for common operations as new programmeryou should use an editor that has these features but doesn' have steep learning curve it' also good to know little about more advanced editors so you'll know when to consider upgrading we'll look at quality editor for each of the main operating systemsgeany for beginners working on linux or windowsand sublime text for os (though it also works well on linux and windowswe'll also look at idlethe editor that comes with python by default finallywe'll look at
505
you spend more time programming we'll use hello_world py as an example program to run in each editor geany geany is simple text editor that lets you run almost all of your programs directly from the editor it also displays your output in terminal windowwhich helps you get comfortable using terminals installing geany on linux you can install geany using one line on most linux systemssudo apt-get install geany if you have multiple versions of python installedyou'll have to configure geany so it uses the correct version open geanyselect file save asand save the empty file as hello_world py enter the following line in the editing windowprint("hello python world!"go to build set build commands you should see the fields compile and execute with command next to each geany assumes python is the correct command for each of thesebut if your system uses the python commandyou'll need to change this in compileenterpython - py_compile "%fmake sure the spaces and capitalization in your compile command exactly match what is shown here use this execute commandpython "%fagainmake sure the spacing and capitalization exactly match what is shown here installing geany on windows you can download windows installer for geany by going to geany organd clicking releases in the download menu run the installer called geany- _setup exeor something similarand accept all of the defaults open geanyselect file save asand save the empty file as hello_world py enter the following line in the editing windowprint("hello python world!" appendix
506
compile and execute with command next to each each of these commands starts with python (in lowercase)but geany doesn' know where your system stored the python command you need to add the path you use when starting terminal session (you can skip these steps if you set the path variable as described in appendix in the compile and execute commandsadd the drive your python command is onand the folder where the python command is stored your compile command should look like thisc:\python \python - py_compile "%fyour path may be little differentbut make sure the spaces and capitalization exactly match what is shown here your execute command should look something like thisc:\python \python "%fagainmake sure the spacing and capitalization in your execute command exactly match what is shown here when you have these lines set correctlyclick ok you should now be able to run your program successfully running python programs in geany there are three ways to run program in geany to run hello_world pyselect build execute in the menuor click the icon with set of gearsor press when you run hello_world pyyou should see terminal window pop up with the following outputhello python world(program exited with code press return to continue customizing geany settings now we'll set up geany to be as efficient as possible by customizing the features mentioned at the beginning of this appendix converting tabs to spaces mixing tabs and spaces in your code can cause problems in your python programs that are very difficult to diagnose to check the indentation settings in geanygo to edit preferences editor indentation set the tab width to and set type to spaces if you have mix of tabs and spaces in one of your programsyou can convert all tabs to spaces with document replace tabs by spaces text editors
507
most editors allow you to set up visual cueusually vertical lineto show where your lines should end set this feature by selecting edit preferences editor displayand make sure that long line marker is enabled then make sure the value of column is set to indenting and unindenting code blocks to indent block of codehighlight the code and go to edit format increase indentor press ctrl- to unindent block of codego to edit format decrease indentor press ctrl- commenting out blocks of code to temporarily disable block of codeyou can highlight the block and comment it so python will ignore it go to edit format toggle line commentation (ctrl-ethe line will be commented out with special sequence (#~to indicate it' not regular comment when you want to uncomment the block of codehighlight the block and issue the same command again sublime text sublime text is simple text editor that' easy to install on os (and other systems as well)and lets you run almost all your programs directly from the editor it also runs your code in terminal session embedded in the sublime text windowwhich makes it easy to see the output of your code sublime text has very liberal licensing policyyou can use the editor free of charge as long as you wantbut the author requests that you purchase license if you like it and want to continue using it we'll download sublime text the most recent version at the time of this writing installing sublime text on os download the installer for sublime text from com/ follow the download link and click the installer for os when it' downloadedopen the installer and drag the sublime text icon into your applications folder installing sublime text on linux on most linux systemsit' easiest to install sublime text from terminal sessionlike thissudo add-apt-repository ppa:webupd team/sublime-text- sudo apt-get update sudo apt-get install sublime-text-installer appendix
508
download an installer for windows from run the installerand you should see sublime text in your start menu running python programs in sublime text if you're using the version of python that came with your systemyou'll probably be able to run your programs without adjusting any settings to run programsgo to tools build or press ctrl - when you run hello_world pyyou should see terminal screen appear at the bottom of the sublime text window displaying the following outputhello python world[finished in sconfiguring sublime text if you have multiple versions of python installed or if sublime text won' run python programs automaticallyyou'll have to set up configuration file firstyou'll need to know the full path to your python interpreter on linux and os xissue the following commandtype - python python is /usr/local/bin/python replace python with the command you normally use to start terminal session if you're using windowssee "installing python on windowson page to find the path to your python interpreter now open sublime textand go to tools build system new build systemwhich will open new configuration file for you delete what you seeand enter the followingpython sublime-build "cmd"["/usr/local/bin/python ""- ""$file"]this code tells sublime text to use the python command when running the currently open file make sure you use the path you found in the previous step (on windowsyour path will look something like :/python pythonsave the file as python sublime-build in the default directory that sublime text opens when you choose save open hello_world pyselect tools build system python and then select tools build you should see your output in terminal embedded at the bottom of the sublime text window text editors
509
now we'll set up sublime text to be as efficient as possible by customizing the features mentioned at the beginning of this appendix converting tabs to spaces go to view indentation and make sure there' check mark next to indent using spaces if there isn'tcheck it setting the line length indicator go to view rulerand then click sublime text will place vertical line at the -character mark indenting and unindenting code blocks to indent block of codehighlight it and select edit line indent or press ctrl-to unindent block of codeclick edit line unindent or press ctrl-commenting out blocks of code to comment out highlighted block of codeselect edit comment toggle commentor press ctrl-to uncomment block of codeissue the same command again idle idle is python' default editor it' little less intuitive to work with than geany or sublime textbut you'll see references to it in other tutorials aimed at beginnersso you might want to give it try installing idle on linux if you're using python install the idle package like thissudo apt-get install idle if you're using python install the idle package like thissudo apt-get install idle installing idle on os if you used homebrew to install pythonidle is probably already on your system in terminalrun the command brew linkappswhich tells idle how to find the correct python interpreter on your system you'll then find idle in your user applications folder appendix
510
the instructions thereyou'll also need to install few graphical packages that idle depends on installing idle on windows idle should have been installed automatically when you installed python you should find it in your start menu customizing idle settings because it' the default python editormost of the settings in idle are already attuned to recommended python settingstabs are automatically converted into spacesand the line length indicator is set to characters wide indenting and unindenting code blocks to indent block of codehighlight it and select format indent region or press ctrl-to unindent block of codeselect format dedent region or press ctrl-commenting out blocks of code to comment out block of codehighlight the codeand then select format comment out regionor press alt- to uncomment the codeselect format uncomment regionor press alt- emacs and vim emacs and vim are two popular editors favored by many experienced programmers because they're designed to be used so your hands never have to leave the keyboard this makes writingreadingand modifying code very efficient once you learn how the editor works it also means they have fairly steep learning curve programmers will often recommend that you give them trybut many proficient programmers forget how much new programmers are already trying to learn it' beneficial to be aware of these editorsbut hold off on using them until you're comfortable writing and working with code in simpler editor that lets you focus on learning to program rather than learning to use an editor text editors
511
get ting help everyone gets stuck at some point when they're learning to programand one of the most important skills to learn as programmer is how to get unstuck efficiently this appendix outlines several ways to help you get unstuck when programming gets confusing first steps when you're stuckyour first step should be to assess your situation before you can get help from anyone elseyou'll need to be able to answer the following three questions clearlywhat are you trying to dowhat have you tried so farwhat results have you been getting
512
explicit statements like " ' trying to install the latest version of python on my windows machineare detailed enough for others in the python community to help you statements like " ' trying to install pythondon' provide enough information for others to offer much help your answer to the second question should provide enough detail that you won' be advised to repeat what you've already tried" went to python org/downloadsand clicked the download button for python then ran the installeris more helpful than" went to the python website and downloaded an installer for the final questionit' helpful to know the exact error messages you received when you're searching online for solution or when asking for help sometimes answering these three questions for yourself allows you to see something you're missing and get you unstuck without having to go any further programmers even have name for thisit' called rubber duck debugging if you explain your situation to rubber duck (or any inanimate objectclearlyand ask it specific questionyou'll often be able to answer your own question some programming shops even keep real rubber duck around to encourage people to "talk to the duck try it again just going back to the start and trying again can be enough to solve many problems say you're trying to write for loop based on an example from this book you might have only missed something simplelike colon at the end of the for line going through the steps again might help you avoid repeating the same mistake take break if you've been working on the same problem for whiletaking break is actually one of the best tactics you can try when we work on the same task for long periods of timeour brains start to zero in on only one solution we lose sight of the assumptions we've madeand taking break helps us get fresh perspective on the problem it doesn' need to be long breakjust something that gets you out of your current mindset if you've been sitting for long timedo something physicaltake short walk or go outside for bitmaybe drink glass of water or eat light and healthy snack if you're getting frustratedit might be worth putting your work away for the day good night' sleep almost always makes problem more approachable refer to this book' resources the online resources for this bookavailable through com/pythoncrashcourse/include number of helpful sections about setting up your system and working through each if you haven' done so alreadytake look at these resources and see if there' anything that helps appendix
513
chances are that someone else has had the same problem you're having and has written about it online good searching skills and specific inquiries will help you find existing resources to solve the issue you're facing for exampleif you're struggling to install python on windows searching python windows might direct you to the answer searching the exact error message can be extremely helpful too for examplesay you get the following error when you try to start python terminal sessionpython 'pythonis not recognized as an internal or external command searching for the full phrase python is not recognized as an internal or external command will probably yield some good advice when you start searching for programming-related topicsa few sites will appear repeatedly 'll describe some of these sites brieflyso you'll know how helpful they're likely to be stack overflow stack overflow (question-and-answer sites for programmersand will often appear in the first page of results on python-related searches members post questions when they're stuckand other members try to give helpful responses users can vote for the responses they find most helpfulso the best answers are usually the first ones you'll find many basic python questions have very clear answers on stack overflowbecause the community has refined them over time users are encouraged to post updates tooso responses tend to stay relatively current at the time of this writingover , python-related questions have been answered on stack overflow the official python documentation the official python documentation (hit or miss for beginnersbecause the purpose is more to document the language than write explanations the examples in the official documentation should workbut you might not understand everything shown stillit' good resource to check when it comes up in your searches and will become more useful to you as you continue building your understanding of python getting help
514
if you're using specific librarysuch as pygamematplotlibdjangoand so onlinks to the official documentation for that project will often appear in searches--for exampleplanning to work with any of these librariesit' good idea to become familiar with the official documentation /learnpython reddit is made up of number of subforums called subreddits the /learnpython subreddit (supportive here you can read othersquestions and post your own blog posts many programmers maintain blogs and share posts about the parts of the language they're working with you should skim the first few comments on blog post to see what reactions other people have had before taking any advice if no comments appeartake the post with grain of salt it' possible no one else has verified the advice irc (internet relay chatprogrammers interact in real time through irc if you're stuck on problem and searching online isn' providing answersasking in an irc channel might be your best option most people who hang out in these channels are polite and helpfulespecially if you can be specific about what you're trying to dowhat you've already triedand what results you're getting make an irc account to create an account on ircgo to nicknamefill out the captcha boxand click connect you'll see message welcoming you to the freenode irc server in the box at the bottom of the windowenter the following command/msg nickserv register password email enter your own password and email address in place of password and email choose simple password that you don' use for any other account this password is not transmitted securelyso don' even try to make secure password you'll receive an email with instructions to verify your account the email will provide you with command like this/msg nickserv verify register nickname verification_code paste this line into the irc site with nickname as the name you chose earlier and value for verification_code now you're ready to join channel appendix
515
to join the main python channelenter /join #python in the input box you'll see confirmation that you joined the channel and some general information about the channel the channel ##learnpython (with two hashtagsis usually quite active as well this channel is associated with see messages about posts on /learnpython too the #pyladies channel focuses on supporting women who are learning pythonas well as people who are supportive of women programmers you might want to join the #django channel if you're working on web applications after you've joined channelyou can read the conversations other people are having and ask your own questions as well irc culture to get effective helpyou should know few details about irc culture focusing on the three questions at the beginning of this appendix will definitely help guide you to successful solution people will be happy to help you if you can explain precisely what you're trying to dowhat you've already triedand the exact results you're getting if you need to share code or outputirc members use external sites made for this purposesuch as output this keeps the channels from being flooded with code and also makes it much easier to read the code that people share being patient will always make people more likely to help you ask your question conciselyand then wait for someone to respond oftenpeople are in the middle of many conversationsbut usually someone will address you in reasonable amount of time if few people are in the channelit might take while to get response getting help
516
gi version control software allows you to take snapshots of project whenever it' in working state when you make changes to project--for examplewhen you implement new feature--you have the option of reverting back to previous working state if the project' current state isn' functioning well using version control software gives you the freedom to work on improvements and make mistakes without worrying about ruining your project this is especially critical in large projectsbut can also be helpful in smaller projectseven when you're working on programs contained in single file in this appendix you'll learn to install git and use it for version control in the programs you're working on now git is the most popular version control software in use today many of its advanced tools help teams
517
solo developers git implements version control by tracking the changes made to every file in projectif you make mistakeyou can just return to previously saved state installing git git runs on all operating systemsbut there are different approaches to installing it on each system the following sections provide specific instructions for each operating system installing git on linux to install git on linuxenter the followingsudo apt-get install git that' it you can now use git in your projects installing git on os git may already be installed on your systemso try issuing the command git --version if you see output listing specific version numbergit is installed on your system if you see message prompting you to install or update gitsimply follow the onscreen directions you can also go to click an appropriate installer for your system installing git on windows you can install git for windows from configuring git git keeps track of who makes changes to projecteven when there' only one person working on the project to do thisgit needs to know your username and email you have to provide usernamebut feel free to make up fake email addressgit config --global user name "usernamegit config --global user email "username@example comif you forget this stepgit will prompt you for this information when you make your first commit appendix
518
let' make project to work with create folder somewhere on your system called git_practice inside the foldermake simple python programhello_world py print("hello git world!"we'll use this program to explore git' basic functionality ignoring files files with the extension pyc are automatically generated from py filesso we don' need git to keep track of them these files are stored in directory called __pycache__ to tell git to ignore this directorymake special file called gitignore--with dot at the beginning of the filename and no file extension--and add the following line to itgitignore __pycache__this tells git to ignore any file in the __pycache__ directory using gitignore file will keep your project clutter free and easier to work with note if you're using python replace this line with pyc python doesn' create __pycache__ directoryeach pyc file is stored in the same directory as its corresponding py file the asterisk tells git to ignore any file with the pyc extension you might need to modify your text editor' settings so it will show hidden files in order to open gitignore some editors are set to ignore filenames that begin with dot initializing repository now that you have directory containing python file and gitignore fileyou can initialize git repository open terminalnavigate to the git_practice folderand run the following commandgit_practicegit init initialized empty git repository in git_practicegitgit_practicethe output shows that git has initialized an empty repository in git_practice repository is the set of files in program that git is actively tracking all the files git uses to manage the repository are located in the hidden directory git/which you won' need to work with at all just don' delete that directoryor you'll lose your project' history using git for version control
519
before doing anything elselet' look at the status of the projectgit_practicegit status on branch master initial commit untracked files(use "git add to include in what will be committedgitignore hello_world py nothing added to commit but untracked files present (use "git addto trackgit_practicein gita branch is version of the project you're working onhere you can see that we're on branch named master each time you check your project' statusit should say that you're on the branch master we then see that we're about to make the initial commit commit is snapshot of the project at particular point in time git informs us that untracked files are in the project vbecause we haven' told it which files to track yet then we're told that there' nothing added to the current commitbut there are untracked files present that we might want to add to the repository adding files to the repository let' add the two files to the repositoryand check the status againu git_practicegit add git_practicegit status on branch master initial commit changes to be committed(use "git rm --cached to unstagew new filegitignore new filehello_world py git_practicethe command git add adds all files within project that are not already being tracked to the repository it doesn' commit the filesit just tells git to start paying attention to them when we check the status of the appendix
520
committed the label new file means these files were newly added to the repository making commit let' make the first commitu git_practicegit commit - "started project [master (root-commitc started project files changed insertion(+create mode gitignore create mode hello_world py git_practicegit status on branch master nothing to commitworking directory clean git_practicewe issue the command git commit - "messageu to take snapshot of the project the - flag tells git to record the message that follows ("started project "in the project' log the output shows that we're on the master branch and that two files have changed when we check the status nowwe can see that we're on the master branchand we have clean working directory this is the message you want to see each time you commit working state of your project if you get different messageread it carefullyit' likely you forgot to add file before making commit checking the log git keeps log of all commits made to the project let' check the loggit_practicegit log commit aa cb eac cfc authoreric matthes datemon mar : : - started project git_practiceeach time you make commitgit generates unique -character reference id it records who made the commitwhen it was madeand the message recorded you won' always need all of this informationso git provides an option to print simpler version of the log entriesgit_practicegit log --pretty=oneline aa cb eac cfc started project git_practiceusing git for version control
521
informationthe reference id of the commit and the message recorded for the commit the second commit to see the real power of version controlwe need to make change to the project and commit that change here we'll just add another line to hello_world pyhello_world py print("hello git world!"print("hello everyone "if we check the status of the projectwe'll see that git has noticed the file that changedgit_practicegit status on branch master changes not staged for commit(use "git add to update what will be committed(use "git checkout -to discard changes in working directoryv modifiedhello_world py no changes added to commit (use "git addand/or "git commit - "git_practicewe see the branch we're working on uthe name of the file that was modified vand that no changes have been committed let' commit the change and check the status againu git_practicegit commit -am "extended greeting [master eextended greeting file changed insertion(+ git_practicegit status on branch master nothing to commitworking directory clean git_practicegit log --pretty=oneline cb cff bd ab ed extended greeting be dbc ff be fd started project git_practicewe make new commitpassing the -am flag when we use the command git commit the - flag tells git to add all modified files in the repository to the current commit (if you create any new files between commitssimply reissue the git add command to include the new files in the repository the - flag tells git to record message in the log for this commit when we check the status of the projectwe see that we once again have clean working directory finallywe see the two commits in the log appendix
522
now let' see how to abandon change and revert back to the previous working state firstadd new line to hello_world pyhello_world py print("hello git world!"print("hello everyone "print("oh noi broke the project!"save and run this file we check the status and see that git notices this changegit_practicegit status on branch master changes not staged for commit(use "git add to update what will be committed(use "git checkout -to discard changes in working directoryu modifiedhello_world py no changes added to commit (use "git addand/or "git commit - "git_practicegit sees that we modified hello_world py uand we can commit the change if we want to but this timeinstead of committing the changewe want to revert back to the last commit when we knew our project was working we won' do anything to hello_world pywe won' delete the line or use the undo feature in the text editor insteadenter the following commands in your terminal sessiongit_practicegit checkout git_practicegit status on branch master nothing to commitworking directory clean git_practicethe command git checkout allows you to work with any previous commit the command git checkout abandons any changes made since the last commit and restores the project to the last committed state when you return to your text editoryou'll see that hello_world py has changed back to thisprint("hello git world!"print("hello everyone "although going back to previous state may seem trivial in this simple projectif we were working on large project with dozens of modified filesall of the files that had changed since the last commit would be reverted this feature is incredibly usefulyou can make as many changes as you using git for version control
523
changes and manually undo them git does all of that for you note you might have to click in your editor' window to refresh the file and see the previous version checking out previous commits you can check out any commit in your lognot just the most recentby including the first six characters of the reference id instead of dot by checking it outyou can review an earlier commitand you're able to then return to the latest commit or abandon your recent work and pick up development from the earlier commitgit_practicegit log --pretty=oneline cb cff bd ab ed extended greeting be dbc ff be fd started project git_practicegit checkout be notechecking out 'be bu you are in 'detached headstate you can look aroundmake experimental changes and commit themand you can discard any commits you make in this state without impacting any branches by performing another checkout if you want to create new branch to retain commits you createyou may do so (now or laterby using - with the checkout command again examplegit checkout - new_branch_name head is now at be started project git_practicewhen you check out previous commityou leave the master branch and enter what git refers to as detached head state head is the current state of the projectwe are detached because we've left named branch (masterin this caseto get back to the master branchyou check it outgit_practicegit checkout master previous head position was be started project switched to branch 'mastergit_practicethis brings you back to the master branch unless you want to work with some more advanced features of gitit' best not to make any changes to your project when you've checked out an old commit howeverif you're appendix
524
recent commits and go back to previous stateyou can reset the project to previous commit working from the master branchenter the followingu git_practicegit status on branch master nothing to commitworking directory clean git_practicegit log --pretty=oneline cb cff bd ab ed extended greeting be dbc ff be fd started project git_practicegit reset --hard be head is now at be started project git_practicegit status on branch master nothing to commitworking directory clean git_practicegit log --pretty=oneline be dbc ff be fd started project git_practicewe first check the status to make sure we're on the master branch when we look at the logwe see both commits we then issue the git reset --hard command with the first six characters of the reference id of the commit we want to revert to permanently we check the status again and see we're on the master branch with nothing to commit when we look at the log againwe see that we're at the commit we wanted to start over from deleting the repository sometimes you'll mess up your repository' history and won' know how to recover it if this happensfirst consider asking for help using the methods discussed in appendix if you can' fix it and you're working on solo projectyou can continue working with the files but get rid of the project' history by deleting the git directory this won' affect the current state of any of the filesbut it will delete all commitsso you won' be able to check out any other states of the project to do thiseither open file browser and delete the git repository or do it from the command line afterwardsyou'll need to start over with fresh repository to start tracking your changes again here' what this entire process looks like in terminal sessionu git_practicegit status on branch master nothing to commitworking directory clean git_practicerm -rf git git_practicegit status fatalnot git repository (or any of the parent directories)git git_practicegit init initialized empty git repository in git_practicegitusing git for version control
525
on branch master initial commit untracked files(use "git add to include in what will be committedgitignore hello_world py nothing added to commit but untracked files present (use "git addto trackz git_practicegit add git_practicegit commit - "starting over [master (root-commit starting over files changed insertions(+create mode gitignore create mode hello_world py git_practicegit status on branch master nothing to commitworking directory clean git_practicewe first check the status and see that we have clean working directory then we use the command rm -rf git to delete the git directory (rmdir / git on windowsv when we check the status after deleting the git folderwe're told that this is not git repository all the information git uses to track repository is stored in the git folderso removing it deletes the entire repository we're then free to use git init to start fresh repository checking the status shows that we're back at the initial stageawaiting the first commit we add the files and make the first commit checking the status now shows us that we're on the new master branch with nothing to commit using version control takes bit of practicebut once you start using it you'll never want to work without it again appendix
526
symbols (addition) (asteriskoperator bmp (bitmapimage files (concatenation operator) - (division) =(equality operator) (greater than) >(greater than or equal to) (hash mark)for comments !(inequality operator) (less than) <(less than or equal to) (modulo operator) - (multiplication) \ (newline) (not) +operator py file extension [(square brackets) (subtraction) \ (tab) addition (+) aliases alice py - alien invasion project see also pygame aliens alien class building fleet of - changing directions checking edges creating creating rows of drawing to the screen dropping fitting in row movement - multiple rows of reaching bottom of screen rebuilding fleet of background colorsetting bullets bullet class - checking with print statements deleting old firing limiting the number of making larger settings speeding up classes alien bullet - button scoreboard settings ship collisions alien-bullet alien-ship - ending game - keyboard shortcuts levels adding - modifying speed settings resetting speeds planning
527
play button adding - button class deactivating drawing hiding the mouse cursor resetting the game starting the game reviewing scoring displaying the level - displaying the number of ships - displaying the score increasing point values making scoring system - rounding and formatting the score scoreboard class scoring all hits tracking the high score tracking the score ship adjusting speed - continuous movement - finding an image limiting range ship class alien py - aliens py - americas py amusement_park py - and keyword - api (application programming interface) call processing response - requesting data using summarizing results of for hacker news - rate limits apostrophe py index append(method - application programming interface see api (application programming interfacearguments - see also functions arithmetic as keyword assert methods - asterisk (*operator attributes accessing default values modifying values - banned_users py bash bicycles py - birthday py bitmap bmpimage files body of function of an html file boolean values bootstrap built-in functions calling functions - methods camelcaps car py - car py module - - cars py - child classes see also classesinheritance cities py classes - attributes accessing default values modifying values - creating -
528
all classes from module - entire module module into module - multiple classes - single class - inheritance - attributes and methods - __init__(method - instances as attributes - overriding methods in python super(function methods calling __init()__ modeling real-world objects - multiple instancescreating styling guidelines - colormap_colors py colors hex format pygal themes comma-separated value files see csv (comma-separated valuefiles comment py comments - comparison operators - concatenation operator (+) - conditional tests - confirmed_users py counting py countries py country codes - country_codes py csv (comma-separated valuefiles - error-checking parsing headers reading data databases see djangodatabasesherokudatabases data mining data visualization - see also matplotlibpygal datetime module - death valleyweather data - debugging tips - decorators default values class attributes function parameters def keyword del statement dice_visual py - dictionaries defining empty formatting larger key-value pairs adding removing looping through keys - keys in order - key-value pairs - values - values accessing modifying - die class die py die_visual py - dimensions py - div (html) division (/) division py - django see also herokulearning log project admin site - bootstrap current working directory index
529
data associating with user connecting to users restricting access to - databases creating foreign keys many-to-one relationships migrating - queries querysets forms - cross-site request forgery displaying get and post requests modelform processing validation widgets hashes (for passwords) http error installed_appsmodifying jquery localhost @login_required login view manage py models - privileges runserver command static files superusersetting up templates anchor tags block tags context filters linebreaks filter template tags third party apps urls namespaces patterns index regular expressions user id values views web server gateway interface django-boostrap app docstrings dog py - dot notation einsteinalbert electric_car py - electric_car py module elif statement - else statement - emacs epoch time equality operator (==) even_numbers py even_or_odd py event loops - exceptionshandling deciding which errors to report else blocks - failing silently - filenotfounderror - to prevent crashes - try-except blocks - zerodivisionerror favorite_languages py - - filenotfounderror - file_reader py - files closing large - opening paths - reading entire files - line by line by making list of lines
530
working with contents writing to by appending empty files multiple lines flags floats - foods py - for loops - functions arguments - arbitrary - avoiding errors with - keyword - lists as - optional - order of positional arguments - built-in calling - multiple times - defining dictionariesreturning - import statements lists in modifying - preventing modifying - modulesstoring in - see also modules parametersdefault values for passing information to return values - styling games see alien invasion projectpygame geany - commenting out blocks customizing settings indenting and unindenting blocks installing on linux on windows - running python programs get-pip py see also pip get requests git - branches commits checking out previous making detached head files adding ignoring head installing logchecking projects checking status of making repositories deleting initializing reverting changes - github see also git greater than (>) greater than or equal to (>=) greeter py - - greet_users py gunicorn - hacker news hash mark (#)for comments headof an html file head (git) hello world hello_world py - heroku see also djangolearning log project bash databases migrating setting up using postgres index
531
making an account procfile projects deleting pushing to securing python runtimespecifying settings pymodifying for superusercreating toolbeltinstalling user-friendly urls wsgi pymodifying for hex formatfor colors highs_lows py - hn_submissions py - homebrew idle - commenting out code customizing settings installing on linux on os on windows if statements and keyword - boolean expressions checking for empty lists equality (==) - inequality (!=) items in list - items not in list special items - elif statement - else statement - if-elif-else chains - lists and - numerical comparisons - or keyword simple - styling guidelines testing multiple conditions - import * import this index indentation errors - index errors inequality operator (!=) infinite loops - inheritance see also classesinheritance input(function numerical input - prompts - insert(method int irc (internet relay chat) - itemgetter(function - items(method jquery json dump(function json files converting strings to numerical values extracting data json load(function jumbotron keys(method key-value pairs see also dictionaries keyword arguments - keywords language_survey py learning log project see also djangoheroku deployment commitsusing git - custom error pages - get_object_or_ (method ignoring files in git making static file directory ongoing development procfile
532
secret_key setting using gunicorn locally html headersdefining logging out - login page - migrating the database - styling bootstrap collapsible navigation jumbotron navigation bar - selectors registration page - users app default login view displaying messages to logged-in users logging in user usercreationform len(function less than (<) less than or equal to (<=) linux geany (text editor) - python checking installed version installing - setting up - running hello world - terminal running commands from running programs from troubleshooting installation issues lists - append(method as arguments - copying - del elements accessing - adding - modifying empty for loops - if statements - indentation errors - indexes errors - negative insert(method len(function list comprehensions - max(function min(function naming numerical - pop(method - range(function - remove(method removing all occurrences of value reverse(method slices - sorted(function sort(method sum(function localhost logical errors lower(method lstrip(method magicians py - magic_number py making_pizzas py - matplotlib formatting plots axes color - labels - line thickness - shading size installing - plot(function plotting dates multiple data series pyplot module saving plots scatter plots - simple line graphs index
533
classes modelform modules - aliases for functions aliases for importing all importing specific importing an entire module modulo operator (%) - motorcycles py - mountain_poll py mpl_squares py - multiplication (*) my_car py my_cars py - my_electric_car py name errors - name_function py - name py - names py na_populations py nesting dictionaries in dictionaries - dictionaries in lists - lists in dictionaries - newline (\ ) not (!) number_reader py numbers arithmetic avoiding type errors - comparisons - exponents floats - integers - order of operations str(function numbers py number_writer py index object-oriented programming see also classes open(function operator module - or keyword os python checking installed version - installing - setting up - running hello world sublime text (text editor) - terminal running commands from running programs from troubleshooting installation issues parameters - parent classes see also classesinheritance parrot py - pass statement pep - person py - peterstim pets py - pi - pip checking for get-pip py installing pi_string py - pizza py - planning project players py - pop(method - positional arguments - postgres post requests
534
print statements long in python privileges procfile project gutenberg promptsfor user input - py file extension pygal charts histograms - linksadding styling - tooltipsadding color themes installing plotting dictionaries rolling dice worldmap - grouping countries - plotting numerical data - styling - pygame see also alien invasion project bitmap bmpimage files colors - creating an empty window displaying text drawing images to the screen groups emptying storing elements in updating all elements in installing - positioning images with rect responding to input - keypresses - mouse clicks - screen coordinates surfaces pyplot module python built-in functions documentation installing on linux - on os on windows - interpreter keywords pep - standard library - terminal session --version zen of - python creating classes in division of integers in print statements in raw_input(function python enhancement proposal (pep) python_repos py - queries in databases on github ( =) - querysetsin databases quit values - random_walk py random walks - coloring points - fill_walk(method multiple walksgenerating - plotting - randomwalk class starting and ending pointsplotting range(function - readlines(method read(method rectpositioning images with reddit refactoring - remember_me py - requests package index
535
debugging tips - documentation - irc (internet relay chat) - channels culture making an account reddit stack overflow return values rollercoaster py rolling dice analyzing results different sizes two dice rubber duck debugging rw_visual py - scatter_squares py - secret_key setting setup(method sitkaalaskaweather data - slice sorted(function sort(method split(method sqlite square brackets ([]) squares py stack overflow storing data json dump(method json load(method saving and reading data - str(function strings changing case concatenating newlines in single and double quotes tabs in whitespace in - strip(method index style guidelines blank lines camelcaps classes functions if statements indentation line length pep subclasses see also classesinheritance sublime text commenting out code configuring indenting and unindenting code blocks installing on linux on os on windows running python programs subtraction (-) superclasses see also classesinheritance superuser in django in heroku survey py syntax errors syntax highlighting tab (\ ) testing code adding tests assert methods - failing tests - full coverage functions - passing tests - test case testing classes - examples - setup(method unittest module unit tests test_name_function py -
536
preface xxxiii part getting started python & session why do people use pythonsoftware quality developer productivity is python "scripting language"okbut what' the downsidewho uses python todaywhat can do with pythonsystems programming guis internet scripting component integration database programming rapid prototyping numeric and scientific programming and moregamingimagesdata miningrobotsexcel how is python developed and supportedopen source tradeoffs what are python' technical strengthsit' object-oriented and functional it' free it' portable it' powerful it' mixable it' relatively easy to use it' relatively easy to learn it' named after monty python
537
summary test your knowledgequiz test your knowledgeanswers how python runs programs introducing the python interpreter program execution the programmer' view python' view execution model variations python implementation alternatives execution optimization tools frozen binaries future possibilitiessummary test your knowledgequiz test your knowledgeanswers how you run programs the interactive prompt starting an interactive session the system path new windows options in pathlauncher where to runcode directories what not to typeprompts and comments running code interactively why the interactive promptusage notesthe interactive prompt system command lines and files first script running files with command lines command-line usage variations usage notescommand lines and files unix-style executable scripts#unix script basics the unix env lookup trick the python windows launcher#comes to windows clicking file icons icon-click basics clicking icons on windows the input trick on windows other icon-click limitations vi table of contents
538
import and reload basics the grander module storyattributes usage notesimport and reload using exec to run module files the idle user interface idle startup details idle basic usage idle usability features advanced idle tools usage notesidle other ides other launch options embedding calls frozen binary executables text editor launch options still other launch options future possibilitieswhich option should usesummary test your knowledgequiz test your knowledgeanswers test your knowledgepart exercises part ii types and operations introducing python object types the python conceptual hierarchy why use built-in typespython' core data types numbers strings sequence operations immutability type-specific methods getting help other ways to code strings unicode strings pattern matching lists sequence operations type-specific operations table of contents vii
539
nesting comprehensions dictionaries mapping operations nesting revisited missing keysif tests sorting keysfor loops iteration and optimization tuples why tuplesfiles binary bytes files unicode text files other file-like tools other core types how to break your code' flexibility user-defined classes and everything else summary test your knowledgequiz test your knowledgeanswers numeric types numeric type basics numeric literals built-in numeric tools python expression operators numbers in action variables and basic expressions numeric display formats comparisonsnormal and chained divisionclassicfloorand true integer precision complex numbers hexoctalbinaryliterals and conversions bitwise operations other built-in numeric tools other numeric types decimal type fraction type sets booleans viii table of contents
540
summary test your knowledgequiz test your knowledgeanswers the dynamic typing interlude the case of the missing declaration statements variablesobjectsand references types live with objectsnot variables objects are garbage-collected shared references shared references and in-place changes shared references and equality dynamic typing is everywhere summary test your knowledgequiz test your knowledgeanswers string fundamentals this scope unicodethe short story string basics string literals singleand double-quoted strings are the same escape sequences represent special characters raw strings suppress escapes triple quotes code multiline block strings strings in action basic operations indexing and slicing string conversion tools changing strings string methods method call syntax methods of strings string method exampleschanging strings ii string method examplesparsing text other common string methods in action the original string module' functions (gone in xstring formatting expressions formatting expression basics advanced formatting expression syntax advanced formatting expression examples table of contents ix
541
string formatting method calls formatting method basics adding keysattributesand offsets advanced formatting method syntax advanced formatting method examples comparison to the formatting expression why the format methodgeneral type categories types share operation sets by categories mutable types can be changed in place summary test your knowledgequiz test your knowledgeanswers lists and dictionaries lists lists in action basic list operations list iteration and comprehensions indexingslicingand matrixes changing lists in place dictionaries dictionaries in action basic dictionary operations changing dictionaries in place more dictionary methods examplemovie database dictionary usage notes other ways to make dictionaries dictionary changes in python and summary test your knowledgequiz test your knowledgeanswers tuplesfilesand everything else tuples tuples in action why lists and tuplesrecords revisitednamed tuples files opening files using files table of contents
542
text and binary filesthe short story storing python objects in filesconversions storing native python objectspickle storing python objects in json format storing packed binary datastruct file context managers other file tools core types review and summary object flexibility references versus copies comparisonsequalityand truth the meaning of true and false in python python' type hierarchies type objects other types in python built-in type gotchas assignment creates referencesnot copies repetition adds one level deep beware of cyclic data structures immutable types can' be changed in place summary test your knowledgequiz test your knowledgeanswers test your knowledgepart ii exercises part iii statements and syntax introducing python statements the python conceptual hierarchy revisited python' statements tale of two ifs what python adds what python removes why indentation syntaxa few special cases quick exampleinteractive loops simple interactive loop doing math on user inputs handling errors by testing inputs handling errors with try statements nesting code three levels deep table of contents xi
543
test your knowledgequiz test your knowledgeanswers assignmentsexpressionsand prints assignment statements assignment statement forms sequence assignments extended sequence unpacking in python multiple-target assignments augmented assignments variable name rules expression statements expression statements and in-place changes print operations the python print function the python print statement print stream redirection version-neutral printing summary test your knowledgequiz test your knowledgeanswers if tests and syntax rules if statements general format basic examples multiway branching python syntax revisited block delimitersindentation rules statement delimiterslines and continuations few special cases truth values and boolean tests the if/else ternary expression summary test your knowledgequiz test your knowledgeanswers while and for loops while loops general format examples breakcontinuepassand the loop else xii table of contents
544
pass continue break loop else for loops general format examples loop coding techniques counter loopsrange sequence scanswhile and range versus for sequence shufflersrange and len nonexhaustive traversalsrange versus slices changing listsrange versus comprehensions parallel traversalszip and map generating both offsets and itemsenumerate summary test your knowledgequiz test your knowledgeanswers iterations and comprehensions iterationsa first look the iteration protocolfile iterators manual iterationiter and next other built-in type iterables list comprehensionsa first detailed look list comprehension basics using list comprehensions on files extended list comprehension syntax other iteration contexts new iterables in python impacts on codepros and cons the range iterable the mapzipand filter iterables multiple versus single pass iterators dictionary view iterables other iteration topics summary test your knowledgequiz test your knowledgeanswers the documentation interlude python documentation sources table of contents xiii
545
the dir function docstrings__doc__ pydocthe help function pydochtml reports beyond docstringssphinx the standard manual set web resources published books common coding gotchas summary test your knowledgequiz test your knowledgeanswers test your knowledgepart iii exercises part iv functions and generators function basics why use functionscoding functions def statements def executes at runtime first exampledefinitions and calls definition calls polymorphism in python second exampleintersecting sequences definition calls polymorphism revisited local variables summary test your knowledgequiz test your knowledgeanswers scopes python scope basics scope details name resolutionthe legb rule scope example the built-in scope the global statement xiv table of contents
546
program designminimize cross-file changes other ways to access globals scopes and nested functions nested scope details nested scope examples factory functionsclosures retaining enclosing scope state with defaults the nonlocal statement in nonlocal basics nonlocal in action why nonlocalstate retention options state with nonlocal only state with globalsa single copy only state with classesexplicit attributes (previewstate with function attributes and summary test your knowledgequiz test your knowledgeanswers arguments argument-passing basics arguments and shared references avoiding mutable argument changes simulating output parameters and multiple results special argument-matching modes argument matching basics argument matching syntax the gritty details keyword and default examples arbitrary arguments examples python keyword-only arguments the min wakeup callfull credit bonus points the punch line generalized set functions emulating the python print function using keyword-only arguments summary test your knowledgequiz test your knowledgeanswers table of contents xv
547
function design concepts recursive functions summation with recursion coding alternatives loop statements versus recursion handling arbitrary structures function objectsattributes and annotations indirect function calls"first classobjects function introspection function attributes function annotations in anonymous functionslambda lambda basics why use lambdahow (notto obfuscate your python code scopeslambdas can be nested too functional programming tools mapping functions over iterablesmap selecting items in iterablesfilter combining items in iterablesreduce summary test your knowledgequiz test your knowledgeanswers comprehensions and generations list comprehensions and functional tools list comprehensions versus map adding tests and nested loopsfilter examplelist comprehensions and matrixes don' abuse list comprehensionskiss generator functions and expressions generator functionsyield versus return generator expressionsiterables meet comprehensions generator functions versus generator expressions generators are single-iteration objects generation in built-in typestoolsand classes examplegenerating scrambled sequences don' abuse generatorseibti exampleemulating zip and map with iteration tools comprehension syntax summary scopes and comprehension variables comprehending set and dictionary comprehensions xvi table of contents
548
extended comprehension syntax for sets and dictionaries summary test your knowledgequiz test your knowledgeanswers the benchmarking interlude timing iteration alternatives timing modulehomegrown timing script timing results timing module alternatives other suggestions timing iterations and pythons with timeit basic timeit usage benchmark module and scripttimeit benchmark script results more fun with benchmarks other benchmarking topicspystones function gotchas local names are detected statically defaults and mutable objects functions without returns miscellaneous function gotchas summary test your knowledgequiz test your knowledgeanswers test your knowledgepart iv exercises part modules and packages modulesthe big picture why use modulespython program architecture how to structure program imports and attributes standard library modules how imports work find it compile it (maybe run it byte code files__pycache__ in python byte code file models in action table of contents xvii
549
configuring the search path search path variations the sys path list module file selection summary test your knowledgequiz test your knowledgeanswers module coding basics module creation module filenames other kinds of modules module usage the import statement the from statement the from statement imports happen only once import and from are assignments import and from equivalence potential pitfalls of the from statement module namespaces files generate namespaces namespace dictionaries__dict__ attribute name qualification imports versus scopes namespace nesting reloading modules reload basics reload example summary test your knowledgequiz test your knowledgeanswers module packages package import basics packages and search path settings package __init__ py files package import example from versus import with packages why use package importsa tale of three systems package relative imports xviii table of contents
550
relative import basics why relative importsthe scope of relative imports module lookup rules summary relative imports in action pitfalls of package-relative importsmixed use python namespace packages namespace package semantics impacts on regular packagesoptional __init__ py namespace packages in action namespace package nesting files still have precedence over directories summary test your knowledgequiz test your knowledgeanswers advanced module topics module design concepts data hiding in modules minimizing from damage_x and __all__ enabling future language features__future__ mixed usage modes__name__ and __main__ unit tests with __name__ exampledual mode code currency symbolsunicode in action docstringsmodule documentation at work changing the module search path the as extension for import and from examplemodules are objects importing modules by name string running code strings direct callstwo options exampletransitive module reloads recursive reloader alternative codings module gotchas module name clashespackage and package-relative imports statement order matters in top-level code from copies names but doesn' link from can obscure the meaning of variables reload may not impact from imports reloadfromand interactive testing table of contents xix
551
summary test your knowledgequiz test your knowledgeanswers test your knowledgepart exercises part vi classes and oop oopthe big picture why use classesoop from , feet attribute inheritance search classes and instances method calls coding class trees operator overloading oop is about code reuse summary test your knowledgequiz test your knowledgeanswers class coding basics classes generate multiple instance objects class objects provide default behavior instance objects are concrete items first example classes are customized by inheritance second example classes are attributes in modules classes can intercept python operators third example why use operator overloadingthe world' simplest python class records revisitedclasses versus dictionaries summary test your knowledgequiz test your knowledgeanswers more realistic example step making instances coding constructors testing as you go xx table of contents
552
step adding behavior methods coding methods step operator overloading providing print displays step customizing behavior by subclassing coding subclasses augmenting methodsthe bad way augmenting methodsthe good way polymorphism in action inheritcustomizeand extend oopthe big idea step customizing constructorstoo oop is simpler than you may think other ways to combine classes step using introspection tools special class attributes generic display tool instance versus class attributes name considerations in tool classes our classesfinal form step (final)storing objects in database pickles and shelves storing objects on shelve database exploring shelves interactively updating objects on shelve future directions summary test your knowledgequiz test your knowledgeanswers class coding details the class statement general form example methods method example calling superclass constructors other method call possibilities inheritance attribute tree construction specializing inherited methods class interface techniques table of contents xxi
553
namespacesthe conclusion simple namesglobal unless assigned attribute namesobject namespaces the "zenof namespacesassignments classify names nested classesthe legb scopes rule revisited namespace dictionariesreview namespace linksa tree climber documentation strings revisited classes versus modules summary test your knowledgequiz test your knowledgeanswers operator overloading the basics constructors and expressions__init__ and __sub__ common operator overloading methods indexing and slicing__getitem__ and __setitem__ intercepting slices slicing and indexing in python but ' __index__ is not indexingindex iteration__getitem__ iterable objects__iter__ and __next__ user-defined iterables multiple iterators on one object coding alternative__iter__ plus yield membership__contains____iter__and __getitem__ attribute access__getattr__ and __setattr__ attribute reference attribute assignment and deletion other attribute management tools emulating privacy for instance attributespart string representation__repr__ and __str__ why two display methodsdisplay usage notes right-side and in-place uses__radd__ and __iadd__ right-side addition in-place addition call expressions__call__ function interfaces and callback-based code comparisons__lt____gt__and others the __cmp__ method in python xxii table of contents
554
boolean methods in python object destruction__del__ destructor usage notes summary test your knowledgequiz test your knowledgeanswers designing with classes python and oop polymorphism means interfacesnot call signatures oop and inheritance"is-arelationships oop and composition"has-arelationships stream processors revisited oop and delegation"wrapperproxy objects pseudoprivate class attributes name mangling overview why use pseudoprivate attributesmethods are objectsbound or unbound unbound methods are functions in bound methods and other callable objects classes are objectsgeneric object factories why factoriesmultiple inheritance"mix-inclasses coding mix-in display classes other design-related topics summary test your knowledgequiz test your knowledgeanswers advanced class topics extending built-in types extending types by embedding extending types by subclassing the "new styleclass model just how new is new-stylenew-style class changes attribute fetch for built-ins skips instances type model changes all classes derive from "objectdiamond inheritance change more on the mromethod resolution order examplemapping attributes to inheritance sources table of contents xxiii
555
slotsattribute declarations propertiesattribute accessors __getattribute__ and descriptorsattribute tools other class changes and extensions static and class methods why the special methodsstatic methods in and static method alternatives using static and class methods counting instances with static methods counting instances with class methods decorators and metaclassespart function decorator basics first look at user-defined function decorators first look at class decorators and metaclasses for more details the super built-in functionfor better or worsethe great super debate traditional superclass call formportablegeneral basic super usage and its tradeoffs the super upsidestree changes and dispatch runtime class changes and super cooperative multiple inheritance method dispatch the super summary class gotchas changing class attributes can have side effects changing mutable class attributes can have side effectstoo multiple inheritanceorder matters scopes in methods and classes miscellaneous class gotchas kiss revisited"overwrapping-itissummary test your knowledgequiz test your knowledgeanswers test your knowledgepart vi exercises part vii exceptions and tools exception basics why use exceptionsexception roles xxiv table of contents
556
default exception handler catching exceptions raising exceptions user-defined exceptions termination actions summary test your knowledgequiz test your knowledgeanswers exception coding details the try/except/else statement how try statements work try statement clauses the try else clause exampledefault behavior examplecatching built-in exceptions the try/finally statement examplecoding termination actions with try/finally unified try/except/finally unified try statement syntax combining finally and except by nesting unified try example the raise statement raising exceptions scopes and try except variables propagating exceptions with raise python exception chainingraise from the assert statement exampletrapping constraints (but not errors!with/as context managers basic usage the context management protocol multiple context managers in and later summary test your knowledgequiz test your knowledgeanswers exception objects exceptionsback to the future string exceptions are right outclass-based exceptions coding exceptions classes table of contents xxv
557
built-in exception classes built-in exception categories default printing and state custom print displays custom data and behavior providing exception details providing exception methods summary test your knowledgequiz test your knowledgeanswers designing with exceptions nesting exception handlers examplecontrol-flow nesting examplesyntactic nesting exception idioms breaking out of multiple nested loops"go toexceptions aren' always errors functions can signal conditions with raise closing files and server connections debugging with outer try statements running in-process tests more on sys exc_info displaying errors and tracebacks exception design tips and gotchas what should be wrapped catching too muchavoid empty except and exception catching too littleuse class-based categories core language summary the python toolset development tools for larger projects summary test your knowledgequiz test your knowledgeanswers test your knowledgepart vii exercises part viii advanced topics unicode and byte strings string changes in string basics xxvi table of contents
558
how python stores strings in memory python' string types text and binary files coding basic strings python string literals python string literals string type conversions coding unicode strings coding ascii text coding non-ascii text encoding and decoding non-ascii text other encoding schemes byte string literalsencoded text converting encodings coding unicode strings in python source file character set encoding declarations using bytes objects method calls sequence operations other ways to make bytes objects mixing string types using / bytearray objects bytearrays in action python string types summary using text and binary files text file basics text and binary modes in and type and content mismatches in using unicode files reading and writing unicode in handling the bom in unicode files in unicode filenames and streams other string tool changes in the re pattern-matching module the struct binary data module the pickle object serialization module xml parsing tools summary test your knowledgequiz test your knowledgeanswers table of contents xxvii
559
why manage attributesinserting code to run on attribute access properties the basics first example computed attributes coding properties with decorators descriptors the basics first example computed attributes using state information in descriptors how properties and descriptors relate __getattr__ and __getattribute__ the basics first example computed attributes __getattr__ and __getattribute__ compared management techniques compared intercepting built-in operation attributes exampleattribute validations using properties to validate using descriptors to validate using __getattr__ to validate using __getattribute__ to validate summary test your knowledgequiz test your knowledgeanswers decorators what' decoratormanaging calls and instances managing functions and classes using and defining decorators why decoratorsthe basics function decorators class decorators decorator nesting decorator arguments decorators manage functions and classestoo coding function decorators xxviii table of contents
560
decorator state retention options class blunders idecorating methods timing calls adding decorator arguments coding class decorators singleton classes tracing object interfaces class blunders iiretaining multiple instances decorators versus manager functions why decorators(revisitedmanaging functions and classes directly example"privateand "publicattributes implementing private attributes implementation details generalizing for public declarationstoo implementation details ii open issues python isn' about control examplevalidating function arguments the goal basic range-testing decorator for positional arguments generalizing for keywords and defaultstoo implementation details open issues decorator arguments versus function annotations other applicationstype testing (if you insist!summary test your knowledgequiz test your knowledgeanswers metaclasses to metaclass or not to metaclass increasing levels of "magica language of hooks the downside of "helperfunctions metaclasses versus class decoratorsround the metaclass model classes are instances of type metaclasses are subclasses of type class statement protocol declaring metaclasses declaration in table of contents xxix
561
metaclass dispatch in both and coding metaclasses basic metaclass customizing construction and initialization other metaclass coding techniques inheritance and instance metaclass versus superclass inheritancethe full story metaclass methods metaclass methods versus class methods operator overloading in metaclass methods exampleadding methods to classes manual augmentation metaclass-based augmentation metaclasses versus class decoratorsround exampleapplying decorators to methods tracing with decoration manually tracing with metaclasses and decorators applying any decorator to methods metaclasses versus class decoratorsround (and lastsummary test your knowledgequiz test your knowledgeanswers all good things the python paradox on "optionallanguage features against disquieting improvements complexity versus power simplicity versus elitism closing thoughts where to go from here encoreprint your own completion certificate part ix appendixes installation and configuration installing the python interpreter is python already presentwhere to get python installation steps xxx table of contents
562
python environment variables how to set configuration options python command-line arguments python windows launcher command lines for more help the python windows launcher the unix legacy the windows legacy introducing the new windows launcher windows launcher tutorial step using version directives in files step using command-line version switches step using and changing defaults pitfalls of the new windows launcher pitfall unrecognized unix !lines fail pitfall the launcher defaults to pitfall the new path extension option conclusionsa net win for windows python changes and this book major / differences differences -only extensions general remarks changes changes in libraries and tools migrating to fifth edition python changes changes in python changes in python changes in python fourth edition python changes changes in python changes in python and specific language removals in third edition python changes earlier and later python changes solutions to end-of-part exercises part igetting started part iitypes and operations part iiistatements and syntax table of contents xxxi
563
part vmodules and packages part viclasses and oop part viiexceptions and tools index xxxii table of contents
564
if you're standing in bookstore looking for the short story on this booktry thispython is powerful multiparadigm computer programming languageoptimized for programmer productivitycode readabilityand software quality this book provides comprehensive and in-depth introduction to the python language itself its goal is to help you master python fundamentals before moving on to apply them in your work like all its prior editionsthis book is designed to serve as singleall-inclusive learning resource for all python newcomerswhether they will be using python xpython xor both this edition has been brought up to date with python releases and and has been expanded substantially to reflect current practice in the python world this preface describes this book' goalsscopeand structure in more detail it' optional readingbut is designed to provide some orientation before you get started with the book at large this book' "ecosystempython is popular open source programming language used for both standalone programs and scripting applications in wide variety of domains it is freeportablepowerfuland is both relatively easy and remarkably fun to use programmers from every corner of the software industry have found python' focus on developer productivity and software quality to be strategic advantage in projects both large and small whether you are new to programming or are professional developerthis book is designed to bring you up to speed on the python language in ways that more limited approaches cannot after reading this bookyou should know enough about python to apply it in whatever application domains you choose to explore by designthis book is tutorial that emphasizes the core python language itselfrather than specific applications of it as suchthis book is intended to serve as the first in two-volume setxxxiii
565
programming pythonamong othersmoves on to show what you can do with python after you've learned it this division of labor is deliberate while application goals can vary per readerthe need for useful language fundamentals coverage does not applications-focused books such as programming python pick up where this book leaves offusing realistically scaled examples to explore python' role in common domains such as the webguissystemsdatabasesand text in additionthe book python pocket reference provides reference materials not included hereand it is designed to supplement this book because of this book' focus on foundationsthoughit is able to present python language fundamentals with more depth than many programmers see when first learning the language its bottom-up approach and self-contained didactic examples are designed to teach readers the entire language one step at time the core language skills you'll gain in the process will apply to every python software system you'll encounter--be it today' popular tools such as djangonumpyand app engineor others that may be part of both python' future and your programming career because it' based upon three-day python training class with quizzes and exercises throughoutthis book also serves as self-paced introduction to the language although its format lacks the live interaction of classit compensates in the extra depth and flexibility that only book can provide though there are many ways to use this booklinear readers will find it roughly equivalent to semester-long python class about this fifth edition the prior fourth edition of this book published in covered python versions and it addressed the many and sometimes incompatible changes introduced in the python line in general it also introduced new oop tutorialand new on advanced topics such as unicode textdecoratorsand metaclassesderived from both the live classes teach and evolution in python "best practice this fifth edition completed in is revision of the priorupdated to cover both python and the current latest releases in the and lines it incorporates and ' short-lived third edition covered python and its simpler--and shorter--single-line python world see in size and complexity in direct proportion to python' own growth per appendix cpython alone introduced additions and changes in the language that found their way into this bookand python continues this trend today' python programmer faces two incompatible linesthree major paradigmsa plethora of advanced toolsand blizzard of feature redundancy--most of which do not divide neatly between the and lines that' not as daunting as it may sound (many tools are variations on theme)but all are fair game in an inclusivecomprehensive python text xxxiv preface
566
all language changes introduced in each line since the prior edition was publishedand has been polished throughout to update and sharpen its presentation specificallypython coverage here has been updated to include features such as dictionary and set comprehensions that were formerly for onlybut have been back-ported for use in python coverage has been augmented for new yield and raise syntaxthe __pycache__ bytecode model namespace packagespydoc' all-browser modeunicode literal and storage changesand the new windows launcher shipped with assorted new or expanded coverage for jsontimeitpypyos popengeneratorsrecursionweak references__mro____iter__super__slots__metaclassesdescriptorsrandomsphinxand more has been addedalong with general increase in compatibility in both examples and narrative this edition also adds new conclusion as (on python' evolution)two new appendixes (on recent python changes and the new windows launcher)and one new (on benchmarkingan expanded version of the former code timing examplesee appendix for concise summary of python changes between the prior edition and this oneas well as links to their coverage in the book this appendix also summarizes initial differences between and in general that were first addressed in the prior editionthough somesuch as new-style classesspan versions and simply become mandated in (more on what the ' mean in momentper the last bullet in the preceding listthis edition has also experienced some growth because it gives fuller coverage to more advanced language features--which many of us have tried very hard to ignore as optional for the last decadebut which have now grown more common in python code as we'll seethese tools make python more powerfulbut also raise the bar for newcomersand may shift python' scope and definition because you might encounter any of thesethis book covers them head-oninstead of pretending they do not exist despite the updatesthis edition retains most of the structure and content of the prior editionand is still designed to be comprehensive learning resource for both the and python lines while it is primarily focused on users of python and -the latest in the line and the likely last in the line--its historical perspective also makes it relevant to older pythons that still see regular use today though it' impossible to predict the futurethis book stresses fundamentals that have been valid for nearly two decadesand will likely apply to future pythons too as usuali'll be posting python updates that impact this book at the book' website described ahead the "what' newdocuments in python' manuals set can also serve to fill in the gaps as python surely evolves after this book is published preface xxxv
567
because it bears heavily on this book' contenti need to say few more words about the python / story up front when the fourth edition of this book was written in python had just become available in two flavorsversion was the first in the line of an emerging and incompatible mutation of the language known generically as version retained backward compatibility with the vast body of existing python codeand was the latest in the line known collectively as while was largely the same languageit ran almost no code written for prior releases itimposed unicode model with broad consequences for stringsfilesand libraries elevated iterators and generators to more pervasive roleas part of fuller functional paradigm mandated new-style classeswhich merge with typesbut grow more powerful and complex changed many fundamental tools and librariesand replaced or removed others entirely the mutation of print from statement to function aloneaesthetically sound as it may bebroke nearly every python program ever written and strategic potential aside ' mandatory unicode and class models and ubiquitous generators made for different programming experience although many viewed python as both an improvement and the future of pythonpython was still very widely used and was to be supported in parallel with python for years to come the majority of python code in use was xand migration to seemed to be shaping up to be slow process the / story today as this fifth edition is being written in python has moved on to versions and but this / story is still largely unchanged in factpython is now dual-version worldwith many users running both and according to their software goals and dependencies and for many newcomersthe choice between and remains one of existing software versus the language' cutting edge although many major python packages have been ported to xmany others are still -only today to some observerspython is now seen as sandbox for exploring new ideaswhile is viewed as the tried-and-true pythonwhich doesn' have all of ' features but is still more pervasive others still see python as the futurea view that seems supported by current core developer planspython will continue to be supported but is to be the last xwhile is the latest in the line' continuing evolution xxxvi preface
568
python that offers stunning performance improvements--represent futureif not an outright faction all opinions asidealmost five years after its release has yet to supersede xor even match its user base as one metric is still downloaded more often than for windows at python org todaydespite the fact that this measure would be naturally skewed to new users and the most recent release such statistics are prone to changeof coursebut after five years are indicative of uptake nonetheless the existing software base still trumps ' language extensions for many moreoverbeing last in the line makes sort of de facto standardimmune to the constant pace of change in the line-- positive to those who seek stable baseand negative to those who seek growth and ongoing relevance personallyi think today' python world is large enough to accommodate both and xthey seem to satisfy different goals and appeal to different campsand there is precedence for this in other language families ( and ++for examplehave longstanding coexistencethough they may differ more than python and xmoreoverbecause they are so similarthe skills gained by learning either python line transfer almost entirely to the otherespecially if you're aided by dual-version resources like this book in factas long as you understand how they divergeit' often possible to write code that runs on both at the same timethis split presents substantial dilemma for both programmers and book authorswhich shows no signs of abating while it would be easier for book to pretend that python never existed and cover onlythis would not address the needs of the large python user base that exists today vast amount of existing code was written for python xand it won' be going away anytime soon and while some newcomers to the language can and should focus on python xanyone who must use code written in the past needs to keep one foot in the python world today since it may still be years before many third-party libraries and extensions are ported to python xthis fork might not be entirely temporary coverage for both and to address this dichotomy and to meet the needs of all potential readersthis book has been updated to cover both python and python and should apply to later releases in both the and lines it' intended for programmers using python xprogrammers using python xand programmers stuck somewhere between the two that isyou can use this book to learn either python line although is often emphasized differences and tools are also noted along the way for programmers using older code while the two versions are largely similarthey diverge in some important waysand 'll point these out as they crop up preface xxxvii
569
print statement so you can make sense of earlier codeand will often use portable printing techniques that run on both lines 'll also freely introduce new featuressuch as the nonlocal statement in and the string format method available as of and and will point out when such extensions are not present in older pythons by proxythis edition addresses other python version and releases as wellthough some older version code may not be able to run all the examples here although class decorators are available as of both python and for exampleyou cannot use them in an older python that did not yet have this feature againsee the change tables in appendix for summaries of recent and changes which python should useversion choice may be mandated by your organizationbut if you're new to python and learning on your ownyou may be wondering which version to install the answer here depends on your goals here are few suggestions on the choice when to choose xnew featuresevolution if you are learning python for the first time and don' need to use any existing codei encourage you to begin with python it cleans up some longstanding warts in the language and trims some dated cruftwhile retaining all the original core ideas and adding some nice new tools for example ' seamless unicode model and broader use of generators and functional techniques are seen by many users as assets many popular python libraries and tools are already available for python xor will be by the time you read these wordsespecially given the continual improvements in the line all new language evolution occurs in onlywhich adds features and keeps python relevantbut also makes language definition constantly moving target-- tradeoff inherent on the leading edge when to choose xexisting codestability if you'll be using system based on python xthe line may not be an option for you today howeveryou'll find that this book addresses your concernstooand will help if you migrate to in the future you'll also find that you're in large company every group taught in was using onlyand still regularly see useful python software in -only form moreoverunlike is no longer being changed--which is either an asset or liabilitydepending on whom you ask there' nothing wrong with using and writing codebut you may wish to keep tabs on and its ongoing evolution as you do python' future remains to be writtenand is largely up to its usersincluding you when to choose bothversion-neutral code probably the best news here is that python' fundamentals are the same in both its lines-- and differ in ways that many users will find minorand this book is designed to help you learn both in factas long as you understand their differencesit' often straightforward to write version-neutral code that runs on both xxxviii preface
570
migration and tips on writing code for both python lines and audiences regardless of which version or versions you choose to focus on firstyour skills will transfer directly to wherever your python work leads you about the xsthroughout this book" xand " xare used to refer collectively to all releases in these two lines for instance includes through and future releases means all from through (and presumably no othersmore specific releases are mentioned when topic applies to it only ( ' set literals and ' launcher and namespace packagesthis notation may occasionally be too broad --some features labeled here may not be present in early releases rarely used today--but it accommodates line that has already spanned years the label is more easily and accurately applied to this younger five-year-old line this book' prerequisites and effort it' impossible to give absolute prerequisites for this bookbecause its utility and value can depend as much on reader motivation as on reader background both true beginners and crusty programming veterans have used this book successfully in the past if you are motivated to learn pythonand willing to invest the time and focus it requiresthis text will probably work for you just how much time is required to learn pythonalthough this will vary per learnerthis book tends to work best when read some readers may use this book as an ondemand reference resourcebut most people seeking python mastery should expect to spend at least weeks and probably months going through the material heredepending on how closely they follow along with its examples as mentionedit' roughly equivalent to full-semester course on the python language itself that' the estimate for learning just python itself and the software skills required to use it well though this book may suffice for basic scripting goalsreaders hoping to pursue software development at large as career should expect to devote additional time after this book to large-scale project experienceand possibly to follow-up texts such as programming python the standard disclaimeri wrote this and another book mentioned earlierwhich work together as setlearning python for language fundamentalsprogramming python for applications basicsand python pocket reference as companion to the other two all three derive from ' original and broad programming python encourage you to explore the many python books available today ( stopped counting at at amazon com just now because there was no end in sightand this didn' include related subjects like djangomy own publisher has recently produced python-focused books on instrumentationdata miningapp enginenumeric analysisnatural language processingmongodbawsand more--specific domains you may wish to explore once you've mastered python language fundamentals here the python story today is far too rich for any one book to address alone preface xxxix
571
and software in generalare both challenging and rewarding enough to merit the effort implied by comprehensive books such as this here are few pointers on using this book for readers on both sides of the experience spectrumto experienced programmers you have an initial advantage and can move quickly through some earlier but you shouldn' skip the core ideasand may need to work at letting go of some baggage in general termsexposure to any programming or scripting before this book might be helpful because of the analogies it may provide on the other handi've also found that prior programming experience can be handicap due to expectations rooted in other languages (it' far too easy to spot the java or +programmers in classes by the first python code they write!using python well requires adopting its mindset by focusing on key core conceptsthis book is designed to help you learn to code python in python to true beginners you can learn python here tooas well as programming itselfbut you may need to work bit harderand may wish to supplement this text with gentler introductions if you don' consider yourself programmer alreadyyou will probably find this book useful toobut you'll want to be sure to proceed slowly and work through the examples and exercises along the way also keep in mind that this book will spend more time teaching python itself than programming basics if you find yourself lost herei encourage you to explore an introduction to programming in general before tackling this book python' website has links to many helpful resources for beginners formallythis book is designed to serve as first python text for newcomers of all kinds it may not be an ideal resource for someone who has never touched computer before (for instancewe're not going to spend any time exploring what computer is)but haven' made many assumptions about your programming background or education on the other handi won' insult readers by assuming they are "dummies,eitherwhatever that means--it' easy to do useful things in pythonand this book will show you how the text occasionally contrasts python with languages such as cc++javaand othersbut you can safely ignore these comparisons if you haven' used such languages in the past this book' structure to help orient youthis section provides quick rundown of the content and goals of the major parts of this book if you're anxious to get to ityou should feel free to skip xl preface
572
this large probably merits brief roadmap up front by designeach part covers major functional area of the languageand each part is composed of focusing on specific topic or aspect of the part' area in additioneach ends with quizzes and their answersand each part ends with larger exerciseswhose solutions show up in appendix practice mattersi strongly recommend that readers work through the quizzes and exercises in this bookand work along with its examples in general if you can in programmingthere' no substitute for practicing what you've read whether you do it with this book or project of your ownactual coding is crucial if you want the ideas presented here to stick overallthis book' presentation is bottom-up because python is too the examples and topics grow more challenging as we move along for instancepython' classes are largely just packages of functions that process built-in types once you've mastered built-in types and functionsclasses become relatively minor intellectual leap because each part builds on those preceding it this waymost readers will find linear reading makes the most sense here' preview of the book' main parts you'll find along the waypart we begin with general overview of python that answers commonly asked initial questions--why people use the languagewhat it' useful forand so on the first introduces the major ideas underlying the technology to give you some background context the rest of this part moves on to explore the ways that both python and programmers run programs the main goal here is to give you just enough information to be able to follow along with later examples and exercises part ii nextwe begin our tour of the python languagestudying python' major built-in object types and what you can do with them in depthnumberslistsdictionariesand so on you can get lot done with these tools aloneand they are at the heart of every python script this is the most substantial part of the book because we lay groundwork here for later we'll also explore dynamic typing and its references--keys to using python well--in this part part iii the next part moves on to introduce python' statements--the code you type to create and process objects in python it also presents python' general syntax model although this part focuses on syntaxit also introduces some related tools (such as the pydoc system)takes first look at iteration conceptsand explores coding alternatives preface xli
573
this part begins our look at python' higher-level program structure tools functions turn out to be simple way to package code for reuse and avoid code redundancy in this partwe will explore python' scoping rulesargument-passing techniquesthe sometimes-notorious lambdaand more we'll also revisit iterators from functional programming perspectiveintroduce user-defined generatorsand learn how to time python code to measure performance here part python modules let you organize statements and functions into larger componentsand this part illustrates how to createuseand reload modules we'll also look at some more advanced topics heresuch as module packagesmodule reloadingpackage-relative imports ' new namespace packagesand the __name__ variable part vi herewe explore python' object-oriented programming toolthe class--an optional but powerful way to structure code for customization and reusewhich almost naturally minimizes redundancy as you'll seeclasses mostly reuse ideas we will have covered by this point in the bookand oop in python is mostly about looking up names in linked objects with special first argument in functions as you'll also seeoop is optional in pythonbut most find python' oop to be much simpler than othersand it can shave development time substantiallyespecially for long-term strategic project development part vii we conclude the language fundamentals coverage in this text with look at python' exception handling model and statementsplus brief overview of development tools that will become more useful when you start writing larger programs (debugging and testing toolsfor instancealthough exceptions are fairly lightweight toolthis part appears after the discussion of classes because user-defined exceptions should now all be classes we also cover some more advanced topicssuch as context managershere part viii in the final partwe explore some advanced topicsunicode and byte stringsmanaged attribute tools like properties and descriptorsfunction and class decoratorsand metaclasses these are all optional readingbecause not all programmers need to understand the subjects they address on the other handreaders who must process internationalized text or binary dataor are responsible for developing apis for other programmers to useshould find something of interest in this part the examples here are also larger than most of those in this bookand can serve as self-study material part ix the book wraps up with set of four appendixes that give platform-specific tips for installing and using python on various computerspresent the new windows xlii preface
574
recent editions and give links to their coverage hereand provide solutions to the end-of-part exercises solutions to end-of-quizzes appear in the themselves see the table of contents for finer-grained look at this book' components what this book is not given its relatively large audience over the yearssome have inevitably expected this book to serve role outside its scope so now that 've told you what this book isi also want to be clear on what it isn'tthis book is tutorialnot reference this book covers the language itselfnot applicationsstandard librariesor thirdparty tools this book is comprehensive look at substantial topicnot watered-down overview because these points are key to this book' contenti want to say few more words about them up front it' not reference or guide to specific applications this book is language tutorialnot referenceand not an applications book this is by designtoday' python--with its built-in typesgeneratorsclosurescomprehensionsunicodedecoratorsand blend of proceduralobject-orientedand functional programming paradigms--makes the core language substantial topic all by itselfand prerequisite to all your future python workin whatever domains you pursue when you are ready for other resourcesthoughhere are few suggestions and remindersreference resources as implied by the preceding structural descriptionyou can use the index and table of contents to hunt for detailsbut there are no reference appendixes in this book if you are looking for python reference resources (and most readers probably will be very soon in their python careers) suggest the previously mentioned book that also wrote as companion to this one--python pocket reference--as well as other reference books you'll find with quick searchand the standard python reference manuals maintained at up to dateand available both on the web and on your computer after windows install applications and libraries as also discussed earlierthis book is not guide to specific applications such as the webguisor systems programming by proxythis includes the libraries and preface xliii
575
introduced here--including timeitshelvepicklestructjsonpdbosurllibrexmlrandompydoc and idle--they are not officially in this book' primary scope if you're looking for more coverage on such topics and are already proficient with pythoni recommend the follow-up book programming pythonamong others that book assumes this one as its prerequisitethoughso be sure you have firm grasp of the core language first especially in an engineering domain like softwareone must walk before one runs it' not the short story for people in hurry as you can tell from its sizethis book also doesn' skimp on the detailsit presents the full python languagenot brief look at simplified subset along the way it also covers software principles that are essential to writing good python code as mentionedthis is multiple-week or -month bookdesigned to impart the skill level you' acquire from full-term class on python this is also deliberate many of this book' readers don' need to acquire full-scale software development skillsof courseand some can absorb python in piecemeal fashion at the same timebecause any part of the language may be used in code you will encounterno part is truly optional for most programmers moreovereven casual scripters and hobbyists need to know basic principles of software development in order to code welland even to use precoded tools properly this book aims to address both of these needs--language and principles--in enough depth to be useful in the endthoughyou'll find that python' more advanced toolssuch as its object-oriented and functional programming supportare relatively easy to learn once you've mastered their prerequisites--and you willif you work through this book one at time it' as linear as python allows speaking of reading orderthis edition also tries hard to minimize forward referencesbut python ' changes make this impossible in some cases (in fact sometimes seems to assume you already know python while you're learning it!as handful of representative examplesprintingsortsthe string format methodand some dict calls rely on function keyword arguments dictionary key lists and testsand the list calls used around many toolsimply iteration concepts using exec to run code now assumes knowledge of file objects and interfaces coding new exceptions requires classes and oop fundamentals xliv preface
576
and descriptors python is still best learned as progression from simple to advancedand linear reading here still makes the most sense stillsome topics may require nonlinear jumps and random lookups to minimize thesethis book will point out forward dependencies when they occurand will ease their impacts as much as possible but if your time is tightthough depth is crucial to mastering pythonsome readers may have limited time if you are interested in starting out with quick python touri suggest and (and perhaps )-- short survey that will hopefully pique your interest in the more complete story told in the rest of the bookand which most readers will need in today' python software world in generalthis book is intentionally layered this way to make its material easier to absorb--with introductions followed by detailsso you can start with overviewsand dig deeper over time you don' need to read this book all at oncebut its gradual approach is designed to help you tackle its material eventually this book' programs in generalthis book has always strived to be agnostic about both python versions and platforms it' designed to be useful to all python users neverthelessbecause python changes over time and platforms tend to differ in pragmatic waysi need to describe the specific systems you'll see in action in most examples here python versions this fifth edition of this bookand all the program examples in itare based on python versions and in additionmany of its examples run under prior and releasesand notes about the history of language changes in earlier versions are mixed in along the way for users of older pythons because this text focuses on the core languagehoweveryou can be fairly sure that most of what it has to say won' change very much in future releases of pythonas noted earlier most of this book applies to earlier python versionstooexcept when it does notnaturallyif you try using extensions added after release you're usingall bets are off as rule of thumbthe latest python is the best python if you are able to upgrade because this book focuses on the core languagemost of it also applies to both jython and ironpythonthe javaand net-based python language implementationsas well as other python implementations such as stackless and pypy (described in such alternatives differ mostly in usage detailsnot language preface xlv
577
the examples in this book were run on windows and ultrabook, though python' portability makes this mostly moot pointespecially in this fundamentals-focused book you'll notice few windows-isms--including command-line promptsa handful of screenshotsinstall pointersand an appendix on the new windows launcher in --but this reflects the fact that most python newcomers will probably get started on this platformand these can be safely ignored by users of other operating systems also give few launching details for other platforms like linuxsuch as "#!line usebut as we'll see in and appendix bthe windows launcher makes even this more portable technique fetching this book' code source code for the book' examplesas well as exercise solutionscan be fetched as zip file from the book' website at the following addressthis site includes both all the code in this book as well as package usage instructionsso 'll defer to it for more details of coursethe examples work best in the context of their appearance in this bookand you'll need some background knowledge on running python programs in general to make use of them we'll study startup details in so please stay tuned for information on this front using this book' code the code in my python books is designed to teachand ' glad when it assists readers in that capacity 'reilly itself has an official policy regarding reusing the book' examples in generalwhich 've pasted into the rest of this section for referencethis book is here to help you get your job done in generalyou may use the code in this book in your programs and documentation you do not need to contact us for permission unless you're reproducing significant portion of the code for examplewriting program that uses several chunks of code from this book does not require permission selling or distributing cd-rom of examples from 'reilly books does require permission answering question by citing this book and quoting example code does not require permission incorporating significant amount of example code from this book into your product' documentation does require permission mostly under windows but it' irrelevant to this book at this writingpython installs on windows and runs in its desktop modewhich is essentially the same as windows without start button as write this (you may need to create shortcuts for former start button menu itemssupport for winrtmetro "appsis still pending see appendix for more details franklythe future of windows is unclear as type these wordsso this book will be as version-neutral as possible xlvi preface
578
authorpublisherand isbn for example"learning pythonfifth editionby mark lutz copyright mark lutz- - if you feel your use of code examples falls outside fair use or the permission given abovefeel free to contact us at permissions@oreilly com font conventions this book' mechanics will make more sense once you start reading itof coursebut as referencethis book uses the following typographical conventionsitalic used for email addressesurlsfilenamespathnamesand emphasizing new terms when they are first introduced constant width used for program codethe contents of files and the output from commandsand to designate modulesmethodsstatementsand system commands constant width bold used in code sections to show commands or text that would be typed by the userandoccasionallyto highlight portions of code constant width italic used for replaceables and some comments in code sections indicates tipsuggestionor general note relating to the nearby text indicates warning or caution relating to the nearby text you'll also find occasional sidebars (delimited by boxesand footnotes (at page endthroughoutwhich are often optional readingbut provide additional context on the topics being presented the sidebars in "why you will caresliceson page for exampleoften give example use cases for the subjects being explored book updates and resources improvements happen (and so do mis^ ^ ^ typosupdatessupplementsand corrections ( erratafor this book will be maintained on the weband may be suggested at either the publisher' website or by email here are the main coordinatespreface xlvii
579
this site will maintain this edition' official list of book errataand chronicle specific patches applied to the text in reprints it' also the official site for the book' examples as described earlier author' sitethis site will be used to post more general updates related to this text or python itself-- hedge against future changeswhich should be considered sort of virtual appendix to this book my publisher also has an email address for comments and technical questions about this bookbookquestions@oreilly com for more information about my publisher' booksconferencesresource centersand the 'reilly networksee its general websitefor more on my bookssee my own book support sitealso be sure to search the web if any of the preceding links become invalid over timeif could become more clairvoyanti wouldbut the web changes faster than published books acknowledgments as write this fifth edition of this book in it' difficult to not be somewhat retrospective have now been using and promoting python for yearswriting books about it for and teaching live classes on it for despite the passage of timei' still regularly amazed at how successful python has been--in ways that most of us could not possibly have imagined in the early so at the risk of sounding like hopelessly self-absorbed authori hope you'll pardon few closing words of history and gratitude here the backstory my own python history predates both python and the web (and goes back to time when an install meant fetching email messagesconcatenatingdecodingand hoping it all somehow workedwhen first discovered python as frustrated +software developer in had no idea what an impact it would have on the next two decades of my life two years after writing the first edition of programming python in for python began traveling around the country and world teaching python to beginners and experts since finishing the first edition of learning python in xlviii preface
580
phenomenal growth in popularity here' the damage so far 've now written python books ( of thisand of two others)which have together sold some , units by my data 've also been teaching python for over decade and halfhave taught some python training sessions in the europecanadaand mexicoand have met roughly , students along the way besides propelling me toward frequent flyer utopiathese classes helped me refine this text and my other python books teaching honed the booksand vice versawith the net result that my books closely parallel what happens in my classesand can serve as viable alternative to them as for python itselfin recent years it has grown to become one of the top to most widely used programming languages in the world (depending on which source you cite and when you cite itbecause we'll be exploring python' status in the first of this booki'll defer the rest of this story until then python thanks because teaching teaches teachers to teachthis book owes much to my live classes ' like to thank all the students who have participated in my courses during the last years along with changes in python itselfyour feedback played major role in shaping this textthere' nothing quite as instructive as watching , people repeat the same beginner mistakes live and in personthis book' recent editions owe their trainingbased changes primarily to recent classesthough every class held since has in some way helped refine this book ' like to thank clients who hosted classes in dublinmexico citybarcelonalondonedmontonand puerto ricosuch experiences have been one of my career' most lasting rewards because writing teaches writers to writethis book also owes much to its audience want to thank the countless readers who took time to offer suggestions over the last yearsboth online and in person your feedback has also been vital to this book' evolution and substantial factor in its successa benefit that seems inherent in the open source world reader comments have run the gamut from "you should be banned from writing booksto "god bless you for writing this book"if consensus is possible in such matters it probably lies somewhere between these twothough to borrow line from tolkienthe book is still too short ' also like to express my gratitude to everyone who played part in this book' production to all those who have helped make this book solid product over the years --including its editorsformattersmarketerstechnical reviewersand more and to 'reilly for giving me chance to work on book projectsit' been net fun (and only feels little like the movie groundhog dayadditional thanks is due to the entire python communitylike most open source systemspython is the product of many unsung efforts it' been my privilege to watch preface xlix
581
deployed in some fashion by almost every organization writing software technical disagreements asidethat' been an exciting endeavor to be part of also want to thank my original editor at 'reillythe late frank willison this book was largely frank' idea he had profound impact on both my career and the success of python when it was newa legacy that remember each time ' tempted to misuse the word "only personal thanks finallya few more personal notes of thanks to the late carl saganfor inspiring an -year-old kid from wisconsin to my motherfor courage to my siblingsfor the truths to be found in museum peanuts to the book the shallowsfor much-needed wakeup call to my son michael and daughters samantha and roxannefor who you are ' not quite sure when you grew upbut ' proud of how you didand look forward to seeing where life takes you next and to my wife verafor patienceproofingdiet cokesand pretzels ' glad finally found you don' know what the next years holdbut do know that hope to spend all of them holding you --mark lutzamongst the larchspring preface
582
getting started
583
python & session if you've bought this bookyou may already know what python is and why it' an important tool to learn if you don'tyou probably won' be sold on python until you've learned the language by reading the rest of this book and have done project or two but before we jump into detailsthis first of this book will briefly introduce some of the main reasons behind python' popularity to begin sculpting definition of pythonthis takes the form of question-and-answer sessionwhich poses some of the most common questions asked by beginners why do people use pythonbecause there are many programming languages available todaythis is the usual first question of newcomers given that there are roughly million python users out there at the momentthere really is no way to answer this question with complete accuracythe choice of development tools is sometimes based on unique constraints or personal preference but after teaching python to roughly groups and over , students during the last yearsi have seen some common themes emerge the primary factors cited by python users seem to be thesesoftware quality for manypython' focus on readabilitycoherenceand software quality in general sets it apart from other tools in the scripting world python code is designed to be readableand hence reusable and maintainable--much more so than traditional scripting languages the uniformity of python code makes it easy to understandeven if you did not write it in additionpython has deep support for more advanced software reuse mechanismssuch as object-oriented (ooand function programming developer productivity python boosts developer productivity many times beyond compiled or statically typed languages such as cc++and java python code is typically one-third to
584
less to debugand less to maintain after the fact python programs also run immediatelywithout the lengthy compile and link steps required by some other toolsfurther boosting programmer speed program portability most python programs run unchanged on all major computer platforms porting python code between linux and windowsfor exampleis usually just matter of copying script' code between machines moreoverpython offers multiple options for coding portable graphical user interfacesdatabase access programswebbased systemsand more even operating system interfacesincluding program launches and directory processingare as portable in python as they can possibly be support libraries python comes with large collection of prebuilt and portable functionalityknown as the standard library this library supports an array of application-level programming tasksfrom text pattern matching to network scripting in additionpython can be extended with both homegrown libraries and vast collection of third-party application support software python' third-party domain offers tools for website constructionnumeric programmingserial port accessgame developmentand much more (see ahead for samplingthe numpy extensionfor instancehas been described as free and more powerful equivalent to the matlab numeric programming system component integration python scripts can easily communicate with other parts of an applicationusing variety of integration mechanisms such integrations allow python to be used as product customization and extension tool todaypython code can invoke and +librariescan be called from and +programscan integrate with java and net componentscan communicate over frameworks such as com and silverlightcan interface with devices over serial portsand can interact over networks with interfaces like soapxml-rpcand corba it is not standalone tool enjoyment because of python' ease of use and built-in toolsetit can make the act of programming more pleasure than chore although this may be an intangible benefitits effect on productivity is an important asset of these factorsthe first two (quality and productivityare probably the most compelling benefits to most python usersand merit fuller description software quality by designpython implements deliberately simple and readable syntax and highly coherent programming model as slogan at past python conference atteststhe net result is that python seems to "fit your brain"--that isfeatures of the language interact python & session
585
this makes the language easier to learnunderstandand remember in practicepython programmers do not need to constantly refer to manuals when reading or writing codeit' consistently designed system that many find yields surprisingly uniform code by philosophypython adopts somewhat minimalist approach this means that although there are usually multiple ways to accomplish coding taskthere is usually just one obvious waya few less obvious alternativesand small set of coherent interactions everywhere in the language moreoverpython doesn' make arbitrary decisions for youwhen interactions are ambiguousexplicit intervention is preferred over "magic in the python way of thinkingexplicit is better than implicitand simple is better than complex beyond such design themespython includes tools such as modules and oop that naturally promote code reusability and because python is focused on qualityso toonaturallyare python programmers developer productivity during the great internet boom of the mid-to-late sit was difficult to find enough programmers to implement software projectsdevelopers were asked to implement systems as fast as the internet evolved in later eras of layoffs and economic recessionthe picture shifted programming staffs were often asked to accomplish the same tasks with even fewer people in both of these scenariospython has shined as tool that allows programmers to get more done with less effort it is deliberately optimized for speed of development--its simple syntaxdynamic typinglack of compile stepsand built-in toolset allow programmers to develop programs in fraction of the time needed when using some other tools the net effect is that python typically boosts developer productivity many times beyond the levels supported by traditional languages that' good news in both boom and bust timesand everywhere the software industry goes in between is python "scripting language"python is general-purpose programming language that is often applied in scripting roles it is commonly defined as an object-oriented scripting language-- definition that blends support for oop with an overall orientation toward scripting roles if pressed for one-lineri' say that python is probably better known as general-purpose pro for more complete look at the python philosophytype the command import this at any python interactive prompt (you'll see how in this invokes an "easter egghidden in python-- collection of design principles underlying python that permeate both the language and its user community among themthe acronym eibti is now fashionable jargon for the "explicit is better than implicitrule these principles are not religionbut are close enough to qualify as python motto and creedwhich we'll be quoting from often in this book is python "scripting language"
586
statement that captures the richness and scope of today' python stillthe term "scriptingseems to have stuck to python like glueperhaps as contrast with larger programming effort required by some other tools for examplepeople often use the word "scriptinstead of "programto describe python code file in keeping with this traditionthis book uses the terms "scriptand "programinterchangeablywith slight preference for "scriptto describe simpler top-level file and "programto refer to more sophisticated multifile application because the term "scripting languagehas so many different meanings to different observersthoughsome would prefer that it not be applied to python at all in factpeople tend to make three very different associationssome of which are more useful than otherswhen they hear python labeled as suchshell tools sometimes when people hear python described as scripting languagethey think it means that python is tool for coding operating-system-oriented scripts such programs are often launched from console command lines and perform tasks such as processing text files and launching other programs python programs can and do serve such rolesbut this is just one of dozens of common python application domains it is not just better shell-script language control language to othersscripting refers to "gluelayer used to control and direct ( scriptother application components python programs are indeed often deployed in the context of larger applications for instanceto test hardware devicespython programs may call out to components that give low-level access to device similarlyprograms may run bits of python code at strategic points to support end-user product customization without the need to ship and recompile the entire system' source code python' simplicity makes it naturally flexible control tool technicallythoughthis is also just common python rolemany (perhaps mostpython programmers code standalone scripts without ever using or knowing about any integrated components it is not just control language ease of use probably the best way to think of the term "scripting languageis that it refers to simple language used for quickly coding tasks this is especially true when the term is applied to pythonwhich allows much faster program development than compiled languages like +its rapid development cycle fosters an exploratoryincremental mode of programming that has to be experienced to be appreciated don' be fooledthough--python is not just for simple tasks ratherit makes tasks simple by its ease of use and flexibility python has simple feature setbut it allows programs to scale up in sophistication as needed because of thatit is commonly used for quick tactical tasks and longer-term strategic development python & session
587
term "scriptingis probably best used to describe the rapid and flexible mode of development that python supportsrather than particular application domain okbut what' the downsideafter using it for yearswriting about it for and teaching it for 've found that the only significant universal downside to python is thatas currently implementedits execution speed may not always be as fast as that of fully compiled and lower-level languages such as and +though relatively rare todayfor some tasks you may still occasionally need to get "closer to the ironby using lower-level languages such as these that are more directly mapped to the underlying hardware architecture we'll talk about implementation concepts in detail later in this book in shortthe standard implementations of python today compile ( translatesource code statements to an intermediate format known as byte code and then interpret the byte code byte code provides portabilityas it is platform-independent format howeverbecause python is not normally compiled all the way down to binary machine code ( instructions for an intel chip)some programs will run more slowly in python than in fully compiled language like the pypy system discussed in the next can achieve to speedup on some code by compiling further as your program runsbut it' separatealternative implementation whether you will ever care about the execution speed difference depends on what kinds of programs you write python has been optimized numerous timesand python code runs fast enough by itself in most application domains furthermorewhenever you do something "realin python scriptlike processing file or constructing graphical user interface (gui)your program will actually run at speedsince such tasks are immediately dispatched to compiled code inside the python interpreter more fundamentallypython' speed-of-development gain is often far more important than any speed-of-execution lossespecially given modern computer speeds even at today' cpu speedsthoughthere still are some domains that do require optimal execution speeds numeric programming and animationfor exampleoften need at least their core number-crunching components to run at speed (or betterif you work in such domainyou can still use python--simply split off the parts of the application that require optimal speed into compiled extensionsand link those into your system for use in python scripts we won' talk about extensions much in this textbut this is really just an instance of the python-as-control-language role we discussed earlier prime example of this dual language strategy is the numpy numeric programming extension for pythonby combining compiled and optimized numeric extension libraries with the python languagenumpy turns python into numeric programming tool that is simultaneously efficient and easy to use when neededsuch extensions provide powerful optimization tool okbut what' the downside
588
mentioned that execution speed is the only major downside to python that' indeed the case for most python usersand especially for newcomers most people find python to be easy to learn and fun to useespecially when compared with its contemporaries like javac#and +in the interest of full disclosurethoughi should also note up front some more abstract tradeoffs 've observed in my two decades in the python world --both as an educator and developer as an educatori've sometimes found the rate of change in python and its libraries to be negativeand have on occasion lamented its growth over the years this is partly because trainers and book authors live on the front lines of such things--it' been my job to teach the language despite its constant changea task at times akin to chronicling the herding of catsstillit' broadly shared concern as we'll see in this bookpython' original "keep it simplemotif is today often subsumed by trend toward more sophisticated solutions at the expense of the learning curve of newcomers this book' size is indirect evidence of this trend on the other handby most measures python is still much simpler than its alternativesand perhaps only as complex as it needs to be given the many roles it serves today its overall coherence and open nature remain compelling features to most moreovernot everyone needs to stay up to date with the cutting edge--as python ' ongoing popularity clearly shows as developeri also at times question the tradeoffs inherent in python' "batteries includedapproach to development its emphasis on prebuilt tools can add dependencies (what if battery you use is changedbrokenor deprecated?)and encourage special-case solutions over general principles that may serve users better in the long run (how can you evaluate or use tool well if you don' understand its purpose?we'll see examples of both of these concerns in this book for typical usersand especially for hobbyists and beginnerspython' toolset approach is major asset but you shouldn' be surprised when you outgrow precoded toolsand can benefit from the sorts of skills this book aims to impart orto paraphrase proverbgive people tooland they'll code for dayteach them how to build toolsand they'll code for lifetime this book' job is more the latter than the former as mentioned elsewhere in this both python and its toolbox model are also susceptible to downsides common to open source projects in general--the potential triumph of the personal preference of the few over common usage of the manyand the occasional appearance of anarchy and even elitism--though these tend to be most grievous on the leading edge of new releases we'll return to some of these tradeoffs at the end of the bookafter you've learned python well enough to draw your own conclusions as an open source systemwhat python "isis up to its users to define in the endpython is more popular today than everand its growth shows no signs of abating to somethat may be more telling metric than individual opinionsboth pro and con python & session
589
at this writingthe best estimate anyone can seem to make of the size of the python user base is that there are roughly million python users around the world today (plus or minus fewthis estimate is based on various statisticslike download ratesweb statisticsand developer surveys because python is open sourcea more exact count is difficult--there are no license registrations to tally moreoverpython is automatically included with linux distributionsmacintosh computersand wide range of products and hardwarefurther clouding the user-base picture in generalthoughpython enjoys large user base and very active developer community it is generally considered to be in the top or top most widely used programming languages in the world today (its exact ranking varies per source and datebecause python has been around for over two decades and has been widely usedit is also very stable and robust besides being leveraged by individual userspython is also being applied in real revenuegenerating products by real companies for instanceamong the generally known python user basegoogle makes extensive use of python in its web search systems the popular youtube video sharing service is largely written in python the dropbox storage service codes both its server and desktop client software primarily in python the raspberry pi single-board computer promotes python as its educational language eve onlinea massively multiplayer online game (mmogby ccp gamesuses python broadly the widespread bittorrent peer-to-peer file sharing system began its life as python program industrial light magicpixarand others use python in the production of animated movies esri uses python as an end-user customization tool for its popular gis mapping products google' app engine web development framework uses python as an application language the ironport email server product uses more than million lines of python code to do its job mayaa powerful integrated modeling and animation systemprovides python scripting api the nsa uses python for cryptography and intelligence analysis irobot uses python to develop commercial and military robotic devices who uses python today
590
python the one laptop per child (olpcproject built its user interface and activity model in python netflix and yelp have both documented the role of python in their software infrastructures intelciscohewlett-packardseagatequalcommand ibm use python for hardware testing jpmorgan chaseubsgetcoand citadel apply python to financial market forecasting nasalos alamosfermilabjpland others use python for scientific programming tasks and so on--though this list is representativea full accounting is beyond this book' scopeand is almost guaranteed to change over time for an up-to-date sampling of additional python usersapplicationsand softwaretry the following pages currently at python' site and wikipediaas well as search in your favorite web browsersuccess storiesapplication domainsuser quoteswikipedia pageprobably the only common thread among the companies using python today is that python is used all over the mapin terms of application domains its general-purpose nature makes it applicable to almost all fieldsnot just one in factit' safe to say that virtually every substantial organization writing software is using pythonwhether for short-term tactical taskssuch as testing and administrationor for long-term strategic product development python has proven to work well in both modes what can do with pythonin addition to being well-designed programming languagepython is useful for accomplishing real-world tasks--the sorts of things developers do day in and day out it' commonly used in variety of domainsas tool for scripting other components and implementing standalone programs in factas general-purpose languagepython' roles are virtually unlimitedyou can use it for everything from website development and gaming to robotics and spacecraft control howeverthe most common python roles currently seem to fall into few broad categories the next few sections describe some of python' most common applications todayas well as tools used in each domain we won' be able to explore the tools python & session
591
mentioned here in any depth--if you are interested in any of these topicssee the python website or other resources for more details systems programming python' built-in interfaces to operating-system services make it ideal for writing portablemaintainable system-administration tools and utilities (sometimes called shell toolspython programs can search files and directory treeslaunch other programsdo parallel processing with processes and threadsand so on python' standard library comes with posix bindings and support for all the usual os toolsenvironment variablesfilessocketspipesprocessesmultiple threadsregular expression pattern matchingcommand-line argumentsstandard stream interfacesshell-command launchersfilename expansionzip file utilitiesxml and json parserscsv file handlersand more in additionthe bulk of python' system interfaces are designed to be portablefor examplea script that copies directory trees typically runs unchanged on all major python platforms the stackless python implementationdescribed in and used by eve onlinealso offers advanced solutions to multiprocessing requirements guis python' simplicity and rapid turnaround also make it good match for graphical user interface programming on the desktop python comes with standard object-oriented interface to the tk gui api called tkinter (tkinter in xthat allows python programs to implement portable guis with native look and feel python/tkinter guis run unchanged on microsoft windowsx windows (on unix and linux)and the mac os (both classic and os xa free extension packagepmwadds advanced widgets to the tkinter toolkit in additionthe wxpython gui apibased on +libraryoffers an alternative toolkit for constructing portable guis in python higher-level toolkits such as dabo are built on top of base apis such as wxpython and tkinter with the proper libraryyou can also use gui support in other toolkits in pythonsuch as qt with pyqtgtk with pygtkmfc with pywin net with ironpythonand swing with jython (the java version of pythondescribed in or jpype for applications that run in web browsers or have simple interface requirementsboth jython and python web frameworks and server-side cgi scriptsdescribed in the next sectionprovide additional user interface options internet scripting python comes with standard internet modules that allow python programs to perform wide variety of networking tasksin client and server modes scripts can communicate over socketsextract form information sent to server-side cgi scriptstransfer files by ftpparse and generate xml and json documentssendreceivecomposeand parse what can do with python
592
over xml-rpcsoapand telnetand more python' libraries make these tasks remarkably simple in additiona large collection of third-party tools are available on the web for doing internet programming in python for instancethe htmlgen system generates html files from python class-based descriptionsthe mod_python package runs python efficiently within the apache web server and supports server-side templating with its python server pagesand the jython system provides for seamless python/java integration and supports coding of server-side applets that run on clients in additionfull-blown web development framework packages for pythonsuch as djangoturbogearsweb pypylonszopeand webwaresupport quick construction of full-featured and production-quality websites with python many of these include features such as object-relational mappersa model/view/controller architectureserver-side scripting and templatingand ajax supportto provide complete and enterprise-level web development solutions more recentlypython has expanded into rich internet applications (rias)with tools such as silverlight in ironpythonand pyjs ( pyjamasand its python-to-javascript compilerajax frameworkand widget set python also has moved into cloud computingwith app engineand others described in the database section ahead where the web leadspython quickly follows component integration we discussed the component integration role earlier when describing python as control language python' ability to be extended by and embedded in and +systems makes it useful as flexible glue language for scripting the behavior of other systems and components for instanceintegrating library into python enables python to test and launch the library' componentsand embedding python in product enables onsite customizations to be coded without having to recompile the entire product (or ship its source code at alltools such as the swig and sip code generators can automate much of the work needed to link compiled components into python for use in scriptsand the cython system allows coders to mix python and -like code larger frameworkssuch as python' com support on windowsthe jython java-based implementationand the ironpython net-based implementation provide alternative ways to script components on windowsfor examplepython scripts can use frameworks to script word and excelaccess silverlightand much more database programming for traditional database demandsthere are python interfaces to all commonly used relational database systems--sybaseoracleinformixodbcmysqlpostgresql python & session
593
of underlying database systems for instancebecause the vendor interfaces implement the portable apia script written to work with the free mysql system will work largely unchanged on other systems (such as oracle)all you generally have to do is replace the underlying vendor interface the in-process sqlite embedded sql database engine is standard part of python itself since supporting both prototyping and basic program storage needs in the non-sql departmentpython' standard pickle module provides simple object persistence system--it allows programs to easily save and restore entire python objects to files and file-like objects on the webyou'll also find third-party open source systems named zodb and durus that provide complete object-oriented database systems for python scriptsotherssuch as sqlobject and sqlalchemythat implement object relational mappers (orms)which graft python' class model onto relational tablesand pymongoan interface to mongodba high-performancenon-sqlopen source json-style document databasewhich stores data in structures very similar to python' own lists and dictionariesand whose text may be parsed and created with python' own standard library json module still other systems offer more specialized ways to store dataincluding the datastore in google' app enginewhich models data with python classes and provides extensive scalabilityas well as additional emerging cloud storage options such as azurepicloudopenstackand stackato rapid prototyping to python programscomponents written in python and look the same because of thisit' possible to prototype systems in python initiallyand then move selected components to compiled language such as or +for delivery unlike some prototyping toolspython doesn' require complete rewrite once the prototype has solidified parts of the system that don' require the efficiency of language such as +can remain coded in python for ease of maintenance and use numeric and scientific programming python is also heavily used in numeric programming-- domain that would not traditionally have been considered to be in the scope of scripting languagesbut has grown to become one of python' most compelling use cases prominent herethe numpy high-performance numeric programming extension for python mentioned earlier includes such advanced tools as an array objectinterfaces to standard mathematical librariesand much more by integrating python with numeric routines coded in compiled language for speednumpy turns python into sophisticated yet easy-to-use numeric programming tool that can often replace existing code written in traditional compiled languages such as fortran or +what can do with python
594
provide additional libraries of scientific programming tools and use numpy as core component the pypy implementation of python (discussed in has also gained traction in the numeric domainin part because heavily algorithmic code of the sort that' common in this domain can run dramatically faster in pypy--often to quicker and moregamingimagesdata miningrobotsexcel python is commonly applied in more domains than can be covered here for exampleyou'll find tools that allow you to use python to dogame programming and multimedia with pygamecgkitpygletpysoypanda dand others serial port communication on windowslinuxand more with the pyserial extension image processing with pil and its newer pillow forkpyopenglblendermayaand more robot control programming with the pyro toolkit natural language analysis with the nltk package instrumentation on the raspberry pi and arduino boards mobile computing with ports of python to the google android and apple ios platforms excel spreadsheet function and macro programming with the pyxll or datanitro add-ins media file content and metadata tag processing with pymediaid pil/pillowand more artificial intelligence with the pybrain neural net library and the milk machine learning toolkit expert system programming with pyclipspykepyrologand pydatalog network monitoring with zenosswritten in and customized with python python-scripted design and modeling with pythoncadpythonoccfreecadand others document processing and generation with reportlabsphinxcheetahpypdfand so on data visualization with mayavimatplotlibvtkvpythonand more xml parsing with the xml library packagethe xmlrpclib moduleand third-party extensions json and csv file processing with the json and csv modules python & session
595
code you can even play solitaire with the pysolfc program and of courseyou can always code custom python scripts in less buzzword-laden domains to perform day-to-day system administrationprocess your emailmanage your document and media librariesand so on you'll find links to the support in many fields at the pypi websiteand via web searches (search google or though of broad practical usemany of these specific domains are largely just instances of python' component integration role in action again adding it as frontend to libraries of components written in compiled language such as makes python useful for scripting in wide variety of domains as general-purpose language that supports integrationpython is widely applicable how is python developed and supportedas popular open source systempython enjoys large and active development community that responds to issues and develops enhancements with speed that many commercial software developers might find remarkable python developers coordinate work online with source-control system changes are developed per formal protocolwhich includes writing pep (python enhancement proposalor other documentand extensions to python' regression testing system in factmodifying python today is roughly as involved as changing commercial software-- far cry from python' early dayswhen an email to its creator would sufficebut good thing given its large user base today the psf (python software foundation) formal nonprofit grouporganizes conferences and deals with intellectual property issues numerous python conferences are held around the worldo'reilly' oscon and the psf' pycon are the largest the former of these addresses multiple open source projectsand the latter is python-only event that has experienced strong growth in recent years pycon and reached , attendees eachin factpycon had to cap its limit at this level after surprise sell-out in (and managed to grab wide attention on both technical and nontechnical grounds that won' chronicle hereearlier years often saw attendance double --from attendees in to over , in for example--indicative of python' growth in generaland impressive to those who remember early conferences whose attendees could largely be served around single restaurant table open source tradeoffs having said thatit' important to note that while python enjoys vigorous development communitythis comes with inherent tradeoffs open source software can also appear chaotic and even resemble anarchy at timesand may not always be as smoothly implemented as the prior paragraphs might imply some changes may still manage to how is python developed and supported
596
process controls (python for instancecame with broken console input function on windowsmoreoveropen source projects exchange commercial interests for the personal preferences of current set of developerswhich may or may not be the same as yours-you are not held hostage by companybut you are at the mercy of those with spare time to change the system the net effect is that open source software evolution is often driven by the fewbut imposed on the many in practicethoughthese tradeoffs impact those on the "bleedingedge of new releases much more than those using established versions of the systemincluding prior releases in both python and if you kept using classic classes in python xfor exampleyou were largely immune to the explosion of class functionality and change in new-style classes that occurred in the early-to-mid though these become mandatory in (along with much more)many users today still happily skirt the issue what are python' technical strengthsnaturallythis is developer' question if you don' already have programming backgroundthe language in the next few sections may be bit baffling--don' worrywe'll explore all of these terms in more detail as we proceed through this book for developersthoughhere is quick introduction to some of python' top technical features it' object-oriented and functional python is an object-oriented languagefrom the ground up its class model supports advanced notions such as polymorphismoperator overloadingand multiple inheritanceyetin the context of python' simple syntax and typingoop is remarkably easy to apply in factif you don' understand these termsyou'll find they are much easier to learn with python than with just about any other oop language available besides serving as powerful code structuring and reuse devicepython' oop nature makes it ideal as scripting tool for other object-oriented systems languages for examplewith the appropriate glue codepython programs can subclass (specializeclasses implemented in ++javaand cof equal significanceoop is an option in pythonyou can go far without having to become an object guru all at once much like ++python supports both procedural and object-oriented programming modes its object-oriented tools can be applied if and when constraints allow this is especially useful in tactical development modeswhich preclude design phases in addition to its original procedural (statement-basedand object-oriented (classbasedparadigmspython in recent years has acquired built-in support for functional python & session
597
these can serve as both complement and alternative to its oop tools it' free python is completely free to use and distribute as with other open source softwaresuch as tclperllinuxand apacheyou can fetch the entire python system' source code for free on the internet there are no restrictions on copying itembedding it in your systemsor shipping it with your products in factyou can even sell python' source codeif you are so inclined but don' get the wrong idea"freedoesn' mean "unsupported on the contrarythe python online community responds to user queries with speed that most commercial software help desks would do well to try to emulate moreoverbecause python comes with complete source codeit empowers developersleading to the creation of large team of implementation experts although studying or changing programming language' implementation isn' everyone' idea of funit' comforting to know that you can do so if you need to you're not dependent on the whims of commercial vendorbecause the ultimate documentation--source code--is at your disposal as last resort as mentioned earlierpython development is performed by community that largely coordinates its efforts over the internet it consists of python' original creator--guido van rossumthe officially anointed benevolent dictator for life (bdflof python-plus supporting cast of thousands language changes must follow formal enhancement procedure and be scrutinized by both other developers and the bdfl this tends to make python more conservative with changes than some other languages and systems while the python / split broke with this tradition soundly and deliberatelyit still holds generally true within each python line it' portable the standard implementation of python is written in portable ansi cand it compiles and runs on virtually every major platform currently in use for examplepython programs run today on everything from pdas to supercomputers as partial listpython is available onlinux and unix systems microsoft windows (all modern flavorsmac os (both os and classicbeosos/ vmsand qnx real-time systems such as vxworks cray supercomputers and ibm mainframes what are python' technical strengths
598
cell phones running symbian osand windows mobile gaming consoles and ipods tablets and smartphones running google' android and apple' ios and more like the language interpreter itselfthe standard library modules that ship with python are implemented to be as portable across platform boundaries as possible furtherpython programs are automatically compiled to portable byte codewhich runs the same on any platform with compatible version of python installed (more on this in the next what that means is that python programs using the core language and standard libraries run the same on linuxwindowsand most other systems with python interpreter most python ports also contain platform-specific extensions ( com support on windows)but the core python language and libraries work the same everywhere as mentioned earlierpython also includes an interface to the tk gui toolkit called tkinter (tkinter in )which allows python programs to implement full-featured graphical user interfaces that run on all major gui desktop platforms without program changes it' powerful from features perspectivepython is something of hybrid its toolset places it between traditional scripting languages (such as tclschemeand perland systems development languages (such as cc++and javapython provides all the simplicity and ease of use of scripting languagealong with more advanced software-engineering tools typically found in compiled languages unlike some scripting languagesthis combination makes python useful for large-scale development projects as previewhere are some of the main things you'll find in python' toolboxdynamic typing python keeps track of the kinds of objects your program uses when it runsit doesn' require complicated type and size declarations in your code in factas you'll see in there is no such thing as type or variable declaration anywhere in python because python code does not constrain data typesit is also usually automatically applicable to whole range of objects automatic memory management python automatically allocates objects and reclaims ("garbage collects"them when they are no longer usedand most can grow and shrink on demand as you'll learnpython keeps track of low-level memory details so you don' have to programming-in-the-large support for building larger systemspython includes tools such as modulesclassesand exceptions these tools allow you to organize systems into componentsuse oop python & session
599
functional programming toolsdescribed earlierprovide additional ways to meet many of the same goals built-in object types python provides commonly used data structures such as listsdictionariesand strings as intrinsic parts of the languageas you'll seethey're both flexible and easy to use for instancebuilt-in objects can grow and shrink on demandcan be arbitrarily nested to represent complex informationand more built-in tools to process all those object typespython comes with powerful and standard operationsincluding concatenation (joining collections)slicing (extracting sections)sortingmappingand more library utilities for more specific taskspython also comes with large collection of precoded library tools that support everything from regular expression matching to networking once you learn the language itselfpython' library tools are where much of the application-level action occurs third-party utilities because python is open sourcedevelopers are encouraged to contribute precoded tools that support tasks beyond those supported by its built-inson the webyou'll find free support for comimagingnumeric programmingxmldatabase accessand much more despite the array of tools in pythonit retains remarkably simple syntax and design the result is powerful programming tool with all the usability of scripting language it' mixable python programs can easily be "gluedto components written in other languages in variety of ways for examplepython' api lets programs call and be called by python programs flexibly that means you can add functionality to the python system as neededand use python programs within other environments or systems mixing python with libraries coded in languages such as or ++for instancemakes it an easy-to-use frontend language and customization tool as mentioned earlierthis also makes python good at rapid prototyping--systems may be implemented in python firstto leverage its speed of developmentand later moved to for deliveryone piece at timeaccording to performance demands it' relatively easy to use compared to alternatives like ++javaand #python programming seems astonishingly simple to most observers to run python programyou simply type it and run it there are no intermediate compile and link stepslike there are for languages what are python' technical strengths