id
int64
0
25.6k
text
stringlengths
0
4.59k
2,000
executablesand changing just py_python as needed conclusionsa net win for windows to be fairsome of the prior section' pitfalls may be an inevitable consequence of trying to simultaneously support unix feature on windows and multiple installed versions in exchangeit provides coherent way to manage mixed-version scripts and installations you'll probably find the windows launcher shipped with and later to be major asset once you start using itand get past any initial incompatibilities you may encounter in factyou may also want to start getting into the habit of coding compatible unixstyle #lines in your windows scriptswith explicit version numbers ( #!/usr/binpython not only does this declare your code' requirements and arrange for its proper execution on windowsit will also subvert the launcher' defaultsand may also make your script usable as unix executable in the future but you should be aware that the launcher may break some formerly valid scripts having #linesmay choose default version that you don' expect and your scripts can' useand may require configuration and code changes on the order of those it was intended to obviate the new boss is better than the old bossbut seems to have gone to the same school for more on windows usagesee appendix for installation and configuration for general conceptsand platform-specific documents in python' manuals set appendix bthe python windows launcher
2,001
python changes and this book this appendix briefly summarizes changes made in recent releases of python organized by the book editions where they first appearedand gives links to their coverage in this book it is intended as reference for both readers of prior editionsas well as developers migrating from prior python releases here' how changes in python relate to this book' recent editionsthis fifth edition of covers python and the fourth edition of covered python and (with some featuresthe third edition of covered python the first and second editions of and covered pythons and the predecessor of this book ' programming pythoncovered python henceto see changes made in just this fifth editionsee the python and changes listed ahead for changes incorporated into both the fourth and fifth editions (that issince the third)also see python and changes here third edition language changes are listed very briefly toothough this seems of only historical value today also note that this appendix focuses on major changes and book impactsand is not intended as complete guide to python' evolution for the fuller story on changes applied in each new python releaseconsult the "what' newdocuments that are part of its standard documentation setand available at the documentation page of python org covers python documentation and its manuals set major / differences much of this appendix relates python changes to book coverage if you're instead looking for quick summary of the most prominent / distinctionsthe following may suffice note that this section primarily compares the latest and releases -- and many features are not listed here because they were either also added
2,002
to ( the with statement and class decorators)or back-ported later to ( set and dictionary comprehensions)but are not available in earlier releases see later sections for more fine-grained information about changes in earlier versionsand see python' "what' newdocuments for changes that may appear in future releases differences the following summarizes tools that differ across python lines unicode string modelin xnormal str strings support all unicode text including asciiand the separate bytes type represents raw -bit byte sequences in xnormal str strings support both -bit text including asciiand separate uni code type represents richer unicode text as an option file modelin xfiles created by open are specialized by content--text files implement unicode encodings and represent content as str stringsand binary files represent content as bytes strings in xfiles use distinct interfaces--files created by open represent content as str strings for content that is either -bit text or bytesbased dataand codecs open implements unicode text encodings class modelin xall classes derive from object automatically and acquire the numerous changes and extensions of new-style classesincluding their differing inheritance algorithmbuilt-ins dispatchand mro search order for diamondpattern trees in xnormal classes follow the classic modeland explicit inheritance from object or other built-in types enables the new-style model as an option built-in iterablesin xmapziprangefilterand dictionary keysvaluesand items are all iterable objects that generate values on request in xthese calls create physical lists printing provides built-in function with keyword arguments for configurationwhile provides statement with special syntax for configuration relative importsboth and support from relative import statementsbut changes the search rule to skip package' own directory for normal imports true divisionboth and support the /floor division operatorbut the is true division in and retains fractional remainderswhile is type-specific in integer types has single integer type that supports extended precision has both normal int and extended longand automatic conversion to long comprehension scopesin xall comprehension forms--listsetdictionarygenerator--localize variables to the expression in xlist comprehensions do not pydocan all-browser pydoc - interface is supported as of and required as of in xthe original pydoc - gui client interface may be used instead byte code storageas of stores byte code files in __pycache__ subdirectory of the source directorywith version-identifying names in xbyte code is stored in the source file directory with generic names appendix cpython changes and this book
2,003
os and io classes that includes additional categories and granularity in xexception attributes must sometimes be inspected on system errors comparisons and sortsin xrelative magnitude comparisons of both mixedtypes and dictionaries are errorsand sorts do not support mixed types or general comparison functions (use key mappers insteadin all these forms work string exceptions and module functionsstring-based exceptions are fully removed in xthough they are also gone in as of (use classes insteadstring module functions redundant with string object methods are also removed in language removalsper table - removesrenamesor relocates many language itemsreloadapply` ` ldict has_keyraw_inputxrangefilereduceand file xreadlines -only extensions the following summarizes tools available in only extended sequence assignment allows in sequence assignment targets to collect remaining unmatched iterable items in list can achieve similar effects with slicing nonlocal provides nonlocal statementwhich allows names in enclosing function scopes to be changed from within nested functions can achieve similar effects with function attributesmutable objectsand class state function annotations allows function arguments and return types to be annotated with objects that are retained in the function but not otherwise used may often achieve similar effects with extra objects or decorator arguments keyword-only arguments allows specification of function arguments that must be passed as keywordstypically used for extra configuration options may often achieve similar effects with argument analysis and dictionary pops chained exceptions allows exceptions to be chained and thus appear in error messageswith raise from extension allows none to cancel the chain yield fromas of the yield statement may delegate to nested generator with from can often achieve similar results with for loop in simpler use cases namespace packagesas of the package model is extended to allow packages that span multiple directories with no initialization fileas fallback option might achieve similar effects with import extensions windows launcheras of launcher is shipped with python for windowsthough this is also available separately for use on other pythonsincluding internalsas of threading is implemented with time slices instead of virtual machine instruction countsand stores unicode text in variable-length major / differences
2,004
general general remarks changes although the python line covered in the two most recent editions of this book is largely the same language as its predecessorit differs in some crucial ways as discussed in the preface and summarized in the preceding section ' nonoptional unicode modelmandatory new-style classesand broader emphasis on generators and other functional tools alone can make it materially different experience on the wholepython may be cleaner languagebut it is also in many ways more sophisticated languagerelying upon concepts that are substantially more advanced in factsome of its changes seem to assume you must already know python in order to learn python the preface mentioned some of the more prominent circular knowledge dependencies in that imply forward topic dependencies as random examplethe rationale for wrapping dictionary views in list call in is incredibly subtle and requires substantial foreknowledge--of viewsgeneratorsand the iteration protocolat the least keyword arguments are similarly required in simple tools ( printingstring formattingdictionary creationand sortingthat crop up long before newcomer learns enough about functions to understand them fully one of this book' goals is to help bridge this knowledge gap in today' / dual-version world changes in libraries and tools there are additional changes in python not listed in this appendixsimply because they don' affect this book for examplesome standard libraries and development tools are outside this book' core language scopethough some are mentioned along the way ( timeit)and others have always been covered here ( pydocfor completenessthe following sections note developments in these categories some of the changes in these categories are also listed later in this appendixin conjunction with the book edition and python version in which they were introduced standard library changes formally speakingthe python standard library is not part of this book' core language subjecteven though it' always available with pythonand permeates realistic python programs in factthe libraries were not subject to the temporary language changes moratorium enacted during ' development because of thischanges in the standard library have larger impact on applicationsfocused books like programming python than they do here although most standard appendix cpython changes and this book
2,005
modulesgrouping them into packagesand changing api call patterns some library changes are much broaderthough python ' unicode modelfor examplecreates widespread differences in ' standard library--it potentially impacts any program that processes file contentfilenamesdirectory walkerspipesdescriptor filessocketstext in guisinternet protocols such as ftp and emailcgi scriptsweb content of many kindsand even some persistence tools such as dbm filesshelvesand pickles for more comprehensive list of changes in ' standard librariessee the "what' newdocuments for releases (especially in python' standard manual set because it uses python throughoutthe aforementioned programming python can also serve as guide to library changes tools changes though most development tools are the same between and ( for debuggingprofilingtimingand testing) few have undergone changes in along with the language and library among thesethe pydoc module documentation system has moved away from its former gui client model in and earlierreplacing it with an all web browser interface other noteworthy changes in this categorythe distutils packageused to distribute and install third-party softwareis to be subsumed by new packaging system in xthe new __pycache__ byte code storage scheme described in this bookthough an improvementpotentially impacts many python tools and programsand the internal implementation of threading changed as of to reduce contention by modifying the global interpreter lock (gilto use absolute time slices instead of virtual machine instruction counter migrating to if you are migrating from python to python xbe sure to also see the to automatic code conversion script that is shipped with python it' currently available in python' tools\scripts install folderor via web search this script cannot translate everythingand attempts to translate core language code primarily-- standard library apis may differ further stillit does reasonable job of converting much code to run under converselythe to back-conversion programcurrently available in the third-party domaincan also translate much python code to run in environments depending on your goals and constraintseither to or to may prove useful if you must maintain code for both python linessee the web for detailsand additional tools and techniques general remarks changes
2,006
presented in this book--importing features from __future__avoiding versionspecific toolsand so on many of the examples in this book are platform-neutral for examplessee the benchmarking tools in the module reloaders and comma formatter in the class tree listers in most of the larger decorator examples in and the joke script at the end of and more as long as you understand / core language differencescoding around them is often straightforward if you're interested in writing code for both and xsee also six-- library of crossversion mapping and renaming toolswhich currently lives at org/six naturallythis package can' offset every difference in language semantics and library apisand in many cases you must use its library tools instead of straight python to realize its portability gains in exchangethoughyour programs become much more version-neutral when using this library' tools fifth edition python changes the following specific changes were made in the python and lines after the fourth edition was publishedand have been incorporated into this edition specificallythis section documents python book-related changes in pythons and changes in python on the technical frontpython mostly incorporates as back-ports handful of features that were covered in the prior edition of this bookbut formerly as -only features this new fifth edition presents these as tools as well among theseset literals{ set and dictionary comprehensions{ for in 'spam'}{cc for in 'spam'dictionary viewsincorporated as optional methodsdict viewkeys()dict viewvalues()dict viewitems(comma separators and field autonumbering in str format (from )'{: {}format( 'spam'nested with statement context managers (from )with (as xy(as yfloat object repr display improvements (back-ported from see ahead appendix cpython changes and this book
2,007
changes list of table - or the python changes sectionboth ahead they were already present for xbut have been updated to reflect their availability in as well on the logistical frontper current plans will be the last major series releasebut will have long maintenance period in which it will continue to be used in production work after new development is to shift to the python line that saidit' impossible to foresee how this official posture will stand the test of timegiven ' still very wide user base see the preface for more on thisthe optimized pypy implementationfor exampleis still python only orto borrow monty python line" ' not dead yet "--stay tuned for developments on the python story changes in python python includes surprisingly large number of changes for point release some of these are not entirely compatible with code written for prior release in the line among thesethe new windows launcherinstalled as mandatory part of has broad potential to break existing scripts run on windows here' brief rundown of noteworthy changesalong with their location in this book where applicable python comes witha reduced memory footprint that is more in line with xthanks mainly to its new variable-length string storage schemeand also to its attribute name-sharing dictionaries system (see and new namespace package modelwhere new-style packages may span multiple directories and require no __init__ py file (see new syntax for delegating to subgeneratorsyield from (see new syntax for suppressing exception contextraise from none (see new syntax for accepting ' unicode literal form to ease migration now treats ' unicode literal 'xxxxthe same as its normal string 'xxxx'similar to the way treats ' bytes literal 'xxxxthe same as its normal string 'xxxx(see and reworked os and io exception hierarchieswhich provide more inclusive general superclassesas well as new subclasses for common errors that can obviate the need to inspect exception object attributes (see an all-web-browser-based interface to pydoc documentation started via pydoc -breplacing its former standalone gui client search interfacewhich was in the windows and earlier start button and invoked by pydoc - (see fifth edition python changes
2,008
and emailand potentially distutilsimpacts in this booktime has new portable calls in (see and an implementation of the __import__ function in importlib __import__in part to unify and more clearly expose its implementation (see and new capability in the windows installer that extends the system path setting to include ' directory as an install-time option to simplify some command lines (see appendixes and ba new windows launcherwhich attempts to interpret unix-style #lines for dispatching python scripts on windowsand allows both #lines and new py command lines to select between python and versions explicitly on both perfile and per-command basis (see the new appendix bchanges in python python continued the line' evolution it was developed during moratorium on core language changesso its relevant changes were minor here' quick review of major changesand their location in this fifth edition where relevantbyte-code files storage model change__pycache__ (see and the struct module' autoencoding for strings is gone (see and str/bytes split supported better by python itself (not relevant to this bookthe cgi escape call was to be moved in (not relevant to this bookthreading implementation changetime slices (not relevant to this bookfourth edition python changes the fourth edition was updated to cover python and and incorporated small number of major changes made in its and changes apply to all future releases in the line including this fifth edition' python and its changes are also part of this edition' as noted earliersome of the changes described here as changes also later found their way into python as back-ports ( set literalsand set and dictionary comprehensionschanges in python in addition to the and changes listed in upcoming sectionsshortly before going to press the fourth edition was also augmented with notes about prominent extensions in the then upcoming python releaseincluding appendix cpython changes and this book
2,009
(multiple context manager syntax in with statements (new methods for number objects ((not added until this fifth editionfloating-point display changes and this fifth edition covers these topics in the just noted because python was targeted primarily at optimization and was released relatively soon after the fourth edition also applied directly to in factbecause python superseded entirelyand because the latest python is usually the best python to fetch and use anyhowwhenever that edition used the term "python it generally referred to the language variations introduced by python but that are present in the entire lineincluding this edition' python one notable exceptionthe fourth edition did not incorporate ' new repr display scheme for floating-point numbers the new display algorithm attempts to display floating-point numbers more intelligently when possibleusually with fewer (but occasionally with moredecimal digits-- change that is reflected in this fifth edition changes in python and the fourth edition' language changes stem from python and all of its and many of its changes are shared by python and today python was extended with some features not present in (see earlier in this appendix)and python inherits all the features introduced by because there were so many changes in the initial releasethey are noted only briefly in tables herewith links to more details in this book table - provides the first set of changeslisting the most prominent new language features covered in the fourth editionalong with the primary in the current fifth edition in which they appear table - extensions in python and extension covered in sthe print function in the nonlocal , statement in the str format method in and string types in str for unicode textbytes for binary data text and binary file distinctions in class decorators in and @private('age' new iterators in rangemapzip dictionary views in keysd valuesd items fourth edition python changes
2,010
covered in sdivision operators in remaindersand / set literals in {abc set comprehensions in { ** for in seq dictionary comprehensions in {xx** for in seq binary digit-string support in and bin( the fraction number type in and fraction( function annotations in def ( : :str)->int keyword-only arguments in def ( *bc** extended sequence unpacking in * seq relative import syntax for packages enabled in from context managers enabled in and with/as exception syntax changes in raiseexcept/assuperclass exception chaining in raise from reserved word changes in and new-style class cutover in property decorators in and @property descriptor use in and metaclass use in and abstract base classes support in and specific language removals in in addition to extensionsa number of language tools have been removed in in an effort to clean up its design table - summarizes the removals that impact this bookcovered in various of this edition as noted as also shown in this tablemany of the removals have direct replacementssome of which are also available in and to support future migration to table - removals in python that impact this book removed replacement covered in sreload(mimp reload( (or exec apply(fpsksf(*ps**ks `xrepr( ! long int has_key(kk in (or get(key!none appendix cpython changes and this book
2,011
replacement covered in sraw_input input old input eval(input() xrange range file open (and io module classes next __next__called by next( __getslice__ __getitem__ passed slice ob __setslice__ __setitem__ passed slice ob reduce functools reduce (or loop code execfile(filenameexec(open(file nameread() exec open(filenameexec(open(file nameread() print xy print(xy print >fxy print(xyfile= print xyprint(xyend=' 'ccc(back in 'ccc 'bbbfor byte strings 'bbb raise ev raise ( except exexcept as def ((ab))def ( )(abx file xreadlines for line in file(or =iter(file) keys()etc as lists list( keys()(dictionary views map()range()etc as lists list(map())list(range() map(nonezip (or manual code to pad results = keys() sort(sorted( (or list( keys()) cmp(xy( ( __cmp__(y__lt____gt____eq__etc __nonzero__ __bool__ __hex__x __oct__ __index__ sort comparison functions use key=transform or ject ject (built-insreverse=true fourth edition python changes
2,012
replacement covered in sdictionary compare sorted( items()(or loop code types listtype list (types is for non-built-in names __metaclass__ class (metaclass= ) __builtin__ builtins (renamed tkinter tkinter (renamed sys exc_typeexc_value sys exc_info()[ ][ function func_code function __code__ __getattr__ run by built-ins redefine __x__ methods in wrapper classes - -tt command-line switches inconsistent tabs/spaces use is always an error from *within function may only appear at the top level of file import modin same package from import modpackage-rel class myexceptionclass myexception(excep tion) exceptions module built-in scopelibrary manual threadqueue modules _threadqueue (both renamed anydbm module dbm (renamed cpickle module _pickle (renamedused automati os popen subprocess popen (os popen re string-based exceptions class-based exceptions (also required in string module functions string object methods unbound methods functions (staticmethod to call via instance mixed type comparisonssorts nonnumeric mixed type magnitude comparisons (and sortsare errors onlyative form callytainedthird edition python changes the third edition of this book was thoroughly updated to reflect python and all changes to the language made after the publication of the second edition in late (the second edition was based largely on python with some features grafted on at the end of the project in additionbrief discussions of anticipated changes in appendix cpython changes and this book
2,013
of the major language topics for which new or expanded coverage was provided (numbers here have been updated to reflect this fifth edition)the new if else conditional expression (with/as context managers (try/except/finally unification (relative import syntax (generator expressions (new generator function features (function decorators (the set object type (new built-in functionssortedsumanyallenumerate and the decimal fixed-precision object type (fileslist comprehensionsand iterators and new development toolseclipsedistutilsunittest and doctestidle enhancementsshed skinand so on and smaller language changes (for instancethe widespread use of true and falsethe new sys exc_info for fetching exception detailsand the demise of string-based exceptionsstring methodsand the apply and reduce built-inswere incorporated throughout the book the third edition also expanded coverage of some of the features that were new in the second editionincluding three-limit slices and the arbitrary arguments call syntax that subsumed apply earlier and later python changes each edition before the third also incorporated python changes too--the first two editions from and covered pythons and and their programming python st edition predecessorfrom which my three later books were all derivedbegan the process with python --but 've omitted these here because they are now ancient history (wellin computer field termsat leastsee the first and second editions for more detailsif you can manage to scare one up while it' impossible to predict the futuregiven how much has stood the test of timeit' likely that the core ideas stressed in this book will likely apply to future pythons as well earlier and later python changes
2,014
solutions to end-of-part exercises part igetting started see "test your knowledgepart exerciseson page in for the exercises interaction assuming python is configured properlythe interaction should look something like the following (you can run this any way you like (in idlefrom shell promptand so on)python copyright information lines "hello world!'hello world!use ctrl- or ctrl- to exitor close window programs your code ( modulefile module py and the operating system shell interactions should look like thisprint('hello module world!'python module py hello module worldagainfeel free to run this other ways--by clicking the file' iconby using idle' run-run module menu optionand so on modules the following interaction listing illustrates running module file by importing itpython import module hello module worldremember that you will need to reload the module to run it again without stopping and restarting the interpreter the question about moving the file to different directory and importing it again is trick questionif python generates module pyc file in the original directoryit uses that when you import the moduleeven if the source code pyfile has been moved to directory not in python'
2,015
file' directoryit contains the compiled byte code version of module see for more on modules scripts assuming your platform supports the #trickyour solution will look like the following (although your #line may need to list another path on your machinenote that these lines are significant under the windows launcher shipped and installed with python where they are parsed to select version of python to run the scriptalong with default settingsee appendix for details and examples #!/usr/local/bin/python print('hello module world!'chmod + module py (or #!/usr/bin/env pythonmodule py hello module world errors the following interaction (run in python xdemonstrates the sorts of error messages you'll get when you complete this exercise reallyyou're triggering python exceptionsthe default exception-handling behavior terminates the running python program and prints an error message and stack trace on the screen the stack trace shows where you were in program when the exception occurred (if function calls are active when the error happensthe "tracebacksection displays all active call levelsin and part viiyou will learn that you can catch exceptions using try statements and process them arbitrarilyyou'll also see there that python includes full-blown source code debugger for special errordetection requirements for nownotice that python gives meaningful messages when programming errors occurinstead of crashing silentlypython * traceback (most recent call last)file ""line in zerodivisionerrorint division or modulo by zero spam traceback (most recent call last)file ""line in nameerrorname 'spamis not defined breaks and cycles when you type this codel [ append(lyou create cyclic data structure in python in python releases before the python printer wasn' smart enough to detect cycles in objectsand it would print appendix dsolutions to end-of-part exercises
2,016
to the original listnot copy of the list an unending stream of [ [ [ [ and so onuntil you hit the break-key combination on your machine (whichtechnicallyraises keyboardinterrupt exception that prints default messagebeginning with python the printer is clever enough to detect cycles and prints []instead to let you know that it has detected loop in the object' structure and avoided getting stuck printing forever the reason for the cycle is subtle and requires information you will glean in part iiso this is something of preview but in shortassignments in python always generate references to objectsnot copies of them you can think of objects as chunks of memory and of references as implicitly followed pointers when you run the first assignment abovethe name becomes named reference to two-item list object-- pointer to piece of memory python lists are really arrays of object referenceswith an append method that changes the array in place by tacking on another object reference at the end herethe append call adds reference to the front of at the end of lwhich leads to the cycle illustrated in figure - pointer at the end of the list that points back to the front of the list besides being printed speciallyas you'll learn in cyclic objects must also be handled specially by python' garbage collectoror their space will remain unreclaimed even when they are no longer in use though rare in practicein some programs that traverse arbitrary objects or structures you might have to detect such cycles yourself by keeping track of where you've been to avoid looping believe it or notcyclic data structures can sometimes be usefuldespite their special-case printing part iitypes and operations see "test your knowledgepart ii exerciseson page in for the exercises part iitypes and operations
2,017
about their meaning againnote that is used in few of these to squeeze more than one statement onto single line (the is statement separator)and commas build up tuples displayed in parentheses also keep in mind that the division result near the top differs in python and (see for details)and the list wrapper around dictionary method calls is needed to display results in xbut not (see )numbers * raised to the power integer truncates in xbut not ( strings "spam"eggs'spameggss "ham"eggs 'eggs hams 'hamhamhamhamhams[: 'concatenation repetition an empty slice at the front -[ : empty of same type as object sliced "green % and % ("eggs"sformatting 'green eggs and ham'green { and { }format('eggs' 'green eggs and hamtuples (' ',)[ ' (' '' ')[ 'yindexing single-item tuple indexing two-item tuple lists [ , , [ , , list operations ll[:] [: ] [- ] [- :([ ][ ][] [ ]([ , , ]+[ , , ])[ : [ [ [ ] [ ]fetch from offsetsstore in list [ reverse() methodreverse list in place [ sort() methodsort list in place [ index( methodoffset of first four (search appendix dsolutions to end-of-part exercises
2,018
{' ': ' ': }[' ' {' ': ' ': ' ': [' ' [' ' [' ' [( , , ) index dictionary by key create new entry tuple used as key (immutabled {' ' ' ' ' ' ( ) ' ' list( keys())list( values())( , , in ([' '' '' '( )' '][ ]truemethodskey test empties [[]]["",[],(),{},none([[]][''[](){}none]lots of nothingsempty objects indexing and slicing indexing out of bounds ( [ ]raises an errorpython always checks to make sure that all offsets are within the bounds of sequence on the other handslicing out of bounds ( [- : ]works because python scales out-of-bounds slices so that they always fit (the limits are set to zero and the sequence lengthif requiredextracting sequence in reversewith the lower bound greater than the higher bound ( [ : ])doesn' really work you get back an empty slice (]because python scales the slice limits to make sure that the lower bound is always less than or equal to the upper bound ( [ : is scaled to [ : ]the empty insertion point at offset python slices are always extracted from left to righteven if you use negative indexes (they are first converted to positive indexes by adding the sequence lengthnote that python ' three-limit slices modify this behavior somewhat for instancel[ : :- does extract from right to leftl [ [ traceback (innermost last)file ""line in indexerrorlist index out of range [- : [ [ : [ [ [ : ['?' [ '?' part iitypes and operations
2,019
an empty list object therebut assigning an empty list to slice deletes the slice slice assignment expects another sequenceor you'll get type errorit inserts items inside the sequence assignednot the sequence itselfl [ , , , [ [ [ [] [ : [ [ del [ [ del [ : [ [ : traceback (innermost last)file ""line in typeerrorillegal argument type for built-in operation tuple assignment the values of and are swapped when tuples appear on the left and right of an assignment symbol (=)python assigns objects on the right to targets on the left according to their positions this is probably easiest to understand by noting that the targets on the left aren' real tupleeven though they look like onethey are simply set of independent assignment targets the items on the right are tuplewhich gets unpacked during the assignment (the tuple provides the temporary assignment needed to achieve the swap effect) 'spamy 'eggsxy yx 'eggsy 'spam dictionary keys any immutable object can be used as dictionary keyincluding integerstuplesstringsand so on this really is dictionaryeven though some of its keys look like integer offsets mixed-type keys work finetood { [ 'ad[ 'bd[( )'cd { ' ' ' '( )' ' dictionary indexing indexing nonexistent key ( [' ']raises an errorassigning to nonexistent key ( [' ']='spam'creates new dictionary entry on the other handout-of-bounds indexing for lists raises an error toobut so do out-of-bounds appendix dsolutions to end-of-part exercises
2,020
been assigned when referencedbut they are created when first assigned in factvariable names can be processed as dictionary keys if you wish (they're made visible in module namespace or stack-frame dictionaries) {' ': ' ': ' ': [' ' [' 'traceback (innermost last)file ""line in keyerrord [' ' {' ' ' ' ' ' ' ' [ [ traceback (innermost last)file ""line in indexerrorlist index out of range [ traceback (innermost last)file ""line in indexerrorlist assignment index out of range generic operations question answersthe operator doesn' work on different/mixed types ( string listlist tupledoesn' work for dictionariesas they aren' sequences the append method works only for listsnot stringsand keys works only on dictionaries append assumes its target is mutablesince it' an in-place extensionstrings are immutable slicing and concatenation always return new object of the same type as the objects processed" traceback (innermost last)file ""line in typeerrorillegal argument type for built-in operation {{traceback (innermost last)file ""line in typeerrorbad operand type(sfor [append( "append(' 'traceback (innermost last)file ""line in attributeerrorattribute-less object part iitypes and operations
2,021
list({keys()[[keys(traceback (innermost last)file ""line in attributeerrorkeys [][:[""[:'list(needed in xnot string indexing this is bit of trick question--because strings are collections of one-character stringsevery time you index stringyou get back string that can be indexed again [ ][ ][ ][ ][ just keeps indexing the first character over and over this generally doesn' work for lists (lists can hold arbitrary objectsunless the list contains stringss "spams[ ][ ][ ][ ][ 'sl [' '' ' [ ][ ][ ' immutable types either of the following solutions works index assignment doesn'tbecause strings are immutables "spams [ 'ls[ : 'slams [ 'ls[ [ 'slam(see also the python and bytearray string type in --it' mutable sequence of small integers that is essentially processed the same as string nesting here is sampleme {'name':('john'' ''doe')'age':'?''job':'engineer'me['job''engineerme['name'][ 'doe files here' one way to create and read back text file in python (ls is unix commanduse dir on windows)filemaker py file open('myfile txt'' 'file write('hello file world!\ 'file close(oropen(write(close not always needed filereader py file open('myfile txt''ris default open mode appendix dsolutions to end-of-part exercises
2,022
print(file read()python maker py python reader py hello file worldls - myfile txt -rwxrwxrwa apr : myfile txt part iiistatements and syntax see "test your knowledgepart iii exerciseson page in for the exercises coding basic loops as you work through this exerciseyou'll wind up with code that looks like the followings 'spamfor in sprint(ord( ) for in sx +ord(cx orx ord(cx [for in sx append(ord( ) [ list(map(ords)[ [ord(cfor in [ list(required in xnot map and listcomps automate list builders backslash characters the example prints the bell character (\ timesassuming your machine can handle itand when it' run outside of idleyou may get series of beeps (or one sustained toneif your machine is fast enoughhey-- warned you sorting dictionaries here' one way to work through this exercise (see or if this doesn' make senserememberyou really do have to split up the keys and sort calls like this because sort returns none in python and lateryou can iterate through dictionary keys directly without calling keys ( part iiistatements and syntax
2,023
recent pythonsyou can achieve the same effect with the sorted built-intood {' ': ' ': ' ': ' ': ' ': ' ': ' ': {' ' ' ' ' ' ' ' ' ' ' ' ' ' keys list( keys()list(required in xnot in keys sort(for key in keysprint(key'=>' [key] = = = = = = = for key in sorted( )print(key'=>' [key]betterin more recent pythons program logic alternatives here' some sample code for the solutions for step eassign the result of * to variable outside the loops of steps and band use it inside the loop your results may vary bitthis exercise is mostly designed to get you playing with code alternativesso anything reasonable gets full credita [ while len( )if * = [ ]print('at index'ibreak + elseprint( 'not found' [ for in lif ( * =pprint(( * )'was found at' index( )break elseprint( 'not found' appendix dsolutions to end-of-part exercises
2,024
if ( *xin lprint(( * )'was found at' index( * )elseprint( 'not found' [for in range( ) append( *iprint(lif ( *xin lprint(( * )'was found at' index( * )elseprint( 'not found' list(map(lambda **xrange( ))print(lor [ ** for in range( )list(to print all in xnot if ( *xin lprint(( * )'was found at' index( * )elseprint( 'not found' code maintenance there is no fixed solution to show heresee mypydoc py in the book' examples package for my edits on this code as one example part ivfunctions and generators see "test your knowledgepart iv exerciseson page in for the exercises the basics there' not much to this onebut notice that using print (and hence your functionis technically polymorphic operationwhich does the right thing for each type of objectpython def func( )print(xfunc("spam"spam func( func([ ][ part ivfunctions and generators
2,025
{'food''spam' arguments here' sample solution remember that you have to use print to see results in the test calls because file isn' the same as code typed interactivelypython doesn' normally echo the results of expression statements in filesdef adder(xy)return print(adder( )print(adder('spam''eggs')print(adder([' '' '][' '' '])python mod py spameggs [' '' '' '' ' varargs two alternative adder functions are shown in the following fileadders py the hard part here is figuring out how to initialize an accumulator to an empty value of whatever type is passed in the first solution uses manual type testing to look for an integerand an empty slice of the first argument (assumed to be sequenceif the argument is determined not to be an integer the second solution uses the first argument to initialize and scan items and beyondmuch like one of the min function variants shown in the second solution is better both of these assume all arguments are of the same typeand neither works on dictionaries (as we saw in part iidoesn' work on mixed types or dictionariesyou could add type test and special code to allow dictionariestoobut that' extra credit def adder (*args)print('adder 'end='if type(args[ ]=type( )sum elsesum args[ ][: for arg in argssum sum arg return sum def adder (*args)print('adder 'end='sum args[ for next in args[ :]sum +next return sum integerinit to zero else sequenceuse empty slice of arg init to arg add items for func in (adder adder )print(func( )print(func('spam''eggs''toast')print(func([' '' '][' '' '][' '' ']) appendix dsolutions to end-of-part exercises
2,026
adder adder spameggstoast adder [' '' '' '' '' '' 'adder adder spameggstoast adder [' '' '' '' '' '' ' keywords here is my solution to the first and second parts of this exercise (coded in the file mod pyto iterate over keyword argumentsuse the **args form in the function header and use loop ( for in args keys()use args[ ])or use args values(to make this the same as summing *args positionalsdef adder(good= bad= ugly= )return good bad ugly print(adder()print(adder( )print(adder( )print(adder( )print(adder(ugly= good= bad= )python mod py second part solutions def adder (*args)tot args[ for arg in args[ :]tot +arg return tot sum any number of positional args def adder (**args)argskeys list(args keys()tot args[argskeys[ ]for key in argskeys[ :]tot +args[keyreturn tot sum any number of keyword args list needed in xdef adder (**args)args list(args values()tot args[ for arg in args[ :]tot +arg return tot samebut convert to list of values list needed to index in xdef adder (**args)return adder (*args values()samebut reuse positional version print(adder ( )adder ('aa''bb''cc')part ivfunctions and generators
2,027
print(adder ( = = = )adder ( ='aa' ='bb' ='cc')print(adder ( = = = )adder ( ='aa' ='bb' ='cc') (and dictionary tools here are my solutions to exercises and (file dicts pythese are just coding exercisesthoughbecause python added the dictionary methods copy(and update( to handle things like copying and adding (mergingdictionaries see for dict update examplesand python' library manual or 'reilly' python pocket reference for more details [:doesn' work for dictionariesas they're not sequences (see for detailsalsoremember that if you assign ( drather than copyingyou generate reference to shared dictionary objectchanging changes etoodef copydict(old)new {for key in old keys()new[keyold[keyreturn new def adddict( )new {for key in keys()new[keyd [keyfor key in keys()new[keyd [keyreturn new python from dicts import { copydict(dd[ '? { '?' { { { adddict(xyz { see # more argument-matching examples here is the sort of interaction you should getalong with comments that explain the matching that goes ondef (ab)print(abnormal args def ( * )print(abpositional varargs def ( ** )print(abkeyword varargs def ( * ** )print(abcmixed modes appendix dsolutions to end-of-part exercises
2,028
def (ab= * )print(abcpython ( ( = = defaults and positional varargs matched by position (order mattersmatched by name (order doesn' matterf ( ( extra positionals collected in tuple ( = = {' ' ' ' extra keywords collected in dictionary ( = = ( {' ' ' ' extra of both kinds ( ( both defaults kick in ( ( ( ( ,one argumentmatches "aonly one default used extra positional collected primes revisited here is the primes examplewrapped up in function and module (file primes pyso it can be run multiple times added an if test to trap negatives and also changed to /in this edition to make this solution immune to the python true division changes we studied in and to enable it to support floating-point numbers (uncomment the from statement and change /to to see the differences in )#from __future__ import division def prime( )if < print( 'not prime'elsex / while if = print( 'has factor'xbreak - elseprint( 'is prime'for some fails no remainderskip else prime( )prime( prime( )prime( part ivfunctions and generators
2,029
prime( )prime( prime(- here is the module in actionthe /operator allows it to work for floating-point numbers tooeven though it perhaps should notpython primes py is prime is prime has factor has factor is prime is prime not prime - not prime this function still isn' very reusable--it could return valuesinstead of printing --but it' enough to run experiments it' also not strict mathematical prime (floating points work)and it' still inefficient improvements are left as exercises for more mathematically minded readers (hinta for loop over range( - may be bit quicker than the whilebut the algorithm is the real bottleneck here to time alternativesuse the homegrown timer or standard library timeit modules and coding patterns like those used in ' timing sections (and see solution iterations and comprehensions here is the sort of code you should writei may have preferencebut yours may varyvalues [ import math res [for in valuesres append(math sqrt( )res [ list(map(math sqrtvalues)[ [math sqrt(xfor in values[ list(math sqrt(xfor in values[ timing tools here is some code wrote to time the three square root optionsalong with the results in cpythons and and pypy (which implements python each test takes the best of three runseach run takes the total time required to call the test function , timesand each test function iterates , times the last result of each function is printed to verify that all three do the same workfile timer py ( and xsame as listed in appendix dsolutions to end-of-part exercises
2,030
import systimer reps repslist range(repsfrom math import sqrt def mathmod()for in repslistres sqrt(ireturn res pull out range list time for not math sqrtadds attr fetch time def powcall()for in repslistres pow( return res def powexpr()for in repslistres * return res print(sys versionfor test in (mathmodpowcallpowexpr)elapsedresult timer bestoftotal(test_reps = _reps= print ('% =% (test __name__elapsedresult)following are the test results for the three pythons the and results are roughly twice as fast as and in the prior editiondue largely to faster test machine for each python testedit looks like the math module is quicker than the *expressionwhich is quicker than the pow callhoweveryou should try this with your code and on your own machine and version of python alsonote that python is essentially twice as slow as on this testand pypy is rough order of magnitude ( xfaster than both cpythonsdespite the fact that this is running floating-point math and iterations later versions of any of these pythons might differso time this in the future to see for yourselfc:\codepy - timesqrt py ( :bd afb ebf sep : : [msc bit (amd )mathmod = powcall = powexpr = :\codepy - timesqrt py (defaultapr : : [msc bit (amd )mathmod = powcall = powexpr = :\codec:\pypy\pypy- \pypy timesqrt py ( ffjun : : [pypy with msc bitmathmod = part ivfunctions and generators
2,031
powexpr = to time the relative speeds of python and dictionary comprehensions and equivalent for loops interactivelyyou can run session like the following it appears that the two are roughly the same in this regard under python unlike list comprehensionsthoughmanual loops are slightly faster than dictionary comprehensions today (though the difference isn' exactly earth-shattering--at the end we save half second when making dictionaries of , , items eachagainrather than taking these results as gospel you should investigate further on your ownon your computer and with your pythonc:\codec:\python \python def dictcomp( )return {ii for in range( )def dictloop( )new {for in range( )new[ii return new dictcomp( { dictloop( { from timer import totalbestof bestof(dictcomp )[ , -item dict bestof(dictloop )[ bestof(dictcomp )[ , -items slower bestof(dictloop )[ bestof(dictcomp )[ of -items time bestof(dictloop )[ total(dictcomp _reps= )[ total to make -item dicts total(dictloop _reps= )[ recursive functions coded this function as followsa simple rangecomprehensionor map will do the job here as wellbut recursion is useful enough to experiment with here (print is function in onlyunless you import it from __future__ or code your own equivalent) appendix dsolutions to end-of-part exercises
2,032
if = print('stop'elseprint(nend='countdown( - xprint 'stop xprint ncountdown( stop countdown( stop nonrecursive optionslist(range( - )[ on onlyt [print(iend='for in range( - ) list(map(lambda xprint(xend=')range( - )) didn' include generator-based solution in this exercise on the grounds of merit (and humanity!)but one is listed belowall the other techniques seem much simpler in this case-- good example of cases where generators should probably be avoided remember that generators produce no results until iteratedso we need for or yield from here (yield from works in and later only)def countdown ( )if = yield 'stopelseyield for in countdown ( - )yield generator functionrecursive +yield from countdown ( - list(countdown ( )[ 'stop'nonrecursive optionsdef countdown ()yield from range( - generator functionsimpler pre for in range()yield list(countdown ()[ list( for in range( - )[ equivalent generator expression list(range( - )[ equivalent nongenerator form computing factorials the following file shows how coded this exerciseit runs on python and xand its output on is given in string literal at the end of the file naturallythere are many possible variations on its codeits rangesfor part ivfunctions and generators
2,033
reduce(operator mulrange( - )to avoid lambda #!python from __future__ import print_function from functools import reduce from timeit import repeat import math def fact ( )if = return elsereturn fact ( - def fact ( )return if = else fact ( - def fact ( )return reduce(lambda xyx yrange( + )def fact ( )res for in range( + )res * return res def fact ( )return math factorial(nfile factorials py recursive fails at by default recursiveone-liner functional iterative stdlib "batteriestests print(fact ( )fact ( )fact ( )fact ( )fact ( ) * * * * * all print(fact ( =fact ( =fact ( =fact ( =fact ( )true for test in (fact fact fact fact fact )print(test __name__min(repeat(stmt=lambdatest( )number= repeat= )) "" :\codepy - factorials py true fact fact fact fact fact ""conclusionsrecursion is slowest on my python and machineand fails once reaches due to the default stack size setting in sysper this limit can be increasedbut simple loops or the standard library tool seem the best route here in any event this general finding holds true often for instance'join(reversed( )may be the preferred way to reverse stringeven though recursive solutions are possible appendix dsolutions to end-of-part exercises
2,034
of magnitude slower in cpythonthough these results vary in pypydef rev ( )if len( = return elsereturn [- rev ( [:- ]recursive slower in cpython today def rev ( )return 'join(reversed( )nonrecursive iterablesimplerfaster def rev ( )return [::- even better?sequence reversal by slice part vmodules and packages see "test your knowledgepart exerciseson page in for the exercises import basics when you're doneyour file (mymod pyand interaction should look similar to the followingremember that python can read whole file into list of line stringsand the len built-in returns the lengths of strings and listsdef countlines(name)file open(namereturn len(file readlines()def countchars(name)return len(open(nameread()def test(name)return countlines(name)countchars(nameor pass file object or return dictionary python import mymod mymod test('mymod py'( your counts may varyas mine may or may not include comments and an extra line at the end note that these functions load the entire file in memory all at onceso they won' work for pathologically large files too big for your machine' memory to be more robustyou could read line by line with iterators instead and count as you godef countlines(name)tot for line in open(name)tot + return tot def countchars(name)tot part vmodules and packages
2,035
return tot generator expression can have the same effect (though the instructor might take off points for excessive magic!)def countlines(name)return sum(+ for line in open(name)def countchars(name)return sum(len(linefor line in open(name)on unixyou can verify your output with wc commandon windowsright-click on your file to view its properties note that your script may report fewer characters than windows does--for portabilitypython converts windows \ \ line-end markers to \nthereby dropping byte (characterper line to match byte counts with windows exactlyyou must open in binary mode ('rb')or add the number of bytes corresponding to the number of lines see and for more on end-of-line translations in text files the "ambitiouspart of this exercise (passing in file object so you only open the file once)will require you to use the seek method of the built-in file object it works like ' fseek call (and may call it behind the scenes)seek resets the current position in the file to passed-in offset after seekfuture input/output operations are relative to the new position to rewind to the start of file without closing and reopening itcall file seek( )the file read methods all pick up at the current position in the fileso you need to rewind to reread here' what this tweak would look likedef countlines(file)file seek( return len(file readlines()rewind to start of file def countchars(file)file seek( return len(file read()ditto (rewind if neededdef test(name)file open(namereturn countlines(file)countchars(filepass file object open file only once import mymod mymod test("mymod py"( from/from here' the from partreplace with countchars to do the restpython from mymod import countchars("mymod py" __main__ if you code it properlythis file works in either mode--program run or module importdef countlines(name)file open(name appendix dsolutions to end-of-part exercises
2,036
def countchars(name)return len(open(nameread()def test(name)return countlines(name)countchars(nameor pass file object or return dictionary if __name__ ='__main__'print(test('mymod py')python mymod py ( this is where would probably begin to consider using command-line arguments or user input to provide the filename to be countedinstead of hardcoding it in the script (see for more on sys argvand for more on input-and use raw_input instead in )if __name__ ='__main__'print(test(input('enter file name:')if __name__ ='__main__'import sys print(test(sys argv[ ])console (raw_input in xcommand line nested imports here is my solution (file myclient py)from mymod import countlinescountchars print(countlines('mymod py')countchars('mymod py')python myclient py as for the rest of this onemymod' functions are accessible (that isimportablefrom the top level of myclientsince from simply assigns to names in the importer (it works as if mymod' defs appeared in myclientfor exampleanother file can sayimport myclient myclient countlinesfrom myclient import countchars countcharsif myclient used import instead of fromyou' need to use path to get to the functions in mymod through myclientimport myclient myclient mymod countlinesfrom myclient import mymod mymod countcharsin generalyou can define collector modules that import all the names from other modules so they're available in single convenience module the following partial part vmodules and packages
2,037
namecollector somenameand __main__ somenameall three share the same integer object initiallyand only the name somename exists at the interactive prompt as isfile mod py somename file collector py from mod import from mod import from mod import collect lots of names here from assigns to my names from collector import somename package imports for thisi put the mymod py solution file listed for exercise into directory package the following is what did in windows console interface to set up the directory and the __init__ py file that it' required to have until python you'll need to interpolate for other platforms ( use cp and vi instead of copy and notepadthis works in any directory ( ' using my own code directory here)and you can do some of this from file explorer guitoo when was donei had mypkg subdirectory that contained the files __init__ py and mymod py until python ' namespace package extensionyou need an __init__ py in the mypkg directorybut not in its parenttechnicallymypkg is located in the home directory component of the module search path notice how print statement coded in the directory' initialization file fires only the first time it is importednot the secondraw strings are also used here to avoid escape issues in the file pathsc:\codemkdir mypkg :\codecopy mymod py mypkg\mymod py :\codenotepad mypkg\__init__ py coded print statement :\codepython import mypkg mymod initializing mypkg mypkg mymod countlines( 'mypkg\mymod py' from mypkg mymod import countchars countchars( 'mypkg\mymod py' reloads this exercise just asks you to experiment with changing the changer py example in the bookso there' nothing to show here circular imports the short story is that importing recur first works because the recursive import then happens at the import in recur not at from in recur the long story goes like thisimporting recur first works because the recursive import from recur to recur fetches recur as wholeinstead of getting specific names recur is incomplete when it' imported from recur but because it uses import instead of fromyou're safepython finds and returns the already created appendix dsolutions to end-of-part exercises
2,038
when the recur import resumesthe second from finds the name in recur (it' been run completely)so no error is reported running file as script is not the same as importing it as modulethese cases are the same as running the first import or from in the script interactively for instancerunning recur as script worksbecause it is the same as importing recur interactivelyas recur is the first module imported in recur running recur as script fails for the same reason--it' the same as running its first import interactively part viclasses and oop see "test your knowledgepart vi exerciseson page in for the exercises inheritance here' the solution code for this exercise (file adder py)along with some interactive tests the __add__ overload has to appear only oncein the superclassas it invokes type-specific add methods in subclassesclass adderdef add(selfxy)print('not implemented!'def __init__(selfstart=[])self data start def __add__(selfother)return self add(self dataotheror in subclassesor return typeclass listadder(adder)def add(selfxy)return class dictadder(adder)def add(selfxy)new {for in keys()new[kx[kfor in keys()new[ky[kreturn new python from adder import adder( add( not implementedx listadder( add([ ][ ][ dictadder( add({ : }{ : }{ adder([ ]part viclasses and oop
2,039
not implementedx listadder([ ] [ [ [ in typeerrorcan only concatenate list (not "listadder"to list earliertypeerror__add__ nor __radd__ defined for these operands notice in the last test that you get an error for expressions where class instance appears on the right of +if you want to fix thisuse __radd__ methodsas described in "operator overloadingin if you are saving value in the instance anyhowyou might as well rewrite the add method to take just one argumentin the spirit of other examples in this part of the book (this is adder py)class adderdef __init__(selfstart=[])self data start def __add__(selfother)return self add(otherdef add(selfy)print('not implemented!'pass single argument the left side is in self class listadder(adder)def add(selfy)return self data class dictadder(adder)def add(selfy) self data copy( update(yreturn listadder([ ] [ print(ychange to use self data instead of or "cheatby using quicker built-ins prints [ dictadder(dict(name='bob'){' ': print(zprints {'name''bob'' ' because values are attached to objects rather than passed aroundthis version is arguably more object-oriented andonce you've gotten to this pointyou'll probably find that you can get rid of add altogether and simply define type-specific __add__ methods in the two subclasses operator overloading the solution code (file mylist pyuses handful of operator overloading methods we explored in copying the initial value in the constructor is important because it may be mutableyou don' want to change or have reference to an object that' possibly shared somewhere outside the class the __getattr__ method routes calls to the wrapped list for hints on an easier appendix dsolutions to end-of-part exercises
2,040
class mylistdef __init__(selfstart)#self wrapped start[:self wrapped list(startdef __add__(selfother)return mylist(self wrapped otherdef __mul__(selftime)return mylist(self wrapped timedef __getitem__(selfoffset)return self wrapped[offsetdef __len__(self)return len(self wrappeddef __getslice__(selflowhigh)return mylist(self wrapped[low:high]def append(selfnode)self wrapped append(nodedef __getattr__(selfname)return getattr(self wrappednamedef __repr__(self)return repr(self wrappedcopy startno side effects make sure it' list here also passed slice in for iteration if no __iter__ ignored in xuses __getitem__ other methodssort/reverse/etc catchall display method if __name__ ='__main__' mylist('spam'print(xprint( [ ]print( [ :]print( ['eggs']print( append(' ' sort(print(join( for in ) :\codepython mylist py [' '' '' '' ' [' '' '' '[' '' '' '' ''eggs'[' '' '' '' '' '' '' '' '' '' '' '' ' note that it' important to copy the start value by calling list instead of slicing herebecause otherwise the result may not be true list and so will not respond to expected list methodssuch as append ( slicing string returns another stringnot listyou would be able to copy mylist start value by slicing because its class overloads the slicing operation and provides the expected list interfacehoweveryou need to avoid slice-based copying for objects such as strings subclassing my solution (mysub pyappears as follows your solution should be similarpart viclasses and oop
2,041
class mylistsub(mylist)calls def __init__(selfstart)self adds mylist __init__(selfstartdef __add__(selfother)print('addstr(other)mylistsub calls + self adds + return mylist __add__(selfotherdef stats(self)return self callsself adds shared by instances varies in each instance class-wide counter per-instance counts all addsmy adds if __name__ ='__main__' mylistsub('spam' mylistsub('foo'print( [ ]print( [ :]print( ['eggs']print( ['toast']print( ['bar']print( stats() :\codepython mysub py [' '' '' 'add['eggs'[' '' '' '' ''eggs'add['toast'[' '' '' '' ''toast'add['bar'[' '' '' ''bar'( attribute methods worked through this exercise as follows notice that in python ' classic classesoperators try to fetch attributes through __getattr__tooyou need to return value to make them work as noted in and elsewhere__getattr__ is not called for built-in operations in python (and in if newstyle classes are used)so the expressions aren' intercepted at all herein new-style classesa class like this must redefine __x__ operator overloading methods explicitly more on this in and it can impact much codec:\codepy - class attrsdef __getattr__(selfname)print('get %snamedef __setattr__(selfnamevalue)print('set % % (namevalue) appendix dsolutions to end-of-part exercises
2,042
attrs( append get append spam 'porkset spam pork get __coerce__ typeerror'nonetypeobject is not callable [ get __getitem__ typeerror'nonetypeobject is not callable [ : get __getslice__ typeerror'nonetypeobject is not callable :\codepy - same startup code typeerrorunsupported operand type(sfor +'attrsand 'intx[ typeerror'attrsobject does not support indexing [ : typeerror'attrsobject is not subscriptable set objects here' the sort of interaction you should get comments explain which methods are called alsonote that sets are built-in type in python todayso this is largely just coding exercise (see for more on setspython from setwrapper import set set([ ] set([ ]runs __init__ set:[ set:[ __and__intersectthen __repr__ set("hello" [ ] [- ] [ :(' '' '[' '' ']__init__ removes duplicates __getitem__ for in zprint(cend=' 'join( upper(for in 'helolen( ) ( set:[' '' '' '' ']__iter__ (else __getitem__[ print__or__unionthen __repr__ __iter__ (else __getitem____len____repr__ "mello" "mello(set:[' '' '' ']set:[' '' '' '' '' ']part viclasses and oop
2,043
class (file multiset pyit needs to replace only two methods in the original set the class' documentation string explains how it worksfrom setwrapper import set class multiset(set)""inherits all set namesbut extends intersect and union to support multiple operandsnote that "selfis still the first argument (stored in the *args argument now)also note that the inherited and operators call the new methods here with argumentsbut processing more than requires method callnot an expressionintersect doesn' remove duplicates herethe set constructor does""def intersect(self*others)res [for in selfscan first sequence for other in othersfor all other args if not in otherbreak item in each oneelsenobreak out of loop res append(xyesadd item to end return set(resdef union(*args)res [for seq in argsfor in seqif not in resres append(xreturn set(resself is args[ for all args for all nodes add new items to result your interaction with the extension will look something like the following note that you can intersect by using or calling intersectbut you must call inter sect for three or more operandsis binary (two-sidedoperator alsonote that we could have called multiset simply set to make this change more transparent if we used setwrapper set to refer to the original within multiset (the as clause in an import could rename the class too if desired)from multiset import multiset([ ] multiset([ ] multiset([ ] yx (set:[ ]set:[ ]two operands intersect(yzset:[ union(yzset:[ intersect([ , , ][ , , ][ , , ]set:[ union(range( )three operands appendix dsolutions to end-of-part exercises four operands non-multisets worktoo
2,044
multiset('spam' set:[' '' '' '' ''join( 'super''spamuer( 'super'multiset('slots'set:[' 'string sets class tree links here is the way changed the lister classesand rerun of the test to show its format do the same for the dir-based versionand also do this when formatting class objects in the tree climber variantclass listinstancedef __attrnames(self)unchanged def __str__(self)return 'self __class__ __name__my class' name self __supers()my class' own supers id(self)my address self __attrnames()name=value list def __supers(self)names [for super in self __class__ __bases__names append(super __name__return 'join(namesone level up from class namenot str(superor'join(super __name__ for super in self __class__ __bases__c:\codepy listinstance-exercise py <instance of sub(superlistinstance)address data =spam data =eggs data = composition my solution is as follows (file lunch py)with comments from the description mixed in with the code this is one case where it' probably easier to express problem in python than it is in englishclass lunchdef __init__(self)make/embed customeremployee self cust customer(self empl employee(def order(selffoodname)start customer order simulation self cust placeorder(foodnameself empldef result(self)ask the customer about its food self cust printfood(class customerdef __init__(self)self food none initialize my food to none part viclasses and oop
2,045
place order with employee self food employee takeorder(foodnamedef printfood(self)print the name of my food print(self food nameclass employeedef takeorder(selffoodname)return food(foodnamereturn foodwith desired name class fooddef __init__(selfname)self name name store food name if __name__ ='__main__' lunch( order('burritos' result( order('pizza' result(self-test code if runnot imported python lunch py burritos pizza zoo animal hierarchy here is the way coded the taxonomy in python (file zoo py)it' artificialbut the general coding pattern applies to many real structuresfrom guis to employee databases to spacecraft notice that the self speak reference in animal triggers an independent inheritance searchwhich finds speak in subclass test this interactively per the exercise description try extending this hierarchy with new classesand making instances of various classes in the treeclass animaldef reply(self)def speak(self)self speak(print('spam'class mammal(animal)def speak(self)print('huh?'class cat(mammal)def speak(self)print('meow'class dog(mammal)def speak(self)print('bark'back to subclass custom message class primate(mammal)def speak(self)print('hello world!'class hacker(primate)pass inherit from primate the dead parrot sketch here' how implemented this one (file parrot pynotice how the line method in the actor superclass worksby accessing self attributes twiceit sends python back to the instance twiceand hence invokes two inheritance searches--self name and self says(find information in the specific subclasses appendix dsolutions to end-of-part exercises
2,046
def line(self)print(self name ':'repr(self says())class customer(actor)name 'customerdef says(self)return "that' one ex-bird!class clerk(actor)name 'clerkdef says(self)return "no it isn' class parrot(actor)name 'parrotdef says(self)return none class scenedef __init__(self)self clerk clerk(self customer customer(self subject parrot(def action(self)self customer line(self clerk line(self subject line(embed some instances scene is composite delegate to embedded part viiexceptions and tools see "test your knowledgepart vii exerciseson page in for the exercises try/except my version of the oops function (file oops pyfollows as for the noncoding questionschanging oops to raise keyerror instead of an indexerror means that the try handler won' catch the exception--it "percolatesto the top level and triggers python' default error message the names keyerror and indexerror come from the outermost built-in names scope (the in "legb"import builtins in (and __builtin__ in python xand pass it as an argument to the dir function to see this for yourself def oops()raise indexerror(def doomed()tryoops(except indexerrorprint('caught an index error!'elseprint('no error caught 'if __name__ ='__main__'doomed(part viiexceptions and tools
2,047
caught an index error exception objects and lists here' the way extended this module for an exception of my ownfile oops pyfrom __future__ import print_function class myerror(exception)pass def oops()raise myerror('spam!'def doomed()tryoops(except indexerrorprint('caught an index error!'except myerror as dataprint('caught error:'myerrordataelseprint('no error caught 'if __name__ ='__main__'doomed(python oops py caught errorspamlike all class exceptionsthe instance is accessible via the as variable datathe error message shows both the class (and its instance (spam!the instance must be inheriting both an __init__ and __repr__ or __str__ from python' excep tion classor it would print much like the class does see for details on how this works in built-in exception classes error handling here' one way to solve this one (file exctools pyi did my tests in filerather than interactivelybut the results are similar enough for full credit notice that the empty except and sys exc_info approach used here will catch exitrelated exceptions that listing exception with an as variable won'tthat' probably not ideal in most applications codebut might be useful in tool like this designed to work as sort of exceptions firewall import systraceback def safe(callee*pargs**kargs)trycallee(*pargs**kargscatch everything else exceptor "except exception as :traceback print_exc(print('got % % (sys exc_info()[ ]sys exc_info()[ ])if __name__ ='__main__'import oops safe(oops oops appendix dsolutions to end-of-part exercises
2,048
traceback (most recent call last)file " :\code\exctools py"line in safe callee(*pargs**kargscatch everything else file " :\code\oops py"line in oops raise myerror('spam!'oops myerrorspamgot spamthe following sort of code could turn this into function decorator that could wrap and catch exceptions raised by any functionusing techniques introduced in but covered more fully in in the next part of the book--it augments functionrather than expecting it to be passed in explicitlyimport systraceback def safe(callee)def callproxy(*pargs**kargs)tryreturn callee(*pargs**kargsexcepttraceback print_exc(print('got % % (sys exc_info()[ ]sys exc_info()[ ])raise return callproxy if __name__ ='__main__'import oops @safe def test()oops oops(test( self-study examples here are few examples for you to study as time allowsfor moresee follow-up books--such as programming pythonfrom which these examples were borrowed or derived--and the webfind the largest python source file in single directory import osglob dirname ' :\python \liballsizes [allpy glob glob(dirname os sep 'py'for filename in allpyfilesize os path getsize(filenameallsizes append((filesizefilename)allsizes sort(print(allsizes[: ]print(allsizes[- :]part viiexceptions and tools
2,049
import sysospprint if sys platform[: ='win'dirname ' :\python \libelsedirname '/usr/lib/pythonallsizes [for (thisdirsubsherefilesherein os walk(dirname)for filename in fileshereif filename endswith(py')fullname os path join(thisdirfilenamefullsize os path getsize(fullnameallsizes append((fullsizefullname)allsizes sort(pprint pprint(allsizes[: ]pprint pprint(allsizes[- :]find the largest python source file on the module import search path import sysospprint visited {allsizes [for srcdir in sys pathfor (thisdirsubsherefilesherein os walk(srcdir)thisdir os path normpath(thisdirif thisdir upper(in visitedcontinue elsevisited[thisdir upper()true for filename in fileshereif filename endswith(py')pypath os path join(thisdirfilenametrypysize os path getsize(pypathexceptprint('skipping'pypathallsizes append((pysizepypath)allsizes sort(pprint pprint(allsizes[: ]pprint pprint(allsizes[- :]sum columns in text file separated by commas filename 'data txtsums {for line in open(filename)cols line split(',' appendix dsolutions to end-of-part exercises
2,050
for (ixnumin enumerate(nums)sums[ixsums get(ix num for key in sorted(sums)print(key'='sums[key]similar to priorbut using lists instead of dictionaries for sums import sys filename sys argv[ numcols int(sys argv[ ]totals [ numcols for line in open(filename)cols line split(','nums [int(xfor in colstotals [( yfor (xyin zip(totalsnums)print(totalstest for regressions in the output of set of scripts import os testscripts [dict(script='test py'args='')dict(script='test py'args='spam')or glob script/args dir for testcase in testscriptscommandline '%(script) %(args)stestcase output os popen(commandlineread(result testcase['script'resultif not os path exists(result)open(result' 'write(outputprint('created:'resultelsepriorresult open(resultread(if output !priorresultprint('failed:'testcase['script']print(outputelseprint('passed:'testcase['script']build gui with tkinter (tkinter in xwith buttons that change color and grow from tkinter import use tkinter in import random fontsize colors ['red''green''blue''yellow''orange''white''cyan''purple'def reply(text)print(textpopup toplevel(part viiexceptions and tools
2,051
label(popuptext='popup'bg='black'fg=colorpack( config(fg=colordef timer() config(fg=random choice(colors)win after( timerdef grow()global fontsize fontsize + config(font=('arial'fontsize'italic')win after( growwin tk( label(wintext='spam'font=('arial'fontsize'italic')fg='yellow'bg='navy'relief=raisedl pack(side=topexpand=yesfill=bothbutton(wintext='press'command=(lambdareply('red'))pack(side=bottomfill=xbutton(wintext='timer'command=timerpack(side=bottomfill=xbutton(wintext='grow'command=growpack(side=bottomfill=xwin mainloop(similar to priorbut use classes so each window has own state information from tkinter import import random class mygui"" gui with buttons that change color and make the label grow ""colors ['blue''green''orange''red''brown''yellow'def __init__(selfparenttitle='popup')parent title(titleself growing false self fontsize self lab label(parenttext='gui 'fg='white'bg='navy'self lab pack(expand=yesfill=bothbutton(parenttext='spam'command=self replypack(side=leftbutton(parenttext='grow'command=self growpack(side=leftbutton(parenttext='stop'command=self stoppack(side=leftdef reply(self)"change the button' color at random on spam pressesself fontsize + color random choice(self colorsself lab config(bg=colorfont=('courier'self fontsize'bold italic')def grow(self)"start making the label grow on grow presses appendix dsolutions to end-of-part exercises
2,052
self grower(def grower(self)if self growingself fontsize + self lab config(font=('courier'self fontsize'bold')self lab after( self growerdef stop(self)"stop the button growing on stop pressesself growing false class mysubgui(mygui)colors ['black''purple'customize to change color choices mygui(tk()'main'mygui(toplevel()mysubgui(toplevel()mainloop(email inbox scanning and maintenance utility ""scan pop email boxfetching just headersallowing deletions without downloading the complete message ""import poplibgetpasssys mailserver 'your pop email server name herepop server net mailuser 'your pop email user name heremailpasswd getpass getpass('password for % ?mailserverprint('connecting 'server poplib pop (mailserverserver user(mailuserserver pass_(mailpasswdtryprint(server getwelcome()msgcountmboxsize server stat(print('there are'msgcount'mail messagessize 'mboxsizemsginfo server list(print(msginfofor in range(msgcount)msgnum + msgsize msginfo[ ][isplit()[ resphdrlinesoctets server top(msgnum get hdrs only print('-'* print('[%doctets=%dsize=% ](msgnumoctetsmsgsize)for line in hdrlinesprint(lineif input('print?'in [' '' ']part viiexceptions and tools
2,053
if input('delete?'in [' '' ']print('deleting'server dele(msgnumelseprint('skipping'finallyserver quit(input('bye 'get whole msg delete on srvr make sure we unlock mbox keep window up on windows cgi server-side script to interact with web browser #!/usr/bin/python import cgi form cgi fieldstorage(parse form data print("content-typetext/html\ "hdr plus blank line print(""print("reply page"html reply page print(""if not 'userin formprint("who are you?"elseprint("hello % !cgi escape(form['user'value)print(""database script to populate shelve with python objects see also shelve and pickle examples rec {'name'{'first''bob''last''smith'}'job'['dev''mgr']'age' rec {'name'{'first''sue''last''jones'}'job'['mgr']'age' import shelve db shelve open('dbfile'db['bob'rec db['sue'rec db close(database script to print and update shelve created in prior script import shelve db shelve open('dbfile'for key in dbprint(key'=>'db[key]bob db['bob'bob['age'+ appendix dsolutions to end-of-part exercises
2,054
db close(database script to populate and query mysql database from mysqldb import connect conn connect(host='localhost'user='root'passwd='xxxxxxx'curs conn cursor(trycurs execute('drop database testpeopledb'exceptpass did not exist curs execute('create database testpeopledb'curs execute('use testpeopledb'curs execute('create table people (name char( )job char( )pay int( ))'curs execute('insert people values (% % % )'('bob''dev' )curs execute('insert people values (% % % )'('sue''dev' )curs execute('insert people values (% % % )'('ann''mgr' )curs execute('select from people'for row in curs fetchall()print(rowcurs execute('select from people where name % '('bob',)print(curs descriptioncolnames [desc[ for desc in curs descriptionwhile trueprint('- row curs fetchone(if not rowbreak for (namevaluein zip(colnamesrow)print('% =% (namevalue)conn commit(save inserted records fetch and open/play file by ftp import webbrowsersys from ftplib import ftp socket-based ftp tools from getpass import getpass hidden password input if sys version[ =' 'input raw_input compatibility nonpassive false filename input('file?'dirname input('dir'or sitename input('site?'user input('user?'if not useruserinofo (elsefrom getpass import getpass force active mode ftp for serverfile to be downloaded remote directory to fetch from ftp site to contact use (for anonymous hidden password input part viiexceptions and tools
2,055
print('connecting 'connection ftp(sitenameconnection login(*userinfoconnection cwd(dirnameif nonpassiveconnection set_pasv(falseconnect to ftp site default is anonymous login xfer at time to localfile force active ftp if server requires print('downloading 'localfile open(filename'wb'local file to store download connection retrbinary('retr filenamelocalfile write connection quit(localfile close(print('playing 'webbrowser open(filename appendix dsolutions to end-of-part exercises
2,056
symbols character comments directives #characters - - (percent signformatting expression operator system shell prompt (parenthesescomprehensions and expression operators and statements and superclasses and tuples and (multiplicationoperator multiplying numbers repeating lists repeating strings (plusoperator adding numbers concatenating lists concatenating strings +in-place addition (comma) operator - operator - (colon) (semicolon) <(left-shiftoperator =(equivalenceoperator prompt about common usage mistakes symbol about function decorators and (square brackets) (backslashescape sequences and - multiline statements and (underscoreclass names module names name mangling and operator overloading showing name values (curly braces) abs built-in function absolute imports abstract superclasses - access-by-key databases and filesystems dictionary interfaces exploring interactively - iterations and object persistence and pickle module storing objects on updating objects accessor functions __add__ method addition operation all built-in function __all__ variable android platform annotations - - __annotations__ attribute we' like to hear your suggestions for improving our indexes send email to index@oreilly com
2,057
any built-in function anydbm module apply built-in function arbitrary arguments - arbitrary expressions arbitrary structures - argparse module arguments (see also keyword argumentsabout arbitrary - avoiding changes calculating lengths of call expressions and coding functions decorator - - - default values - - intersecting sequences example - matching - - positional - quiz questions and answers running script files with self shared references and - simulating multiple results simulating output parameters unpacking usage example - arithmeticerror class arrayslists and as extension for import/from statements ascii built-in function ascii character set about character code conversions encoding encoding and decoding usage example aspect-oriented programming assert statement about special-case handling triggering exceptions usage example assertionerror exception assignment statements about index augmented assignments - extended sequence unpacking list-unpacking assignments multiple-target assignments - quiz questions and answers sequence assignments - syntax patterns - tuple-unpacking assignments variable name rules - asterisk (*) atexit module attribute fetches about attribute name qualification and built-in types and - attributeerror exception attributes (see also specific types of attributesabout accessing assigning and deleting attribute tools built-in - data descriptors and - handling generically - inheritance and - - listing per object - managing - mapping to inheritance sources modules and - - name qualification for namespaces and operator overloading and - privacy considerations properties for - quiz questions and answers - referencing special class - string method calls and validating - augmented assignments - augmented classes - automatic memory management awk utility
2,058
backslash (\escape sequences and - multiline statements and backtrackingexception handlers and base classes baseexception class __bases__ attribute about inheritance and bdfl (benevolent dictator for life) benchmarking pystone py program quiz questions and answers timeit module - timing iteration - usage examples benevolent dictator for life (bdfl) big-endian format - bin built-in function binary files about - escape sequences and frozen executables storing data struct module and - text files and version considerations binary formatting binary notation - binary operator methods - bitwise operations - blank lines common usage mistakes statements and block strings - blocks of code delimiting - indenting - loop coding techniques - nesting - special case rules bom (byte order marker) - __bool__ method - booleans (bool typeabout operator overloading and - truth test and - version considerations bound methods - bounds checking for lists branching in if statements - break statement about nested loops and bsddb extension module built-in attributes - built-in exception classes about built-in categories default printing and state - built-in exceptions built-in object types about attribute fetches for - class decorators and common usage mistakes - comparison operations - core data types dictionaries (see dictionariesequality and - extending - files (see filesgeneral type categories - generation in - iteration and - lists (see listsmetaclasses and - numbers (see numbersobject flexibility references versus copies - strings (see stringstuples (see tuplestype hierarchies - built-in scope about - legb rule and __builtin__ module builtins module - byte code about - modules and - optimizing pvm and python versions and source changes and byte order marker (bom) - bytearray string type index
2,059
changing strings bytes built-in function bytes string type about - bytearray string type and encoded text making bytes objects method calls mixing string types pickle module and quiz questions and answers - sequence operations type and content mismatches language argument-passing model #define directive error checks #include directive memory address pointers while loops +language call expressions - __call__ method about - bound methods and - class decorators and class objects and function decorators and case considerations case conversion for strings variable name rules certificatecompletion - cgi fieldstorage class chaining exceptions - methods numeric comparisons - character code conversions character sets (see also ascii character setunicode character setchr built-in function circular references __class__ attribute about index coding exception classes comparing class instances exception type and inheritance and listing attributes in class trees class attributes about abstract superclasses and class gotchas - creating function decorators and instance attributes versus pseudoprivate - special usage examples class decorators about built-in types and coding - implementing - manager functions versus metaclasses and - - - multiple instances and singleton classes - state retention options tracing object interfaces - usage considerations class methods about counting instances - metaclass methods versus usage considerations - class statement about - decorators and general form inheritance and - local scope and metaclasses and methods and - modules and objects and properties for usage examples - classes about - augmented - class instances
2,060
closures versus coding class trees - coding gotchas - combining - customizing behavior - customizing constructors - decorators and - descriptors and dictionaries versus - docstrings and exception - explicit attributes and extending built-in types - functions and generators and - inheritance and - - instances (see instancesintercepting operators - - introspection tools - listing attributes in class trees - methods and - - mix-in - - modules and mro ordering name considerations namespaces and - nesting - new-style (see new-style classesobjects and - operator overloading persistence and polymorphism and - proxy (see proxy classesquiz questions and answers - scopes in singleton - storing objects in databases - subclasses (see subclassessuperclasses (see superclassestype object and - usage examples - - - user-defined version considerations classmethod built-in function client module closures (see factory functions__cmp__ method - code points codecs module about open method coding (see development considerationscohesion in functions in modules collections module namedtuple function ordereddict subclass colon (:) comma (,) command lines and files (see system command lines and filescommand-line arguments comments character #characters - statements and comparison operations built-in object types - dictionaries lists numbers - operator overloading and - recursive sets strings testing truth values - tuples version considerations compile built-in function compiled extensions completion certificate - complex built-in function complex numbers component coupling component integration composition about combining classes - oop considerations - compound object types compound statements (see also specific statementsindex
2,061
colon character common usage mistakes special case rules - - terminating timing comprehension variables comprehensions (see also list comprehensionsdictionary - - iterables versus - quiz questions and answers set - syntax summary - concatenating lists strings tuples virtual concatenation conflict resolutiondiamond inheritance trees - constants constructors class gotchas coding customizing - __init__ method and operator overloading and superclass __contains__ method - __context__ attribute context managers about - closing files and server connections decimals files implementing multiple - version considerations - contextlib module continuation lines in statements continue statement control flows exceptions and nesting control languages control-flow statements conversions case index for encodings fraction hexoctalbinary notation - integer mixed types storing objects in files - string - string types to converter tuple - to converter copy module core data types (see built-in object typescoupling component functions modules super built-in function - cpickle module cpython system about timeit module and - csv file format csv module curly braces } currency symbols - current working directory (cwd) cwd (current working directory) cx_freeze tool cyclesrecursive calls and cyclic data structures cyclic references cygwin system cython system data attributes data structures about arbitrary - built-in object types and cyclic dictionaries and empty data types (see object typesdatabase programming
2,062
databases and filesystemsdbm module __debug__ built-in variable debugging python code about - idle debugger string issues tools supporting with try statement decimal module decimals (decimal objectabout - context manager from_float method getcontext method localcontext method numeric accuracy in resetting precision temporarily setting precision globally decoding (see encoding and decodingdecorators (see also class decoratorsfunction decoratorsabout abstract superclasses and arguments and - - coding properties - defining encapsulation and macros versus manager functions versus managing calls and instances managing functions and classes - methods and - - nesting - private and public attributes - quiz questions and answers - range-testing for positional arguments - timing alternatives usage considerations - def statement about class statement and coding functions decorators and lambda expressions and name resolution and nesting runtime execution scope and default exception handler __del__ method about descriptors and managing attributes object destruction and - del statement __delattr__ method delegation about class gotchas function decorators and inheritance versus oop considerations - operator overloading and - proxy classes and __delete__ method deleting dictionary items list items delimiters blocks of code - statement __delitem__ method deprecation protocol for python depth-firstleft-to-right (dflrpath derived classes - descriptors about - attribute access and builtins routing mixin decorating methods with - inheritance and - management techniques compared managing attributes metaclasses and properties and - read-only slots and state information in - validating with - design patterns - destructor method - index
2,063
built-in type gotchas - class gotchas - code reuse - coding class decorators - coding class trees - coding constructors coding exception classes - coding exception details - coding function decorators - coding functions - - coding metaclasses - coding methods - coding strings - coding subclasses common coding gotchas - database programming development community eibti acronym - function gotchas - improvement suggestions - for larger projects - minimizing cross-file changes - minimizing global variables module coding - program execution rapid development cycle rapid prototyping dflr (depth-firstleft-to-rightpath diamond patterns about attribute searches inheritance search order - __dict__ attribute about listing attributes in class trees listing instance attributes - metaprogram example namespace dictionaries and namespaces and private attributes and slots and - usage example wrapper classes and dict built-in function dictionaries (dict objectabout - adding keys index alternate ways to make changing in place classes versus - clear method common operations comparison operations copy method data structures and deleting items dictionary views - - empty dictionaries fromkeys method get method has_key method indexing interface considerations items method iteration in - keys method keyword arguments lists versus literals mapping operations - missing keys - movie database example - mutable nature of nesting optimization in ordereddict subclass pop method popitem method quiz questions and answers sequence operations and setdefault method sorting keys - string formatting expressions type-specific methods - update method usage considerations - values method version considerations - viewitems method viewkeys method viewvalues method zip built-in function and
2,064
- dir built-in function about customizing version of as documentation source - inheritance and - inspecting namespaces directives directoriesfile precedence over - diretory walkers display formats generic display tool neutralizing difference with code - numeric print operations - distutils modules division operations about floor division - truncating division - version considerations - __ doc__ attribute - doctest module documentation comments about additional resources - dir built-in function - docstrings - help built-in function pydoc system - quiz questions and answers sphinx tool documentation strings about - modules and triple-quoted strings usage considerations dom parsing dot path syntax duck typing dynamic typing about objects and - quiz questions and answers references and - variables and - easter eggs ebcdic encoding eclipse ide eibti acronym - elementtree package else clause (loop blocks) - embedded programs empty data structures empty dictionaries empty lists empty strings empty tuples encapsulation about decorators and polymorphism and enclosing scope about function-related gotchas legb rule and nonlocal statement and - retaining state with defaults - state retention and encoding and decoding about - additional schemes ascii byte string literals character set declarations - converting ebcdic filenames non-ascii text - unicode - encodings module endianness - __enter__ method enumerate built-in function about iteration and usage example env program environment variables about - path pythonioencoding index
2,065
pythonstartup py_python py_python py_python tcl_library tk_library eoferror exception __eq__ method equality built-in object types - shared references and - testing truth values - value equality operators equivalence (==operator errno module error handling displaying errors and tracebacks exceptions and missing keys - scripts and testing inputs with try statements - escape sequences - etree package eval built-in function jump tables and strings and event notification exception class about as catchall user-defined exceptions and exception classes about - built-in - coding - custom data and behavior - custom print displays hierarchies in - quiz questions and answers version considerations exception handlers (see also specific statementsabout backtracking and default defining methods for - index interactive prompt and nesting - termination actions and exception variables exceptions (see also specific exceptions and specific statementsabout built-in catching - catching too little catching too much - chaining - class-based - coding details - common roles design tips and gotchas - errors versus propagating quiz questions and answers raising string-based usage considerations - user-defined exceptions module exec built-in function - execfile built-in function executable scripts #comment in windows - about env program executing programs (see program executionexercises part - - part ii - - part iii - - part iv - - part - - part vi - - part vii - __exit__ method explicit attributes exponentiation operation expression operators converting mixed types grouping with parentheses listed operator overloading
2,066
polymorphism and set operations and version considerations expressions (see also lambda expressionsabout arbitrary call - code examples expression operators - functions versus generator - indexing numbers in - objects and operator overloading and quiz questions and answers slice statements and - string formatting - variables and extended sequence unpacking about - for loops and extending built-in types about by embedding by subclassing - extension modules factorials factory functions about - generic - gotchas metaclasses and false value in python booleans and - - built-in scope and operator overloading and - fieldstorage class fifo (first-in-first-out) __file__ attribute files (file object) (see also binary filestext filesabout close method closing common operations context manager context managers flush method generating namespaces __init__ py files - inspecting iteration in - list comprehensions and literals minimizing cross-file changes - module filenames __next__ method open built-in function and precedence over directories - print operations and quiz questions and answers read method readline method readlines method seek method storing objects in files - tools supporting type-specific methods usage considerations - write method writelines method xreadlines method filesystemsaccess-by-key (see access-by-key databases and filesystemsfilter built-in function generator expressions versus iteration and list comprehensions and - filtering test results first-class object model first-in-first-out (fifo) float built-in function floating-point numbers (float typeabout as_integer_ratio method is_integer method try statements and floatingpointerror exception floor division - for statement about extended sequence unpacking index
2,067
general format iteration and list comprehensions and nested loops nesting - parallel traversals - quiz questions and answers range built-in function and recursion versus sequence scans sorting keys - terminating usage examples - format built-in function __format__ method formatting strings (see string formattingfractions (fraction objectabout conversions and mixed types from_float method numeric accuracy in fractions module freeze tool from statement about modules and namespace pollution and package imports and variables and from statement about - as extension copying names exec built-in function and import statement versus package imports and potential pitfalls - relative imports model and reload built-in function and - testing and frozen binaries frozenset built-in function function attributes - - function decorators about - adding arguments - coding - implementing index manager functions versus method blunders - method declaration and properties and state retention options - timing calls - tracing calls - usage considerations user-defined validating arguments - functional programming built-in functions for - classes closures - list comprehensions - functions (see also specific functionsabout - accessor annotations and - - anonymous - applying generically - *arg form - **args form - calling classes and coding - - cohesion in common pitfalls - coupling decorators and - defining design concepts - expressions versus factory - - first-class object model generator - - helper - intersecting sequences - - introspection tools **kargs form keyword arguments manager - mapping operations - metafunctions - methods and nesting - *pargs form polymorphism in
2,068
quiz questions and answers recursive - - scope considerations signaling conditions with unbound methods as functools module __future__ module garbage collection about exception variables and objects and - gc module __ge__ method generators about classes and - eibti acronym - functions versus expressions - generating scrambled sequences - iterables versus comprehensions - iteration and - - multithreading and __next__ method quiz questions and answers recursive calls send method yield versus return statement - __get__ method about descriptors and managing attributes getattr built-in function __getattr__ method about - attribute fetches and attribute interception and class decorators and - emulating privacy __getattribute__ method comparison implementation alternatives - intercepting built-in operation attributes - managing attributes - metaclasses and new-style classes and validating with - wrapper classes and __getattribute__ method about attribute fetches and __getattr__ method comparison intercepting built-in operation attributes - managing attributes - new-style classes and recursive looping and validating with __getitem__ method about - index iteration and - membership and - user defined class and user defined iterables and getopt module __getslice__ method global scope about legb rule and state retention and global statement about coding functions global variables alternatives for accessing minimizing modules and go to statements graphical user interface (gui) __gt__ method gui (graphical user interface) hash character (#comments directives help built-in function about pydoc system and - helper functions - hex built-in function __hex__ method hexadecimal notation index
2,069
string escape sequences html reports - - command-line argument __iadd__ method - icon clicks about limitations - windows platform - id built-in function ides (integrated development environmentsabout alternative - idle user interface about advanced tools basic usage - common usage mistakes - multiline block strings startup details usability features if (elif/elsestatement about basic examples filter clauses general format interactive loops example missing keys tests - multiway branching - quiz questions and answers terminating if/else ternary expression - immutable objects about changing in place constraints with immutable sequences imp reload function - implementation-related object types implicit assignments __import__ built-in function import statement (see also package importsabout - - as extension as one-time occurrence common usage mistakes index dot path syntax enabling context managers as executable statement from statement versus importing modules by name string packages and potential pitfalls - process overview - scopes versus import this command importlib import_module function in operator dictionaries and sets and strings and in-place change operations avoiding mutable argument changes dictionaries and expression statements and immutable objects and lists and - scope and shared references and - indenting blocks of code - common usage mistakes statements - __index__ method indexerror exception indexing dictionaries lists - operator overloading and - strings - tuples indirect function calls inheritance (see also multiple inheritanceabout - abstract superclasses - assignment and attribute tree construction attributes and - - built-ins and class interface techniques - classes and - - delegation versus descriptors and -
2,070
instances and mapping attributes to sources - metaclasses and - multiple namespaces and oop considerations - specializing inherited methods subclasses and type object and usage examples __init__ method about attribute validation and class decorators and coding multiple constructors and inheritance and metaclasses and __init__ py files - - input built-in function input trick on windows prompting for test inputs usage example installing python - instance attributes class attributes versus creating emulating privacy for function decorators and listing with __dict__ - usage examples instance methods instances about about and counting with class methods - counting with static methods creating - decorators managing inheritance and metaclasses and - - multiple - namespaces and raising with raise statement type object and - usage examples - int built-in function about alternatives to interactive loops example integers (int typeabout bit_length method converting to strings hexoctalbinary notation - integer keys precision in integrated development environments (idesabout alternative - interactive loops - interactive prompt about code directories common usage mistakes - exception handling and as experimenting tool new windows options printing values at prompts and comments and recursive reload example running code interactively scope and starting interactive sessions system path terminating compound statements as testing tool internet scripting interpreters (see python interpreterintrospection tools classes - functions ios platform ironpython system is operator isinstance built-in function iter built-in function about - user defined iterables and __iter__ method about coding example - iterable objects and - membership and - user defined classes and iteration index
2,071
additional contexts - additional information built-in functions and - built-in types supported - comprehensions versus - in dictionaries - in files - generators and - in lists loop coding techniques - - manual - multiple versus single pass one-shot operator overloading and - quiz questions and answers timing iteration alternatives - in tuples version considerations - jit (just-in-timecompiler json format about storing objects in - json module jump tables just-in-time (jitcompiler jython system keyboardinterrupt exception keys (see also access-by-key databases and filesystemsaccess-by-key databases and filesystems dictionary integer-based mapping values to missing - sorting - string method calls and tuple-based usage notes keyword arguments index about - abstract superclasses and decorators and homegrown timing module mapping operations and modifying sort behavior printing example usage examples version considerations - kiss principle - komodo ide lambda expressions about - callbacks and coding functions - def statement and inline callbacks multiway branching and nesting scope and unpacking arguments usage example language featuresenabling in modules last-in-first-out (lifo) latin- character set __le__ method left-shift (<<operator legb rule built-in scope and name resolution - namespaces and nested classes - len built-in function dictionaries and sequence shufflers strings strings and __len__ method - lexical scoping lifo (last-in-first-out) linux platform configuring python frozen binaries and gui support icon clicks idle startup details installing python
2,072
working directory list built-in function about converting objects to lists iteration protocol and type customization and list comprehensions about - - extended syntax - files and filter built-in function and - for statement and functional tools - generator expressions and map built-in function versus matrixes and - range built-in function and usage considerations - list-unpacking assignments lists (list objectabout - append method bounds checking changing in place - common operations comparison operations concatenating copy method count method deleting items dictionaries versus empty lists extend method index method indexing - insert method iteration in literals matrixes and mutable nature of nesting pop method quiz questions and answers remove method repeating reverse method sequence operations slicing - sort method - tuples versus type-specific methods - type-specific operations literals about built-in object type examples byte string dictionary file hexoctalbinary notation - integer objects - list numeric - set string - - tuple unicode little-endian format - local scope about class statement and legb rule and local variables logical operations lookuperror class loops (see also specific statementsattribute interception methods and breaking out of coding techniques for - else clause - function-related gotchas interactive - iterations and - - nesting - - quiz questions and answers recursion versus __lt__ method mac os platform frozen binaries and gui support icon clicks idle startup details installing python index
2,073
system shell prompt working directory macrosdecorators versus __main__ module - manager functions - map built-in function benchmarking generator expressions versus - homegrown timing module and - iteration and - list comprehensions versus loop coding techniques and - parallel traversals - timing calls example version considerations mapattrs module mapping operations about dictionaries and - functions and - mapping attributes to inheritance sources - mapping values to keys missing keys - math module about built-in numeric tools floor function trunc function mathematical operations about division - expression operators nesting matlab numeric programming system matrixes list comprehensions and - nested lists and max built-in function membership in operator and operator overloading and - memory management automatic garbage collection generator expressions and index storing strings metaclasses about built-in object types and - call pattern issues and class decorators and - - - class statement and coding - customizing construction and initialization declaring - descriptors and factory functions and inheritance and - instances and - - methods in - model overview - operator overloading and - superclasses versus type object and usage considerations - usage examples - version considerations - metafunctions - metaprograms - method resolution order (see mromethods (see also operator overloadingabout adding - - attribute fetches augmenting - binary operator - bound - chaining coding - decorators and - - dictionary - exception handler - expressions and file functions and instance list - metaclass - number-specific
2,074
scopes in static string - - string formatting - superclass constructors tuple - unbound - underscores in usage examples microthreads min built-in function missing keys - mix-in classes - - __mod__ method module search path about - changing - lookup rules summary running modules modules (see also from statementimport statementpackagesabout - as extension for import/from statements attributes and - - byte code files - classes and common usage mistakes copying names - creating - data hiding in design concepts - dual mode code example - embedding calls enabling future language features exec built-in function and extension importing mixed usage modes - module search path - name clashes namespaces and - as objects - potential gotchas - programs and python program architecture and - quiz questions and answers reloading - - - scope considerations statements and usage considerations - modulus operator mod_python package mongodb database movie database example - mro (method resolution orderabout - new-style classes and super built-in function and __mro__ attribute about - inheritance and multiline block strings - multiline statements (see compound statementsmultiple context managers - multiple inheritance about class gotchas - diamond patterns of - mix-in classes and - super built-in function and - - multiple instances - multiple-target assignments - multiplication (*operator multiplying numbers repeating lists repeating strings multithreading multiway branching in if statements - mutable objects avoiding argument changes changing in modules default values for arguments dictionaries as function gotchas - lists as __name__ attribute about functions and index
2,075
metaprogram example mixed usage modes - modules and preset value name collisions name mangling name resolution - named tuples - namespace declarations namespace dictionaries about - __dict__ attribute slots and - namespace package model about file precedence in - nesting semantics - usage examples - namespaces about assigning names - attribute names and classes and __dict__ attribute files generating inheritance and instances and legb rule and - minimizing namespace pollution modules and - nested classes and - nesting scope and naming conventions and rules classes legb rule - - scope and for variables - _x name prefix __ne__ method nesting blocks of code - classes - control flows decorators - def statement dictionaries index exception handlers - for statement - functions - lambda expressions lists loops - - mathematical operations namespace packages namespaces string formatting try/except/finally statement tuples netbeans ide __new__ method new-style classes about - attribute tools changes in - class tools - extensions to - mro and multiple inheritance in properties - slots - next built-in function - __next__ method about file iterators and generator functions and iterable objects and - user defined iterables and none object nonlocal statement about - boundary cases coding functions enclosing scope and - state retention options - version considerations - normal versus chained comparisons - notimplemented object notimplementederror exception numbers about - bitwise operations - booleans (see booleansbuilt-in tools -
2,076
complex decimals (see decimalsdivision operation - expression operators - in expressions - floating-point (see floating-point numbersfractions (see fractionsintegers (see integersnumeric display formats numeric extensions numeric literals - quiz questions and answers rational sequence operations sets (see setsin variables - numeric programming numpy numeric programming extension about customer base matrix support object persistence (see also specific modulesabout classes and database programming and implementing object relational mappers (orms) object serialization - object superclass - object types built-in (see built-in object typescompound dictionaries (see dictionariesdynamic typing - files (see filesgeneral type categories - implementation-related lists (see listsnumbers (see numbersquiz questions and answers strings (see stringsstrong typing testing - tuples (see tuplesobject-oriented programming (see oopobjects (see also immutable objectsmutable objectsabout attributes for - classes and - dynamic typing - expressions and garbage collection iterable - listing attributes per - methods as - modules as - optimizing reference counters shared references and - slice strong typing type designators updating on shelves variables and oct built-in function __oct__ method octal notation - oop (object-oriented programmingabout attribute inheritance - bound and unbound methods - class gotchas - classes and instances code reuse - coding class trees - coding classes - - composition and - by customization decorators and metaclasses - delegation and - exception classes - extending built-in types - generic object factories - important concepts in inheritance and - kiss principle metaclasses method calls mix-in classes - new-style classes - operator overloading - polymorphism and index
2,077
pseudoprivate class attributes - python and quiz questions and answers realistic example of classes - state information static and class methods - super built-in function - open built-in function customizing - file processing and version considerations windows platform and operations (see specific operationsoperator module operator overloading about attributes and - - binary operator methods - boolean tests and - call expressions and - common methods - comparisons and - constructors and expressions delegation and display formats and double underscores and indexing and slicing - iteration and - membership and - metaclasses and - object destruction - polymorphism and quiz questions and answers string representation and - super built-in function and usage considerations usage examples - - validating methods operator precedence optimizing objects about byte code files execution optimization tools - optparse module __or__ method or operator ord built-in function ordereddict subclass ordering (see sorting index orms (object relational mappers) os module descriptor files _exit function popen function system function walk function oserror class overflowerror exception package imports about - __all__ variable from versus import statement __init__ py files - relative imports model - search path settings usage considerations - usage example - version considerations packages about __all__ variable namespace package model package imports - quiz questions and answers relative imports model - search path settings parameters (see argumentsparentheses comprehensions and expression operators and statements and superclasses and tuples and parrot project parsing text in strings pass statement - passing-arguments-by-pointer passing-arguments-by-value path environment variable about env program and new windows options setting paths
2,078
- package imports package search paths recording for recursive calls pattern matching in strings about re module and pdb command-line debugger pep (python enhancement proposal) percent sign (%formatting expression operator system shell prompt performance considerations (see also benchmarkinglist comprehensions mro and program execution python alternatives slots perl programming language permutations - persistence (see object persistencepeterstim pexpect system pickle module about object persistence and object serialization and - persistence and storing objects plus (+operator adding numbers concatenating lists concatenating strings pmw extension package polymorphism about classes and - in functions oop considerations operator overloading and testing exception types portability positional arguments - pow built-in function pprint module pformat function pprint function usage considerations precedence rules print built-in function - - print operations (see also print statementabout built-in exception classes and - completion certificate - custom displays display formats - expression statements and file object methods and print built-in function - print stream redirection - quiz questions and answers standard output stream version considerations - - version-neutral - print statement about - common usage mistakes debugging code and numeric display formats and private attributes - procedures (see functionsprofile module program architecture about conceptual hierarchy modules and - program execution about alternative ides - alternative launch options - byte code compilation and - clicking file icons - debugging code - development considerations embedding calls exec built-in function and - frozen binaries future possibilities idle user interface - interactive prompt - interpreters and - model variations in - index
2,079
optimization tools - performance considerations programmer' perspective - pvm and quiz questions and answers - selecting from options system command lines and files - text editor launch options unix-style scripts - program units (see also classesfunctionsmodulesprogramming python (lutz) programs about metaprograms - modules and prompts (see interactive promptsystem promptproperties about - attribute - class statement coding with decorators - descriptors and - validating with - property built-in function prototyping systems proxy classes (wrappersabout - decorators installing delegation and pseudoprivate class attributes about - larger projects and public attributes and psf (python software foundation) pstats module psyco system pth file extension public attributes - pvm (python virtual machine) py file extension about common usage mistakes imported files and py app tool py exe tool index pyc file extension __pycache__ subdirectory pychecker tool pydev ide pydoc system about changing colors in help function - html reports - version considerations - pydoc py script pygame toolkit pyinstaller tool pylint system pymongo interface pyo file extension pypy system about benchmarking performance considerations timeit module and - pyrolog interpreter pyserial extension pysolfc program pystone py program python enhancement proposal (pep) python interpreter about additional information alternatives to byte code and - configuring - development considerations installing - locating with env program performance considerations pvm and python programming language additional information advantages of - common applications of - compared to other languages - compared to perl development community execution speed future directions - implementation alternatives - new windows options
2,080
pillars of programming portability quiz questions and answers - scripting and technical strengths - tools supporting - tradeoffs using user base - version considerations (see version considerations for pythonpython software foundation (psf) python virtual machine (pvm) pythonioencoding environment variable pythonlauncher pythonpath environment variable about module search paths package search paths pydoc html reports windows platform and pythonstartup environment variable pythonwin ide pyunit tool pyw file extension py_python environment variable py_python environment variable py_python environment variable queue module queues best-first searches fifo recursion versus quiz questions and answers python & session - program execution program execution - object types numbers dynamic typing strings lists and dictionaries tuplesfilesand everything else statements assignmentsexpressionsand prints if tests and syntax rules while and for loops iterations and comprehensions documentation functions scopes - arguments functions comprehensions and generators benchmarking modules modules module packages modules oop classes classes - classes operator overloading classes classes exceptions exceptions exception classes exceptions unicode and byte strings attributes - decorators - quotation marks interchangeable multiline block strings - strings in file processing mode __radd__ method - raise statement about built-in exceptions and chaining exceptions - from clause - index
2,081
raising exceptions raising instances signaling conditions with version considerations random module about generator example range built-in function counter loops iteration and list comprehensions and loop coding techniques and - nonexhaustive traversals sequence scans sequence shufflers timing calls example rapid development cycle rational numbers raw_input built-in function re module about findall function match function pattern matching and search function read-only descriptors recursive comparisons recursive functions about coding alternatives from statement and generators and handling arbitrary structures - loops versus reloaders - summation with usage examples reduce built-in function reference counters references (see also shared referencesabout assignments and attribute circular copies versus - cyclic dynamic typing and - index string method calls weak relative imports model about - absolute imports versus lookup rules summary pitfalls of - scope of usage considerations - usage examples - version considerations reload built-in function about - - common usage mistakes from statement and - usage examples - repetition as programming pillar in strings in tuples usage considerations repr built-in function about display formats string formatting method calls and version considerations __repr__ method about - custom print displays inheritance and print display example - recursive looping and reserved words restructuredtext markup language return statement about coding functions function gotchas returning multiple values yield statement versus - reversed built-in function rias (rich internet applications) rich internet applications (rias) __rmod__ method round built-in function running programs (see program executions sax parsing
2,082
scipy programming extension scopes about - accessing global variables builtins module - comprehension variables and function-related gotchas global statement imports versus legb rule and - in methods and classes minimizing cross-file changes - minimizing global variables modules and name resolution and - nested functions and - nonlocal statement - quiz questions and answers - relative imports model try/except statement and usage example screen scraping technique scripts and scripting about common usage mistakes error handling executable - internet launching scripts with icon clicks - modules and python support running with arguments terminating compound statements timeit module and - timing script writing scripts search path modules - - packages selection as programming pillar self argument about coding constructors lambda callbacks and static methods and usage considerations semicolon (;) sentinel value sequence assignments about - advanced patterns - sequence operations bytes string type dictionaries and generating scrambled sequences - iteration and lists loop coding techniques - numbers statement execution strings - sequences about escape - intersecting - - list as programming pillar repeating string tuple server connectionsclosing set built-in function set comprehensions - __set__ method about descriptors and managing attributes set notation setattr built-in function __setattr__ method about - attribute assignments and emulating privacy private attributes and recursive looping and __setitem__ method - sets about - comparison operations copy method creating dictionary views and frozen immutable constraints literals index
2,083
__setslice__ method shadowing shared references about - arguments and - augmented assignments and equality and - in-place changes and - multiple-target assignments and shed skin system shell tools and commands - (see also system command lines and filesshelve module about dictionary interfaces and exploring shelves interactively - object persistence and open function pickle module and - storing objects on database updating objects shelves (see access-by-key databases and filesystemssingleton classes - slice expressions slice objects slicing lists - nonexhaustive traversals operator overloading and - strings - tuples slots about descriptors and example impacts of handling generically - managing attributes namespace dictionaries and - private attributes and speed considerations superclasses and usage rules socket module sorted built-in function about dictionaries and iteration and index lists and tuples and sorting keys - lists - version considerations source code about timestamps in spaces versus tabs sphinx tool sql database api square brackets ] square roots stack traces stackless python stacks inspecting - lifo limiting depth of recursion versus standard error stream (stderr) standard input stream (stdin) standard library about launch options standard output stream (stdout) state information about built-in exception classes and - class decorators and in descriptors - factory functions and function attributes and function decorators and - generator functions nonlocal statement and - recursive functions and validating with descriptors and - statements about assignment - colon character and common usage mistakes compound (see compound statementscontinuation lines in control-flow delimiting
2,084
indenting - interactive loops example - listed - modules and parentheses and python syntax model - quiz questions and answers semicolon and special case rules - - syntax rules - terminating version considerations static methods about alternatives for counting instances usage considerations - version considerations - staticmethod built-in function - steps in slicing stopiteration exception storing objects and data binary data class building example - class gotchas in files - in json format - pickle module on shelve database strings struct module str built-in function about display formats string formatting method calls and usage example version considerations __str__ method about - custom print displays inheritance and print display example - str string type about - converting encoded text re module and text files and unicode literals version considerations stream redirection strides in slicing string formatting about converting integers to strings expressions technique - literals method calls technique - nesting type codes - string module about - relative imports examples - strings (str objectabout - __add__ method alternate ways to code backslash characters - casefold method changing - coding - common operations - comparison operations concatenating converting - debugging decode method documentation - empty strings encode method endswith method exceptions based on find method format method - formatting (see string formattinggarbage collection and immutable importing modules by name string indexing - isdigit method join method literals - - lower method multiline block strings - index
2,085
operator overloading and - parsing text pattern matching quiz questions and answers repeating replace method rstrip method sequence operations - slicing - split method tool changes - type and content mismatches type-specific methods - unicode - - upper method version considerations - - strong typing struct module - __sub__ method subclasses about class interface techniques - coding customizing behavior - extending built-in types - inheritance and type object and subprocess module substitution operations in string formatting sum built-in function super built-in function about basic usage and tradeoffs - debates about - multiple inheritance and - - operator overloading and runtime class changes summary of version considerations superclasses about abstract - class gotchas index class interface techniques - constructor methods customizing inheritance and metaclasses versus multiple inheritance and operator overloading methods and parentheses and slots and traditional forms sys module argv attribute excepthook function exc_info function - exit function file name settings getrecursionlimit function modules dictionary path list platform attribute setrecursionlimit function stderr attribute stdin attribute stdout attribute - system command lines and files about - common usage mistakes running files with command lines running in python - starting interactive sessions system shell prompt timeit module and usage variations writing scripts system shell prompt about running files systemexit exception systeminfo command systems programming - command-line flag tabs versus spaces tcl_library environment variable termination actions about - default exception handler and
2,086
try/finally statement and - - with/as statement and testing error handling - filtering results from statement and interactive prompt and list comprehensions and - for missing keys with __name__ attribute for positional arguments - processes - reloading variants timing calls example truth values - - type - text editor launch options text files about - binary files and creating unicode - - version considerations _thread module threading module to converter time module about clock function homegrown timing module and perf_counter function process_time function time function timeit module about - benchmark and script - other examples repeat function setup code timestamps in source code timing calls with function decorators timing iterations alternatives for - timeit module - timsort algorithm tkinter gui toolkit about callbacks and common usage mistakes configuring python and idle and keyword arguments and lambda callbacks quit function testing reloading variants tk_library environment variable traceback module traceback objects translation (see encoding and decodingtriple quotes - true value in python booleans and - - built-in scope and operator overloading and - truncating division - try statement about - catching built-in exceptions clauses supported - debugging with default behavior wrapping statements with try/except statement about catching exceptions error handling - nesting - scopes and try/except/else statement - try/except/finally statement - - try/finally statement about closing files and server connections closing files example termination actions - - -tt command-line flag tuple built-in function tuple-unpacking assignments - tuples about - assignments and index
2,087
python is an easy to learnpowerful programming language it has efficient high-level data structures and simple but effective approach to object-oriented programming python' elegant syntax and dynamic typingtogether with its interpreted naturemake it an ideal language for scripting and rapid application development in many areas on most platforms the python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the python web sitesame site also contains distributions of and pointers to many free third party python modulesprograms and toolsand additional documentation the python interpreter is easily extended with new functions and data types implemented in or +(or other languages callable from cpython is also suitable as an extension language for customizable applications this tutorial introduces the reader informally to the basic concepts and features of the python language and system it helps to have python interpreter handy for hands-on experiencebut all examples are self-containedso the tutorial can be read off-line as well for description of standard objects and modulessee library-index reference-index gives more formal definition of the language to write extensions in or ++read extending-index and -api-index there are also several books covering python in depth this tutorial does not attempt to be comprehensive and cover every single featureor even every commonly used feature insteadit introduces many of python' most noteworthy featuresand will give you good idea of the language' flavor and style after reading ityou will be able to read and write python modules and programsand you will be ready to learn more about the various python library modules described in library-index the glossary is also worth going through contents
2,088
contents
2,089
one whetting your appetite if you do much work on computerseventually you find that there' some task you' like to automate for exampleyou may wish to perform search-and-replace over large number of text filesor rename and rearrange bunch of photo files in complicated way perhaps you' like to write small custom databaseor specialized gui applicationor simple game if you're professional software developeryou may have to work with several / ++/java libraries but find the usual write/compile/test/re-compile cycle is too slow perhaps you're writing test suite for such library and find writing the testing code tedious task or maybe you've written program that could use an extension languageand you don' want to design and implement whole new language for your application python is just the language for you you could write unix shell script or windows batch files for some of these tasksbut shell scripts are best at moving around files and changing text datanot well-suited for gui applications or games you could write / ++/java programbut it can take lot of development time to get even first-draft program python is simpler to useavailable on windowsmac os xand unix operating systemsand will help you get the job done more quickly python is simple to usebut it is real programming languageoffering much more structure and support for large programs than shell scripts or batch files can offer on the other handpython also offers much more error checking than candbeing very-high-level languageit has high-level data types built insuch as flexible arrays and dictionaries because of its more general data types python is applicable to much larger problem domain than awk or even perlyet many things are at least as easy in python as in those languages python allows you to split your program into modules that can be reused in other python programs it comes with large collection of standard modules that you can use as the basis of your programs -or as examples to start learning to program in python some of these modules provide things like file /osystem callssocketsand even interfaces to graphical user interface toolkits like tk python is an interpreted languagewhich can save you considerable time during program development because no compilation and linking is necessary the interpreter can be used interactivelywhich makes it easy to experiment with features of the languageto write throw-away programsor to test functions during bottom-up program development it is also handy desk calculator python enables programs to be written compactly and readably programs written in python are typically much shorter than equivalent cc++or java programsfor several reasonsthe high-level data types allow you to express complex operations in single statementstatement grouping is done by indentation instead of beginning and ending bracketsno variable or argument declarations are necessary python is extensibleif you know how to program in it is easy to add new built-in function or module to the interpretereither to perform critical operations at maximum speedor to link python programs to libraries that may only be available in binary form (such as vendor-specific graphics libraryonce you
2,090
are really hookedyou can link the python interpreter into an application written in and use it as an extension or command language for that application by the waythe language is named after the bbc show "monty python' flying circusand has nothing to do with reptiles making references to monty python skits in documentation is not only allowedit is encouragednow that you are all excited about pythonyou'll want to examine it in some more detail since the best way to learn language is to use itthe tutorial invites you to play with the python interpreter as you read in the next the mechanics of using the interpreter are explained this is rather mundane informationbut essential for trying out the examples shown later the rest of the tutorial introduces various features of the python language and system through examplesbeginning with simple expressionsstatements and data typesthrough functions and modulesand finally touching upon advanced concepts like exceptions and user-defined classes whetting your appetite
2,091
two using the python interpreter invoking the interpreter the python interpreter is usually installed as /usr/local/bin/python on those machines where it is availableputting /usr/local/bin in your unix shell' search path makes it possible to start it by typing the commandpython to the shell since the choice of the directory where the interpreter lives is an installation optionother places are possiblecheck with your local python guru or system administrator ( /usr/local/python is popular alternative location on windows machinesthe python installation is usually placed in :\program files\python \though you can change this when you're running the installer to add this directory to your pathyou can type the following command into the command prompt in dos boxset path=%path%; :\program files\python typing an end-of-file character (control- on unixcontrol- on windowsat the primary prompt causes the interpreter to exit with zero exit status if that doesn' workyou can exit the interpreter by typing the following commandquit(the interpreter' line-editing features include interactive editinghistory substitution and code completion on systems that support readline perhaps the quickest check to see whether command line editing is supported is typing control- to the first python prompt you get if it beepsyou have command line editingsee appendix interactive input editing and history substitution for an introduction to the keys if nothing appears to happenor if ^ is echoedcommand line editing isn' availableyou'll only be able to use backspace to remove characters from the current line the interpreter operates somewhat like the unix shellwhen called with standard input connected to tty deviceit reads and executes commands interactivelywhen called with file name argument or with file as standard inputit reads and executes script from that file second way of starting the interpreter is python - command [argwhich executes the statement(sin commandanalogous to the shell' - option since python statements often contain spaces or other characters that are special to the shellit is usually advised to quote command in its entirety with single quotes some python modules are also useful as scripts these can be invoked using python - module [argwhich executes the source file for module as if you had spelled out its full name on the command line when script file is usedit is sometimes useful to be able to run the script and enter interactive mode afterwards this can be done by passing - before the script on unixthe python interpreter is by default not installed with the executable named pythonso that it does not conflict with simultaneously installed python executable
2,092
all command line options are described in using-on-general argument passing when known to the interpreterthe script name and additional arguments thereafter are turned into list of strings and assigned to the argv variable in the sys module you can access this list by executing import sys the length of the list is at least onewhen no script and no arguments are givensys argv[ is an empty string when the script name is given as '-(meaning standard input)sys argv[ is set to '-when - command is usedsys argv[ is set to '-cwhen - module is usedsys argv[ is set to the full name of the located module options found after - command or - module are not consumed by the python interpreter' option processing but left in sys argv for the command or module to handle interactive mode when commands are read from ttythe interpreter is said to be in interactive mode in this mode it prompts for the next command with the primary promptusually three greater-than signs ()for continuation lines it prompts with the secondary promptby default three dots the interpreter prints welcome message stating its version number and copyright notice before printing the first promptpython python (defaultsep : : [gcc on linux type "help""copyright""creditsor "licensefor more information continuation lines are needed when entering multi-line construct as an exampletake look at this if statementthe_world_is_flat true if the_world_is_flatprint("be careful not to fall off!"be careful not to fall offfor more on interactive modesee interactive mode the interpreter and its environment source code encoding by defaultpython source files are treated as encoded in utf- in that encodingcharacters of most languages in the world can be used simultaneously in string literalsidentifiers and comments -although the standard library only uses ascii characters for identifiersa convention that any portable code should follow to display all these characters properlyyour editor must recognize that the file is utf- and it must use font that supports all the characters in the file to declare an encoding other than the default onea special comment line should be added as the first line of the file the syntax is as follows-*codingencoding -*where encoding is one of the valid codecs supported by python using the python interpreter
2,093
for exampleto declare that windows- encoding is to be usedthe first line of your source code file should be-*codingcp -*one exception to the first line rule is when the source code starts with unix "shebangline in this casethe encoding declaration should be added as the second line of the file for example#!/usr/bin/env python -*codingcp -* the interpreter and its environment
2,094
using the python interpreter
2,095
three an informal introduction to python in the following examplesinput and output are distinguished by the presence or absence of prompts and )to repeat the exampleyou must type everything after the promptwhen the prompt appearslines that do not begin with prompt are output from the interpreter note that secondary prompt on line by itself in an example means you must type blank linethis is used to end multi-line command many of the examples in this manualeven those entered at the interactive promptinclude comments comments in python start with the hash character#and extend to the end of the physical line comment may appear at the start of line or following whitespace or codebut not within string literal hash character within string literal is just hash character since comments are to clarify code and are not interpreted by pythonthey may be omitted when typing in examples some examplesthis is the first comment spam and this is the second comment and now thirdtext "this is not comment because it' inside quotes using python as calculator let' try some simple python commands start the interpreter and wait for the primary prompt(it shouldn' take long numbers the interpreter acts as simple calculatoryou can type an expression at it and it will write the value expression syntax is straightforwardthe operators +-and work just like in most other languages (for examplepascal or )parentheses (()can be used for grouping for example * ( * division always returns floating point number the integer numbers ( have type intthe ones with fractional part ( have type float we will see more about numeric types later in the tutorial
2,096
division (/always returns float to do floor division and get an integer result (discarding any fractional resultyou can use the /operatorto calculate the remainder you can use % classic division returns float / floor division discards the fractional part the operator returns the remainder of the division result divisor remainder with pythonit is possible to use the *operator to calculate powers * * squared to the power of the equal sign (=is used to assign value to variable afterwardsno result is displayed before the next interactive promptwidth height width height if variable is not "defined(assigned value)trying to use it will give you an errorn try to access an undefined variable traceback (most recent call last)file ""line in nameerrorname 'nis not defined there is full support for floating pointoperators with mixed type operands convert the integer operand to floating point in interactive modethe last printed expression is assigned to the variable this means that when you are using python as desk calculatorit is somewhat easier to continue calculationsfor exampletax price price tax price round( this variable should be treated as read-only by the user don' explicitly assign value to it -you would create an independent local variable with the same name masking the built-in variable with its magic behavior since *has higher precedence than -- ** will be interpreted as -( ** and thus result in - to avoid this and get you can use (- )** an informal introduction to python
2,097
in addition to int and floatpython supports other types of numberssuch as decimal and fraction python also has built-in support for complex numbersand uses the or suffix to indicate the imaginary part ( + jstrings besides numberspython can also manipulate stringswhich can be expressed in several ways they can be enclosed in single quotes ('or double quotes ("with the same result can be used to escape quotes'spam eggssingle quotes 'spam eggs'doesn\'tuse \to escape the single quote "doesn' "doesn'tor use double quotes instead "doesn' '"yes,they said '"yes,they said "\"yes,\they said '"yes,they said '"isn\' ,they said '"isn\' ,they said in the interactive interpreterthe output string is enclosed in quotes and special characters are escaped with backslashes while this might sometimes look different from the input (the enclosing quotes could change)the two strings are equivalent the string is enclosed in double quotes if the string contains single quote and no double quotesotherwise it is enclosed in single quotes the print(function produces more readable outputby omitting the enclosing quotes and by printing escaped and special characters'"isn\' ,they said '"isn\' ,they said print('"isn\' ,they said '"isn' ,they said 'first line \nsecond line \ means newline without print()\ is included in the output 'first line \nsecond line print(swith print()\ produces new line first line second line if you don' want characters prefaced by to be interpreted as special charactersyou can use raw strings by adding an before the first quoteprint(' :\some\name'here \ means newlinec:\some ame print( ' :\some\name'note the before the quote :\some\name string literals can span multiple lines one way is using triple-quotes""""or ''''end of lines are automatically included in the stringbut it' possible to prevent this by adding at the end of the line the following example unlike other languagesspecial characters such as \ have the same meaning with both single ('and double ("quotes the only difference between the two is that within single quotes you don' need to escape (but you have to escape \'and vice versa using python as calculator
2,098
print("""usagethingy [options- - hostname """display this usage message hostname to connect to produces the following output (note that the initial newline is not included)usagethingy [options- - hostname display this usage message hostname to connect to strings can be concatenated (glued togetherwith the operatorand repeated with * times 'un'followed by 'ium 'un'ium'unununiumtwo or more string literals ( the ones enclosed between quotesnext to each other are automatically concatenated 'py'thon'pythonthis feature is particularly useful when you want to break long stringstext ('put several strings within parentheses 'to have them joined together 'text 'put several strings within parentheses to have them joined together this only works with two literals thoughnot with variables or expressionsprefix 'pyprefix 'thoncan' concatenate variable and string literal syntaxerrorinvalid syntax ('un 'iumsyntaxerrorinvalid syntax if you want to concatenate variables or variable and literaluse +prefix 'thon'pythonstrings can be indexed (subscripted)with the first character having index there is no separate character typea character is simply string of size oneword 'pythonword[ character in position 'pword[ character in position 'nindices may also be negative numbersto start counting from the right an informal introduction to python
2,099
word[- 'nword[- 'oword[- 'plast character second-last character note that since - is the same as negative indices start from - in addition to indexingslicing is also supported while indexing is used to obtain individual charactersslicing allows you to obtain substringword[ : 'pyword[ : 'thocharacters from position (includedto (excludedcharacters from position (includedto (excludednote how the start is always includedand the end always excluded this makes sure that [:is[ :is always equal to sword[: word[ :'pythonword[: word[ :'pythonslice indices have useful defaultsan omitted first index defaults to zeroan omitted second index defaults to the size of the string being sliced word[: 'pyword[ :'onword[- :'oncharacter from the beginning to position (excludedcharacters from position (includedto the end characters from the second-last (includedto the end one way to remember how slices work is to think of the indices as pointing between characterswith the left edge of the first character numbered then the right edge of the last character of string of characters has index nfor example+---+---+---+---+---+--- +---+---+---+---+---+--- - - - - - - the first row of numbers gives the position of the indices in the stringthe second row gives the corresponding negative indices the slice from to consists of all characters between the edges labeled and jrespectively for non-negative indicesthe length of slice is the difference of the indicesif both are within bounds for examplethe length of word[ : is attempting to use an index that is too large will result in an errorword[ the word only has characters traceback (most recent call last)file ""line in indexerrorstring index out of range using python as calculator