id
int64
0
25.6k
text
stringlengths
0
4.59k
1,600
this book postponed the super call until now (and omitted it almost entirely in prior editionsbecause it has significant issues--it' prohibitively cumbersome to use in xdiffers in form between and xis based upon unusual semantics in xand mixes poorly with python' multiple inheritance and operator overloading in typical...
1,601
def act(self) act(selfprint('eggs'name superclass explicitlypass self ( act(spam eggs this form works the same in and xfollows python' normal method call mapping modelapplies to all inheritance tree formsand does not lead to confusing behavior when operator overloading is used to see why these distinctions matterlet' s...
1,602
superclass changes in the future one of the biggest downsides of this call in xthoughis its reliance on deep magicthough prone to changeit operates today by inspecting the call stack in order to automatically locate the self argument and find the superclassand pairs the two in special proxy object that routes the later...
1,603
def act(self)super(act( ( act( super applied to single-inheritance tree if such classes later grow to use more than one superclassthoughsuper can become error-proneand even unusable--it does not raise an exception for multiple inheritance treesbut will naively pick just the leftmost superclass having the method being r...
1,604
be better off not deploying it in single-inheritance mode either this coding situation isn' nearly as abstract as it may seem here' real-world example of such casetaken from the pymailgui case study in programming python--the following very typical python classes use multiple inheritance to mix in both application logi...
1,605
as briefly noted in python' library manualsuper also doesn' fully work in the presence of __x__ operator overloading methods if you study the following codeyou'll see that direct named calls to overload methods in the superclass operate normallybut using the super result in an expression fails to dispatch to the superc...
1,606
if you are python user reading this dual-version bookyou should also know that the super technique is not portable between python lines its form differs between and --and not just between classic and new-style classes it' really different tool in xwhich cannot run ' simpler form to make this call work in python xyou mu...
1,607
in many morethough its basis is complexthe next sections attempt to rally support for the super cause the super upsidestree changes and dispatch having just shown you the downsides of superi should also confess that 've been tempted to use this call in code that would only ever run on xand which used very long supercla...
1,608
class ( )def (self)super( ( ( ( __bases__ ( , ( start out inheriting from can' hardcode class name here change superclass at runtimethis works (and shares behavior-morphing goals with other deep magicsuch as changing an instance' __class__)but seems rare in the extreme moreoverthere may be other ways to achieve the sam...
1,609
classes)the applications are broader than you might expect in factsome of the earlier examples that demonstrated super shortcomings in multiple inheritance trees could use this call to achieve their dispatch goals to do sohoweversuper must be used universally in the class tree to ensure that method call chains are pass...
1,610
class (bc)pass ( __init__ __init__ class (bc)def __init__(self) __init__(selfc __init__(selfx ( __init__ __init__ __init__ __init__ still runs leftmost only traditional form invoke both supers by name but this now invokes twiceby contrastif all classes use superor are appropriately coerced by proxies to behave as if th...
1,611
class in the mro sequencea super call in class' method propagates the call through the treeso long as all classes do the same in this mode super does not necessarily choose superclass at allit picks the next in the linearized mrowhich might be sibling--or even lower relative--in the class tree of given instance see "tr...
1,612
(herefor instancethe next class in the mro after is cwhich is followed by object whose __init__ silently accepts the call from and ends the chain thusb' method calls 'swhich ends in object' versioneven though is not superclass to reallythoughthis example is atypical--and perhaps even lucky in most casesno such suitable...
1,613
__mro__ (what if you must use class that doesn' call superclass bdef __init__(self)print(' __init__'class (bc)def __init__(self)print(' __init__')super(__init__( ( __init__ __init__ it' an all-or-nothing tool satisfying this mandatory propagation requirement may be no simpler than direct byname calls--which you might s...
1,614
on related notethe universal deployment expectations of super may make it difficult for single class to replace (overridean inherited method altogether not passing the call higher with super--intentionally in this case--works fine for the class itselfbut may break the call chain of trees it' mixed intothereby preventin...
1,615
subtlywhen we say super selects the next class in the mrowe really mean the next class in the mro that implements the requested method--it technically skips ahead until it finds class with the requested name this matters for independent mix-in classeswhich might be added to arbitrary client trees without this skipping-...
1,616
this is also true in the presence of diamonds--disjoint method sets are dispatched as expectedeven if not implemented by each disjoint branchbecause we select the next on the mro with the method reallybecause the mro contains the same classes in these casesand because subclass always appears before its superclass in th...
1,617
class (mixinb)def method(self)print(' method')mixin other(self) method(selfx ( method( method mixin other other method more cruciallythis example so far assumes that method names are disjoint in its branchesthe dispatch order for same-named methods in diamonds like this may be much less fortuitous in diamond like the p...
1,618
method more to the pointby making mix-ins more self-containeddirect calls minimize component coupling that always skews program complexity higher-- fundamental software principle that seems neglected by super' variable and context-specific dispatch model customizationsame-argument constraints as final noteyou should al...
1,619
sue server ('sue'bob salarysue salary ( watch what happensthoughwhen an employee is member of both categories because the constructors in the tree have differing argument listswe're in troubleclass twojobs(chef server )pass tom twojobs('tom'typeerror__init__(takes positional arguments but were given the problem here is...
1,620
and server to mix-in classes without constructorfor example it' also true that polymorphism in general assumes that the methods in an object' external interface have the same argument signaturethough this doesn' quite apply to customization of superclass methods--an internal implementation technique that should by natu...
1,621
in xrelies on arguably non-pythonic magicand does not fully apply to operator overloading or traditionally coded multiple-inheritance trees in xseems so verbose in this intended role that it may make code more complex instead of less claims code maintenance benefits that may be more hypothetical than real in python pra...
1,622
my own advice to readers is to remember that using superin single-inheritance mode can mask later problems and lead to unexpected behavior as trees grow in multiple-inheritance mode brings with it substantial complexity for an atypical python use case for other opinions on python' super that go into further details bot...
1,623
so farso good--this is the normal case but notice what happens when we change the class attribute dynamically outside the class statementit also changes the attribute in every object that inherits from the class moreovernew instances created from the class during this session or program run also get the dynamically set...
1,624
shared [def __init__(self)self perobj [class attribute instance attribute ( ( sharedy perobj ([][]two instances implicitly share class attrs shared append('spam' perobj append('spam' sharedx perobj (['spam']['spam']impacts ' view tooimpacts ' data only sharedy perobj (['spam'][] shared ['spam' sees change made through ...
1,625
inheritance searches listtree before super which class would we inherit it from--listtree or superas inheritance searches proceed from left to rightwe would get the method from whichever class is listed first (leftmostin sub' class header presumablywe would list listtree first because its whole purpose is its custom __...
1,626
in the tree scopes in methods and classes when working out the meaning of names in class-based codeit helps to remember that classes introduce local scopesjust as functions doand methods are simply further nested functions in the following examplethe generate function returns an instance of the nested spam class within...
1,627
def generate(label)returns class instead of an instance class spamcount def method(self)print("% =% (labelspam count)return spam aclass generate('gotchas' aclass( method(gotchas= miscellaneous class gotchas here' handful of additional class-related warningsmostly as review choose per-instance or class storage wisely on...
1,628
kiss revisited"overwrapping-itiswhen used wellthe code reuse features of oop make it excel at cutting development time sometimesthoughoop' abstraction potential can be abused to the point of making code difficult to understand if classes are layered too deeplycode can become obscureyou may have to search through many c...
1,629
name two ways to extend built-in object type what are function and class decorators used for how do you code new-style class how are new-style and classic classes different how are normal and static methods different are tools like __slots__ and super valid to use in your code how long should you wait before lobbing "h...
1,630
with it substantial complexity for an isolated use caseand both require universal deployment to be most useful evaluating new or advanced tools is primary task of any engineerand is why we explored tradeoffs so carefully in this this book' goal is not to tell you which tools to usebut to underscore the importance of ob...
1,631
you add to your class instancesin practiceyou might find it easier to code your add methods to accept just one real argument ( add(self, ))and add that one argument to the instance' current data ( self data ydoes this make more sense than passing two arguments to addwould you say this makes your classes more "object-or...
1,632
set objects experiment with the set class described in "extending types by embeddingrun commands to do the following sorts of operationsa create two sets of integersand compute their intersection and union by using and operator expressions create set from stringand experiment with indexing your set which methods in the...
1,633
def result(selfstart customer order simulation ask the customer what food it has class customerdef __init__(selfinitialize my food to none def placeorder(selffoodnameemployeeplace order with an employee def printfood(selfprint the name of my food class employeedef takeorder(selffoodnamereturn foodwith requested name cl...
1,634
spot reply(meow data hacker(data reply(hello worldanimal replycalls cat speak animal replycalls primate speak figure - zoo hierarchy composed of classes linked into tree to be searched by attribute inheritance animal has common "replymethodbut each class may have its own custom "speakmethod called by "reply the dead pa...
1,635
three other classes (customerclerkparrotthe embedded instance' classes may also participate in an inheritance hierarchycomposition and inheritance are often equally useful ways to structure classes for code reuse why you will careoop by the masters when teach python classesi invariably find that about halfway through t...
1,636
classes naturally promote code factoringwhich allows us to minimize redundancy thanks both to the structure and code reuse support of classesusually only one copy of the code needs to be changed consistency classes and inheritance allow you to implement common interfacesand hence create common look and feel in your cod...
1,637
exceptions and tools
1,638
exception basics this part of the book deals with exceptionswhich are events that can modify the flow of control through program in pythonexceptions are triggered automatically on errorsand they can be triggered and intercepted by your code they are processed by four statements we'll study in this partthe first of whic...
1,639
pieand so on nowsuppose that something goes very wrong during the "bake the piestep perhaps the oven is brokenor perhaps our robot miscalculates its reach and spontaneously combusts clearlywe want to be able to jump to code that handles such states quickly as we have no hope of finishing the pizza task in such unusual ...
1,640
velopment termination actions as you'll seethe try/finally statement allows you to guarantee that required closing-time operations will be performedregardless of the presence or absence of exceptions in your programs the newer with statement offers an alternative in this department for objects that support it unusual c...
1,641
triggered when the function tries to run obj[indexpython detects out-of-bounds indexing for sequences and reports it by raising (triggeringthe built-in indexerror exceptionfetcher( traceback (most recent call last)file ""line in file ""line in fetcher indexerrorstring index out of range default handler shell interface ...
1,642
nowpython jumps to your handler--the block under the except clause that names the exception raised--automatically when an exception is triggered while the try block is running the net effect is to wrap nested block of code in an error handler that intercepts the block' exceptions when working interactively like thisaft...
1,643
way as those python raises the following may not be the most useful python code ever pennedbut it makes the point--raising the built-in indexerror exceptiontryraise indexerror except indexerrorprint('got exception'got exception trigger exception manually as usualif they're not caughtuser-triggered exceptions are propag...
1,644
def __str__(self)return 'so became waiter raise career(traceback (most recent call last)file ""line in __main__ careerso became waiter termination actions finallytry statements can say "finally"--that isthey may include finally blocks these look like except handlers for exceptionsbut the try/finally combination specifi...
1,645
try/finally block when an exception occurs insteadpython jumps back to run the finally actionand then propagates the exception up to prior handler (in this caseto the default handler at the topif we change the call inside this function so as not to trigger an exceptionthe finally code still runsbut the program continue...
1,646
operation that could possibly go astrayand propagate the results of the tests as your programs rundostuff( program if (dofirstthing(=errordetect errors everywhere return erroreven if not handled here if (donextthing(=errorreturn errorreturn dolastthing()main(if (dostuff(=errorbadending()else goodending()in factrealisti...
1,647
combined--one that handles exceptionsand one that executes finalization code regardless of whether exceptions occur or not python' raise and assert statements trigger exceptions on demand--both built-ins and new exceptions we define with classes--and the with/as statement is an alternative way to ensure that terminatio...
1,648
code exitsregardless of whether the block raises an exception or not the withas statement can also be used to ensure termination actions are runbut only when processing object types that support it test your knowledgeanswers
1,649
exception coding details in the prior we took quick look at exception-related statements in action herewe're going to dig bit deeper--this provides more formal introduction to exception processing syntax in python specificallywe'll explore the details behind the tryraiseassertand with statements as we'll seealthough th...
1,650
linefollowed by block of (usuallyindented statementsthen one or more except clauses that identify exceptions to be caught and blocks to process themand an optional else clause and block at the end you associate the words tryexceptand else by indenting them to the same level ( lining them up verticallyfor referencehere'...
1,651
runs the statements under the else line (if present)and control then resumes below the entire try statement in other wordsexcept clauses catch any matching exceptions that happen while the try block is runningand the else clause runs only if no exceptions happen while the try block runs exceptions raised are matched to...
1,652
raise statement later in this they provide access to the objects that are raised as exceptions catching any and all exceptions the first and fourth entries in table - are new hereexcept clauses that list no exception name (except:catch all exceptions not previously listed in the try statement except clauses that list s...
1,653
handle the no-exception case the empty except clause is sort of wildcard feature--because it catches everythingit allows your handlers to be as general or specific as you like in some scenariosthis form may be more convenient than listing all possible exceptions in try for examplethe following catches everything withou...
1,654
rules in xeven with the new as syntaxthe variable is still available after the except block in in xv is not available laterand is in fact forcibly deleted the try else clause the purpose of the else clause is not always immediately obvious to python newcomers without itthoughthere is no direct way to tell (without sett...
1,655
level of the python process and run python' default exception-handling logic ( python terminates the running program and prints standard error messageto illustraterunning the following module filebad pygenerates divide-by-zero exceptiondef gobad(xy)return def gosouth( )print(gobad( )gosouth( because the program ignores...
1,656
again in such as the pdb standard library module examplecatching built-in exceptions python' default exception handling is often exactly what you want--especially for code in top-level script filean error often should terminate your program immediately for many programsthere is no need to be more specific about errors ...
1,657
run this action first statements finallystatements always run this code on the way out with this variantpython begins by running the statement block associated with the try header line as usual what happens next depends on whether an exception occurs during the try blockif an exception does not occur while the try bloc...
1,658
stuff(filefinallyfile close(print('not reached'raises exception always close file to flush output buffers continue here only if no exception when the function in this code raises its exceptionthe control flow jumps back and runs the finally block to close the file the exception is then propagated on to either another t...
1,659
else clause to be run if no exceptions occurred that isthe finally clause could not be mixed with except and else this was partly because of implementation issuesand partly because the meaning of mixing the two seemed obscure--catching and recovering from exceptions seemed disjoint concept from performing cleanup actio...
1,660
when combined like thisthe try statement must have either an except or finallyand the order of its parts must be like thistry -except -else -finally where the else and finally are optionaland there may be zero or more exceptsbut there must be at least one except if an else appears reallythe try statement consists of tw...
1,661
elseno-error finallycleanup againthe finally block is always run on the way outregardless of what happened in the main action and regardless of any exception handlers run in the nested try (trace through the four cases listed previously to see how this works the samesince an else always requires an exceptthis nested fo...
1,662
finallyprint('finally run'print('after run'print(sep 'exception raised but not caught'tryx except indexerrorprint('except run'finallyprint('finally run'print('after run'when this code is runthe following output is produced in python in xits behavior and output are the same because the print calls each print single item...
1,663
raise class raise raise instance of class make and raise instance of classmakes an instance reraise the most recent exception as mentioned earlierexceptions are always instances of classes in python and later hencethe first raise form here is the most common--we provide an instance directlyeither created before the rai...
1,664
except indexerror as xx assigned the raised instance object the as is optional in try handler (if it' omittedthe instance is simply not assigned to name)but including it allows the handler to access both data in the instance and methods in the exception class this model works the same for user-defined exceptions we cod...
1,665
print integer division or modulo by zero zerodivisionerror('integer division or modulo by zero',by contrastpython localizes the exception reference name to the except block-the variable is not available after the block exitsmuch like temporary loop variable in comprehension expressions ( also doesn' accept ' except com...
1,666
except exception as xprint(xsaveit division by zero nameerrorname 'xis not defined saveit zerodivisionerror('division by zero',python removes this reference assign exc to retain exc if needed propagating exceptions with raise the raise statement is bit more feature-rich than we've seen thus far for examplea raise that ...
1,667
traceback (most recent call last)file ""line in zerodivisionerrordivision by zero the above exception was the direct cause of the following exceptiontraceback (most recent call last)file ""line in typeerrorbad when an exception is raised implicitly by program error inside an exception handlera similar procedure is foll...
1,668
traceback (most recent call last)file ""line in syntaxerrornone code like the following would similarly display three exceptionsthough implicitly triggered heretrytry exceptbadname exceptopen('nonesuch'like the unified trychained exceptions are similar to utility in other languages (including java and #though it' not c...
1,669
byte code if the - python command-line flag is usedthereby optimizing the program assertionerror is built-in exceptionand the __debug__ flag is built-in name that is automatically set to true unless the - flag is used use command line like python - main py to run in optimized mode and disable (and hence skipasserts exa...
1,670
python and introduced new exception-related statement--the withand its optional as clause this statement is designed to work with context manager objectswhich support new method-based protocolsimilar in spirit to the way that iteration tools work with methods of the iteration protocol this feature is also available as ...
1,671
protocoland so can be used with the with statement for examplefile objects (covered in have context manager that automatically closes the file after the with block regardless of whether an exception is raisedand regardless of if or when the version of python running the code may close automaticallywith open( ' :\misc\d...
1,672
saving and restoring the current decimal contextwhich specifies the precision and rounding characteristics for calculationswith decimal localcontext(as ctxafterimport decimal ctx prec decimal decimal(' 'decimal decimal(' 'after this statement runsthe current thread' context manager state is automatically restored to wh...
1,673
return self def __exit__(selfexc_typeexc_valueexc_tb)if exc_type is noneprint('exited normally\ 'elseprint('raise an exceptionstr(exc_type)return false propagate if __name__ ='__main__'with traceblock(as actionaction message('test 'print('reached'with traceblock(as actionaction message('test 'raise typeerror print('not...
1,674
python introduced with extension that eventually appeared in python as well in these and later pythonsthe with statement may also specify multiple (sometimes referred to as "nested"context managers with new comma syntax in the followingfor exampleboth filesexit actions are automatically run when the statement block exi...
1,675
more direct closure inside loops to avoid taxing system resourcesdue to differing garbage collectors even more usefullythe following automatically closes the output file on statement exitto ensure that any buffered text is transferred to disk immediatelywith open('script py'as finopen('upper py'' 'as foutfor line in fi...
1,676
they arethe only substantially complex thing about them is how they are identified the next continues our exploration by describing how to implement exception objects of your ownas you'll seeclasses allow you to code new exceptions specific to your programs before we move aheadthoughlet' work through the following shor...
1,677
its protocoltry handles many more use cases test your knowledgeanswers
1,678
exception objects so fari've been deliberately vague about what an exception actually is as suggested in the prior as of python and both built-in and user-defined exceptions are identified by class instance objects this is what is raised and propagated along by exception processingand the source of the class matched ag...
1,679
version skew notepython and later require exceptions to be defined by classes in addition requires exception classes to be derived from the baseexception built-in exception superclasseither directly or indirectly as we'll seemost programs inherit from this class' exception subclassto support catchall handlers for norma...
1,680
:\codepy - raise 'spamtypeerrorexceptions must be old-style classes or derived from baseexceptionetc although you can' use string exceptions todaythey actually provide natural vehicle for introducing the class-based exceptions model class-based exceptions strings were simple way to define exceptions as described earlie...
1,681
let' look at an example to see how class exceptions translate to code in the following fileclassexc pywe define superclass called general and two subclasses called spe cific and specific this example illustrates the notion of exception categories-general is category nameand its two subclasses are specific types of exce...
1,682
argument to make an instance for us exception instances can be created before the raiseas done hereor within the raise statement itself catching categories this code includes functions that raise instances of all three of our classes as exceptionsas well as top-level try that calls the functions and catches general exc...
1,683
large if you've forgotten what __class__ means in an instanceand the prior for review of the as used here why exception hierarchiesbecause there are only three possible exceptions in the prior section' exampleit doesn' really do justice to the utility of class exceptions in factwe could achieve the same effects by codi...
1,684
thoughyou revise it (as programmers are prone to do!along the wayyou identify new thing that can go wrong--underflowperhaps--and add that as new exceptionmathlib py class divzero(exception)pass class oflow(exception)pass class uflow(exception)pass unfortunatelywhen you re-release your codeyou create maintenance problem...
1,685
than defining your library' exceptions as set of autonomous classesarrange them into class tree with common superclass to encompass the entire categorymathlib py class numerr(exception)pass class divzero(numerr)pass class oflow(numerr)pass def func()raise divzero(and so on this wayusers of your library simply need to l...
1,686
which they inherit built-in exception classes didn' really pull the prior section' examples out of thin air all built-in exceptions that python itself may raise are predefined class objects moreoverthey are organized into shallow hierarchy with general superclass categories and specific subclass typesmuch like the prio...
1,687
doesn' document it exhaustively you can read further about this structure in reference texts such as python pocket reference or the python library manual in factthe exceptions class tree differs slightly between python and in ways we'll omit herebecause they are not relevant to examples you can also see the built-in ex...
1,688
good exampleby using similar techniques for class exceptions in your own codeyou can provide exception sets that are flexible and easily modified python reworks the built-in io and os exception hierarchies it adds new specific exception classes corresponding to common file and system error numbersand groups these and o...
1,689
messages--any constructor arguments are attached to the instance and displayed when the instance is printedraise indexerror traceback (most recent call last)file ""line in indexerror same as indexerror()no arguments raise indexerror('spam'traceback (most recent call last)file ""line in indexerrorspam constructor argume...
1,690
multiple arguments save/display tuple raise ('spam''eggs''ham'except as xprint('% % (xx args)('spam''eggs''ham'('spam''eggs''ham'note that exception instance objects are not strings themselvesbut use the __str__ operator overloading protocol we studied in to provide display strings when printedto concatenate with real ...
1,691
always look on the bright side of life raise mybad(traceback (most recent call last)file ""line in __main__ mybadalways look on the bright side of life whatever your method returns is included in error messages for uncaught exceptions and used when exceptions are printed explicitly the method returns hardcoded string h...
1,692
passing extra state information along in the exception itself allows the try statement to access it more reliably with classesthis is nearly automatic as we've seenwhen an exception is raisedpython passes the class instance object along with the exception code in try statements can access the raised instance by listing...
1,693
class formaterror(exception)logfile 'formaterror txtdef __init__(selflinefile)self line line self file file def logerror(self)log open(self logfile' 'print('error at:'self fileself linefile=logdef parser()raise formaterror( 'spam txt'if __name__ ='__main__'tryparser(except formaterror as excexc logerror(when runthis sc...
1,694
the next summary in this we explored coding user-defined exceptions as we learnedexceptions are implemented as class instance objects as of python and (an earlier stringbased exception model alternative was available in earlier releases but has now been deprecatedexception classes support the concept of exception hiera...
1,695
attributes in the instance object raisedusually in custom class constructor for simpler needsbuilt-in exception superclasses provide constructor that stores its arguments on the instance automatically (as tuple in the attribute argsin exception handlersyou list variable to be assigned to the raised instancethen go thro...
1,696
designing with exceptions this rounds out this part of the book with collection of exception design topics and common use case examplesfollowed by this part' gotchas and exercises because this also closes out the fundamentals portion of the book at largeit includes brief overview of development tools as well to help yo...
1,697
jumps back to the most recently entered try statement with matching except clauseand the program resumes after that try statement except clauses intercept and stop the exception--they are where you process and recover from exceptions figure - nested try/finally statementswhen an exception is raised herecontrol returns ...
1,698
let' turn to an example to make this nesting concept more concrete the following module filenestexc pydefines two functions action is coded to trigger an exception (you can' add numbers and sequences)and action wraps call to action in try handlerto catch the exceptiondef action ()print( []def action ()tryaction (except...
1,699
identically tothe prior example in factsyntactic nesting works just like the cases sketched in figure - and figure - the only difference is that the nested handlers are physically embedded in try blocknot coded elsewhere in functions that are called from the try block for examplenested finally handlers all fire on an e...