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 python code in factas we'll seein some code super can actually mask problemsand discourage more explicit coding style that offers better control in its defensethis call does have valid use case too--cooperative same-named method dispatch in diamond multiple inheritance trees--but it seems to ask lot of newcomers it requires that super be used universally and consistently (if not neurotically)much like __slots__ discussed earlierrelies on the arguably obscure mro algorithm to order callsand addresses use case that seems far more the exception than the norm in python programs in this rolesuper seems an advanced tool based upon esoteric principleswhich may be beyond much of python' audienceand seems artificial to real program goals that asideits expectation of universal use seems unrealistic for the vast amount of existing python code because of all these factorsthis introductory-level book has preferred the traditional explicit-name call scheme thus far and recommends the same for newcomers you're better off learning the traditional scheme firstand might be better off sticking with that in generalrather than using an extra special-case tool that may not work in some contextsand relies on arcane magic in the valid but atypical use case it addresses this is not just your author' opiniondespite its advocate' best intentionssuper is not widely recognized as "best practicein python todayfor completely valid reasons on the other handjust as for other tools the increasing use of this call in python code in recent years makes it no longer optional for many python programmers--the first time you see itit' officially mandatoryfor readers who may wish to experiment with superand for other readers who may have it imposed upon themthis section provides brief look at this tool and its rationale--beginning with alternatives to it traditional superclass call formportablegeneral in generalthis book' examples prefer to call back to superclass methods when needed by naming the superclass explicitlybecause this technique is traditional in pythonbecause it works the same in both python and xand because it sidesteps limitations and complexities related to this call in both and as shown earlierthe traditional superclass method call scheme to augment superclass method works as followsclass cdef act(self)print('spam' advanced class topics in python and
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' see how super compares basic super usage and its tradeoffs in this sectionwe'll both introduce super in basicsingle-inheritance modeand look at its perceived downsides in this role as we'll findin this context super does work as advertisedbut is not much different from traditional callsrelies on unusual semanticsand is cumbersome to deploy in more criticallyas soon as your classes grow to use multiple inheritancethis super usage mode can both mask problems in your code and route calls in ways you may not expect odd semanticsa magic proxy in python the super built-in actually has two intended roles the more esoteric of these--cooperative multiple inheritance dispatch protocols in diamond multiple-inheritance trees (yesa mouthful!)--relies on the mrowas borrowed from the dylan languageand will be covered later in this section the role we're interested in here is more commonly usedand more frequently requested by people with java backgrounds--to allow superclasses to be named generically in inheritance trees this is intended to promote simpler code maintenanceand to avoid having to type long superclass reference paths in calls in python xthis call seems at least at first glance to achieve this purpose wellclass cdef act(self)print('spam'class ( )def act(self)super(act(print('eggs'in python (onlysee super form aheadreference superclass genericallyomit self ( act(spam eggs the super built-in functionfor better or worse
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 call to the superclass version of the method if that sounds complicated and strangeit' because it is in factthis call form doesn' work at all outside the context of class' methodsuper "magicproxy object that routes later calls super(systemerrorsuper()no arguments class ( )def method(self)proxy super(print(proxyproxy act(self is implicit in super onlythis form has no meaning outside method show the normally hidden proxy object no argumentsimplicitly calls superclass methode(method(spam reallythis call' semantics resembles nothing else in python--it' neither bound nor unbound methodand somehow finds self even though you omit one in the call in single inheritance treesa superclass is available from self via the path self __class__ __bases__[ ]but the heavily implicit nature of this call makes this difficult to seeand even flies in the face of python' explicit self policy that holds true everywhere else that isthis call violates fundamental python idiom for single use case it also soundly contradicts python' longstanding eibti design rule (run an "import thisfor more on this rulepitfalladding multiple inheritance naively besides its unusual semanticseven in this super role applies most directly to single inheritance treesand can become problematic as soon as classes employ multiple inheritance with traditionally coded classes this seems major limitation of scopedue to the utility of mix-in classes in pythonmultiple inheritance from disjoint and independent superclasses is probably more the norm than the exception in realistic code the super call seems recipe for disaster in classes coded to naively use its basic modewithout allowing for its much more subtle implications in multiple inheritance trees the following illustrates the trap this code begins its life happily deploying super in single-inheritance mode to invoke method one level up from cclass ain python def act(self)print(' 'class bdef act(self)print(' ' advanced class topics
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 run (technicallythe first per the mro)which may or may not be the one that you wantclass (ab)def act(self)super(act( ( act( class (ba)def act(self)super(act( ( act( add mix-in class with the same method doesn' fail on multi-inherbut picks just oneif is listed firsta act(is no longer runperhaps worsethis silently masks the fact that you should probably be selecting superclasses explicitly in this caseas we learned earlier in both this and its predecessor in other wordssuper usage may obscure common source of errors in python --one so common that it shows up again in this part' "gotchas if you may need to use direct calls laterwhy not use them earlier tooclass (ab)def act(self) act(selfb act(selfx ( act( traditional form you probably need to be more explicit here this form handles both single and multiple inher and works the same in both python and so why use the super(special case at allas we'll see in few momentsyou might also be able to address such cases by deploying super calls in every class of the tree but that' also one of the biggest downsides of super--why code it in every classwhen it' usually not neededand when using the preceding simpler traditional form in single class will usually sufficeespecially in existing code--and new code that uses existing code--this super requirement seems harshif not unrealistic much more subtlyas we'll also see aheadonce you step up to multiple inheritance calls this waythe super calls in your code might not invoke the class you expect them to they'll be routed per the mro orderwhichdepending on where else super might be usedmay invoke method in class that is not the caller' superclass at all--an the super built-in functionfor better or worse
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 logic and window tools from independentstandalone classesand hence must invoke both superclass constructors explicitly with direct calls by name as codeda super(__init__(here would run only one constructorand adding super throughout this example' disjoint class trees would be more workwould be no simplerand wouldn' make sense in tools meant for arbitrary deployment in clients that may use super or notclass pymailserverwindow(pymailserverwindows mainwindow)" tkwith extra protocol and mixed-in methodsdef __init__(self)windows mainwindow __init__(selfappnamesrvrnamepymailserver __init__(selfclass pymailfilewindow(pymailfilewindows popupwindow)" toplevelwith extra protocol and mixed-in methodsdef __init__(selffilename)windows popupwindow __init__(selfappnamefilenamepymailfile __init__(selffilenamethe crucial point here is that using super for just the single inheritance cases where it applies most clearly is potential source of error and confusionand means that programmers must remember two ways to accomplish the same goalwhen just one-explicit direct calls--could suffice for all cases in other wordsunless you can be sure that you will never add second superclass to class in tree over your software' entire lifespanyou cannot use super in singleinheritance mode without understanding and allowing for its much more sophisticated role in multiple-inheritance trees we'll discuss the latter aheadbut it' not optional if you deploy super at all from more practical viewit' also not clear that the trivial amount of code maintenance that this super role is envisioned to avoid fully justifies its presence in python practicesuperclass names in headers are rarely changedwhen they arethere are usually at most very small number of superclass calls to update within the class and consider thisif you add new superclass in the future that doesn' use super (as in the preceding example)you'll have to either wrap it in an adaptor proxy or augment all the super calls in your class to use the traditional explicit-name call scheme anyhow- maintenance task that seems just as likelybut perhaps more error-prone if you've grown to rely on super magic advanced class topics
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 superclass' overload methodclass cdef __getitem__(selfix)print(' index'class ( )def __getitem__(selfix)print(' index' __getitem__(selfixsuper(__getitem__(ixsuper()[ixin python indexing overload method redefine to extend here traditional call form works direct name calls work too but operators do not(__getattribute__x ( [ index ( [ index index index traceback (most recent call last)file ""line in file ""line in __getitem__ typeerror'superobject is not subscriptable this behavior is due to the very same new-style (and xclass change described earlier in this (see "attribute fetch for built-ins skips instanceson page )--because the proxy object returned by super uses __getattribute__ to catch and dispatch later method callsit fails to intercept the automatic __x__ method invocations run by built-in operations including expressionsas these begin their search in the class instead of the instance this may seem less severe than the multiple-inheritance limitationbut operators should generally work the same as the equivalent method callespecially for built-in like this not supporting this adds another exception for super users to confront and remember other languagesmileage may varybut in pythonself is explicitmultiple-inheritance mix-ins and operator overloading are commonand superclass name updates are rare because super adds an odd special case to the language--one with strange semanticslimited scoperigid requirementsand questionable reward--most python programmers may be better served by the more broadly applicable traditional call scheme while super has some advanced applications too that we'll study aheadthey may be too obscure to warrant making it mandatory part of every python programmer' toolbox the super built-in functionfor better or worse
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 must first use new-style classes even thenyou must also explicitly pass in the immediate class name and self to supermaking this call so complex and verbose that in most cases it' probably easier to avoid it completelyand simply name the superclass explicitly per the previous traditional code pattern (for brevityi'll leave it to readers to consider what changing class' own name means for code maintenance when using the super form!)class (object)def act(self)print('spam'class ( )def act(self)super(dselfact(print('eggs'in python xfor new-style classes only xdifferent call format seems too complex "dmay be just as much to type/change as " " ( act(spam eggs although you can use the call form in for backward compatibilityit' too cumbersome to deploy in -only codeand the more reasonable form is not usable in xclass ( )def act(self)super(act(print('eggs'simpler call format fails in ( act(typeerrorsuper(takes at least argument ( givenon the other handthe traditional call form with explicit class names works in in both classic and new-style classesand exactly as it does in xclass ( )def act(self) act(selfprint('eggs' ( act(spam eggs advanced class topics but traditional pattern works portably and may often be simpler in code
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 superclass reference path through module package (that ismostly for lazinessbut coding brevity can matter tooto be fairsuper may still be useful in some use casesthe chief among which merit brief introduction herechanging class trees at runtimewhen superclass may be changed at runtimeit' not possible to hardcode its name in call expressionbut it is possible to dispatch calls via super on the other handthis case is extremely rare in python programmingand other techniques can often be used in this context as well cooperative multiple inheritance method dispatchwhen multiple inheritance trees must dispatch to the same-named method in multiple classessuper can provide protocol for orderly call routing on the other handthe class tree must rely upon the ordering of classes by the mro-- complex tool in its own right that is artificial to the problem program is meant to address--and must be coded or augmented to use super in each version of the method in the tree to be effective such dispatch can also often be implemented in other ways ( via instance stateas discussed earliersuper can also be used to select superclass generically as long as the mro' default makes sensethough in traditional code naming superclass explicitly is often preferableand may even be required moreovereven valid super use cases tend to be uncommon in many python programs--to the point of seeming academic curiosity to some the two cases just listedhoweverare most often cited as super rationalesso let' take quick look at each runtime class changes and super superclass that might be changed at runtime dynamically preclude hardcoding their names in subclass' methodswhile super will happily look up the current superclass dynamically stillthis case may be too rare in practice to warrant the super model by itselfand can often be implemented in other ways in the exceptional cases where it is needed to illustratethe following changes the superclass of dynamically by changing the subclass' __bases__ tuple in xclass xdef (self)print(' 'class ythe super built-in functionfor better or worse
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 same effect--perhaps most simplycalling through the current superclass tuple' value indirectlyspecial code to be surebut only for very special case (and perhaps not any more special than implicit routing by mros)class ( )def (self) __bases__[ (selfi ( ( __bases__ ( , ( special code for special case same effectwithout super(given the preexisting alternativesthis case alone doesn' seem to justify superthough in more complex treesthe next rationale--based on the tree' mro order instead of physical superclass links--may apply here as well cooperative multiple inheritance method dispatch the second of the use cases listed earlier is the main rationale commonly given for superand also borrows from other programming languages (most notablydylan)where its use case may be more common than it is in typical python code it generally applies to diamond pattern multiple inheritance treesdiscussed earlier in this and allows for cooperative and conformant classes to route calls to same-named method coherently among multiple class implementations especially for constructorswhich have multiple implementations normallythis can simplify call routing protocol when used consistently in this modeeach super call selects the method from next class following it in the mro ordering of the class of the self subject of method call the mro was introduced earlierit' the path python follows for inheritance in new-style classes because the mro' linear ordering depends on which class self was made fromthe order of method dispatch orchestrated by super can vary per class treeand visits each class just once as long as all classes use super to dispatch advanced class topics
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 passed on-- fairly major requirement that may be difficult to enforce in much existing and new code the basicscooperative super call in action let' take look at what this role means in code in this and the following sectionswe'll both learn how super worksand explore the tradeoffs it implies along the way to get startedconsider the following traditionally coded python classes (condensed somewhat here as usual for space)class bdef __init__(self)print(' __init__'class cdef __init__(self)print(' __init__'class (bc)pass ( __init__ disjoint class tree branches runs leftmost only by default in this casesuperclass tree branches are disjoint (they don' share common explicit ancestor)so subclasses that combine them must call through each superclass by name -- common situation in much existing python code that super cannot address directly without code changesclass (bc)def __init__(self) __init__(selfc __init__(selftraditional form invoke supers by name ( __init__ __init__ in diamond class tree patternsthoughexplicit-name calls may by default trigger the top-level class' method more than oncethough this might be subverted with additional protocols ( status markers in the instance)class adef __init__(self)print(' __init__'class ( )def __init__(self)print(' __init__') __init__(selfclass ( )def __init__(self)print(' __init__') __init__(selfx ( __init__ __init__ ( __init__ each super works by itself the super built-in functionfor better or worse
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 they dothe method calls are dispatched according to class order in the mrosuch that the top-level class' method is run just onceclass adef __init__(self)print(' __init__'class ( )def __init__(self)print(' __init__')super(__init__(class ( )def __init__(self)print(' __init__')super(__init__( ( __init__ __init__ ( __init__ __init__ class (bc)pass ( __init__ __init__ __init__ runs __init__a is next super in self' mro runs __init__c is next super in self' mrothe real magic behind this is the linear mro list constructed for the class of self-because each class appears just once on this listand because super dispatches to the next class on this listit ensures an orderly invocation chain that visits each class just once cruciallythe next class following in the mro differs depending on the class of self--it' for instancebut for instanceaccounting for the order of constructors runb __mro__ ( __mro__ ( advanced class topics
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 "tracing the mroon page for other examples of the path super dispatch would followespecially for nondiamonds the preceding works--and may even seem clever at first glance--but its scope may also appear limited to some most python programs do not rely on the nuances of diamond pattern multiple inheritance trees (in factmany python programmers 've met do not know what the term means!moreoversuper applies most directly to single inheritance and cooperative diamond casesand may seem superfluous for disjoint nondiamond caseswhere we might want to invoke superclass methods selectively or independently even cooperative diamonds can be managed in other ways that may afford programmers more control than an automatic mro ordering can to evaluate this tool objectivelythoughwe need to look deeper constraintcall chain anchor requirement the super call comes with complexities that may not be apparent on first encounterand may even seem initially like features for examplebecause all classes inherit from object in automatically (and explicitly in new-style classes)the mro ordering can be used even in cases where the diamond is only implicit--in the followingtriggering constructors in independent classes automaticallyclass bdef __init__(self)print(' __init__')super(__init__(class cdef __init__(self)print(' __init__')super(__init__( ( __init__ ( __init__ object is an implied super at the end of mro class (bc)pass ( __init__ __init__ inherits __init__ but ' mro differs for runs __init__c is next super in self' mrotechnicallythis dispatch model generally requires that the method being called by super must existand must have the same argument signature across the class treeand every appearance of the method but the last must use super itself this prior example works only because the implied object superclass at the end of the mro of all three classes happens to have compatible __init__ that satisfies these rulesb __mro__ (the super built-in functionfor better or worse
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 default will exist in objectand it may be less trivial to satisfy this model' expectations most trees will require an explicit--and possibly extra--superclass to serve the anchoring role that object does hereto accept but not forward the call other trees may require careful design to adhere to this requirement moreoverunless python optimizes it awaythe call to object (or other anchordefaults at the end of the chain may also add extra performance costs by contrastin such cases direct calls incur neither extra coding requirements nor added performance costand make dispatch more explicit and directclass bdef __init__(self)print(' __init__'class cdef __init__(self)print(' __init__'class (bc)def __init__(self) __init__(self) __init__(selfx ( __init__ __init__ scopean all-or-nothing model also keep in mind that traditional classes that were not written to use super in this role cannot be directly used in such cooperative dispatch treesas they will not forward calls along the mro chain it' possible to incorporate such classes with proxies that wrap the original object and add the requisite super callsbut this imposes both additional coding requirements and performance costs on the model given that there are many millions of lines of existing python code that do not use superthis seems major detriment watch what happensfor exampleif any one class fails to pass along the call chain by omitting superending the call chain prematurely--like __slots__super is generally an all-or-nothing featureclass bdef __init__(self)print(' __init__')super(__init__(class cdef __init__(self)print(' __init__')super(__init__(class (bc)def __init__(self)print(' __init__')super(__init__( ( __init__ __init__ advanced class topics
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 still forgetbut which you won' need to require of all the code your classes employ as mentionedit' possible to adapt class like by inheriting from proxy class that embeds instancesbut that seems artificial to program goalsadds an extra call to each wrapped methodis subject to the new-style class problems we met earlier regarding interface proxies and built-insand seems an extraordinary and even stunning added coding requirement inherent in model intended to simplify code flexibilitycall ordering assumptions routing with super also assumes that you really mean to pass method calls throughout all your classes per the mrowhich may or may not match your call ordering requirements for exampleimagine that--irrespective of other inheritance ordering needs-the following requires that the class ' version of given method be run before ' in some contexts if the mro says otherwiseyou're back to traditional callswhich may conflict with super usage--in the followinginvoking ' method twicewhat if method call ordering needs differ from the mroclass bdef __init__(self)print(' __init__')super(__init__(class cdef __init__(self)print(' __init__')super(__init__(class (bc)def __init__(self)print(' __init__') __init__(self) __init__(selfx ( __init__ __init__ __init__ __init__ it' the mro xor explicit calls similarlyif you want some methods to not run at allthe super automatic path won' apply as directly as explicit calls mayand will make it difficult to take more explicit control of the dispatch process in realistic programs with many methodsresourcesand state variablesthese seem entirely plausible scenarios while you could reorder superclasses in for this methodthat may break other expectations the super built-in functionfor better or worse
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 preventing methods elsewhere in the tree from running consider the following treeclass adef method(self)print(' method')super(method(class ( )def method(self)print(' method')super(method(class cdef method(self)print(' method'no supermust anchor the chainclass (bc)def method(self)print(' method')super(method( ( method( method method method dispatch to all per the mro automatically method method replacement here breaks the super modeland probably leads us back to the traditional formwhat if class needs to replace super' default entirelyclass ( )def method(self)print(' method'drop super to replace ' method class (bc)def method(self)print(' method')super(method( ( method( method method but replacement also breaks the call chain class (bc)def method(self)print(' method') method(self) method(selfd(method( method method method it' back to explicit calls once againthe problem with assumptions is that they assume thingsalthough the assumption of universal routing might be reasonable for constructorsit would also seem to conflict with one of the core tenets of oop--unrestricted subclass customization this might suggest restricting super usage to constructorsbut even these might sometimes warrant replacementand this adds an odd special-case requirement for one specific context tool that can be used only for certain categories of methods might be seen by some as redundant--and even spuriousgiven the extra complexity it implies advanced class topics
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-ahead behaviorsuch mix-ins wouldn' work at all--they would otherwise drop the call chain of their clientsarbitrary methodsand couldn' rely on their own super calls to work as expected in the following independent branchesfor examplec' call to method is passed oneven though mixinthe next class in the instance' mrodoesn' define that method' name as long as method name sets are disjointthis just works--the call chains of each branch can exist independentlymix-ins work for disjoint method sets class adef other(self)print(' other'class mixin( )def other(self)print('mixin other')super(other(class bdef method(self)print(' method'class (mixinb)def method(self)print(' method')super(other()super(method( (method( method mixin other other method __mro__ (similarlymixing the other way doesn' break call chains of the mix-in either for instancein the followingeven though doesn' define other when called in cclasses do later in the mro in factthe call chains work even if one of the branches doesn' use super at all--as long as method is defined somewhere ahead on the mroits call worksclass (bmixin)def method(self)print(' method')super(other()super(method( (method( method mixin other other method __mro__ the super built-in functionfor better or worse
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 the mrothey are equivalent contexts for examplethe call in mixin to other in the following still finds it in aeven though the next class after mixin on the mro is (the call to method in works again for similar reasons)explicit diamonds work too class adef other(self)print(' other'class mixin( )def other(self)print('mixin other')super(other(class ( )def method(self)print(' method'class (mixinb)def method(self)print(' method')super(other()super(method( (method( method mixin other other method __mro__ (other mix-in orderings work too class (bmixin)def method(self)print(' method')super(other()super(method( (method( method mixin other other method __mro__ (stillthis has an effect that is no different--but may seem wildly more implicit--than direct by-name callswhich also work the same in this case regardless of superclass orderingand whether there is diamond or not in this casethe motivation for relying on mro ordering seems on shaky groundif the traditional form is both simpler and more explicitand offers more control and flexibility advanced class topics
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 precedingfor exampleit' not impossible that client class could invalidate super call' intent--the call to method in mixin in the following works to run ' version as expectedunless it' mixed into tree that drops the call chainbut for nondisjoint methodssuper creates overly strong coupling class adef method(self)print(' method'class mixin( )def method(self)print('mixin method')super(method(mixin(method(mixin method method class ( )def method(self)print(' method'super here would invoke after class (mixinb)def method(self)print(' method')super(method( (method( method mixin method method we miss in this context onlyit may be that shouldn' redefine this method anyhow (and franklywe may be encroaching on problems inherent in multiple inheritance in general)but this need not also break the mix-in--direct calls give you more control in such casesand allow mixin classes to be much more independent of usage contextsand direct calls do notthey are immune to context of use class adef method(self)print(' method'class mixin( )def method(self)print('mixin method') method(selfc irrelevant class (mixinb)def method(self)print(' method')mixin method(selfc(method( method the super built-in functionfor better or worse
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 also consider the consequences of using super when method arguments differ per class--because class coder can' be sure which version of method super might invoke (indeedthis may vary per tree!)every version of the method must generally accept the same arguments listor choose its inputs with analysis of generic argument lists--either of which imposes additional requirements on your code in realistic programsthis constraint may in fact be true showstopper for many potential super applicationsprecluding its use entirely to illustrate why this can matterrecall the pizza shop employee classes we wrote in as coded thereboth subclasses use direct by-name calls to invoke the superclass constructorfilling in an expected salary argument automatically--the logic being that the subclass implies the pay gradeclass employeedef __init__(selfnamesalary)self name name self salary salary class chef (employee)def __init__(selfname)employee __init__(selfname common superclass differing arguments dispatch by direct call class server (employee)def __init__(selfname)employee __init__(selfname bob chef ('bob'sue server ('sue'bob salarysue salary ( this worksbut since this is single-inheritance treewe might be tempted to deploy super here to route the constructor calls generically doing so works for either subclass in isolationsince its mro includes just itself and its actual superclassclass chef (employee)def __init__(selfname)super(__init__(name class server (employee)def __init__(selfname)super(__init__(name advanced class topics dispatch by super(
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 that the super call in chef no longer invokes its employee superclassbut instead invokes its sibling class and follower on the mroserver since this sibling has differing argument list than the true superclass--expecting just self and name--the code breaks this is inherent in super usebecause the mro can differ per treeit might call different versions of method in different trees--even some you may not be able to anticipate when coding class by itselftwojobs __mro__ (chef __mro__ (by contrastthe direct by-name call scheme still works when the classes are mixedthough the results are bit dubious--the combined category gets the pay of the leftmost superclassclass twojobs(chef server )pass tom twojobs('tom'tom salary reallywe probably want to route the call to the top-level class in this event with new salary-- model that is possible with direct calls but not with super alone moreovercalling employee directly in this one class means our code uses two dispatch techniques when just one--direct calls--would sufficeclass twojobs(chef server )def __init__(selfname)employee __init__(selfname tom twojobs('tom'tom salary class twojobs(chef server )def __init__(selfname)super(__init__(name tom twojobs('tom'typeerror__init__(takes positional arguments but were given the super built-in functionfor better or worse
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 nature support variationespecially in constructors but the crucial point here is that because direct calls do not make code dependent on magic ordering that can vary per treethey more directly support argument list flexibility more broadlythe questionable (or weakperformances super turns in on method replacementmix-in couplingcall orderingand argument constraints should make you evaluate its deployment carefully even in single-inheritance modeits potential for later impacts as trees grow is considerable in sumthe three requirements of super in this role are also the source of most of its usability issuesthe method called by super must exist--which requires extra code if no anchor is present the method called by super must have the same argument signature across the class tree--which impairs flexibilityespecially for implementation-level methods like constructors every appearance of the method called by super but the last must use super itself --which makes it difficult to use existing codechange call orderingoverride methodsand code self-contained classes taken togetherthese seem to make for tool with both substantial complexity and significant tradeoffs--downsides that will assert themselves the moment the code grows to incorporate multiple inheritance naturallythere may be creative workarounds for the super dilemmas just posedbut additional coding steps would further dilute the call' benefits--and we've run out of space here in any event there are also alternative non-super solutions to some diamond method dispatch problemsbut these will have to be left as user exercise for space reasons too in generalwhen superclass methods are called by explicit nameroot classes of diamonds might check state in instances to avoid firing twice-- similarly complex coding patternbut required rarely in most codeand which to some may seem no more difficult than using super itself the super summary so there it is--the bad and the good as with all python extensionsyou should be the judge on this one too 've tried to give both sides of the debate fair shake here to help you decide but because the super calldiffers in form between and advanced class topics
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 practice even ex-java programmers should also consider this book' preferred traditional technique of explicit-name superclass calls to be at least as valid solution as python' super -- call that on some levels seems an unusual and limited answer to question that was not being asked by most python programmersand was not deemed important for much of python' history at the same timethe super call offers one solution to the difficult problem of samenamed method dispatch in multiple inheritance treesfor programs that choose to use it universally and consistently but therein lies one of its largest obstaclesit requires universal deployment to address problem most programmers probably do not have moreoverat this point in python' historyasking programmers to change their existing code to use this call widely enough to make it reliable seems highly unrealistic perhaps the chief problem of this rolethoughis the role itself--same-named method dispatch in multiple inheritance trees is relatively rare in real python programsand obscure enough to have generated both much controversy and much misunderstanding surrounding this role people don' use python the same way they use ++javaor dylanand lessons from other such languages do not necessarily apply also keep in mind that using super makes your program' behavior dependent on the mro algorithm-- procedure that we've covered only informally here due to its complexitythat is artificial to your program' purposeand that seems tersely documented and understood in the python world as we've seeneven if you understand the mroits implications on customizationcouplingand flexibility are remarkably subtle if you don' completely understand this algorithm--or have goals that its application does not address--you may be better served not relying on it to implicitly trigger actions in your code orto quote python motto from its import this creedif the implementation is hard to explainit' bad idea the super call seems firmly in this category most programmers won' use an arcane tool aimed at rare use caseno matter how clever it may be this is especially true in scripting language that bills itself as friendly to nonspecialists regrettablyuse by any programmer can impose such tool on others anyhow--the real reason 've covered it hereand theme we'll revisit at the end of this book as usualtime and user base will tell if this call' tradeoffs or momentum lead to broader adoption or not at the leastit behooves you to also know about the traditional explicitname superclass call techniqueas it is still commonly used and often either simpler or the super built-in functionfor better or worse
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 both good and badsearch the web for related articles you can find plenty of additional positionsthough in the endpython' future relies as much on yours as any other class gotchas we've reached the end of the primary oop coverage in this book after exceptionswe'll explore additional class-related examples and topics in the last part of the bookbut that part mostly just gives expanded coverage to concepts introduced here as usuallet' wrap up this part with the standard warnings about pitfalls to avoid most class issues can be boiled down to namespace issues--which makes sensegiven that classes are just namespaces with handful of extra tricks some of the items in this section are more like class usage pointers than problemsbut even experienced class coders have been known to stumble on few changing class attributes can have side effects theoretically speakingclasses (and class instancesare mutable objects as with builtin lists and dictionariesyou can change them in place by assigning to their attributes --and as with lists and dictionariesthis means that changing class or instance object may impact multiple references to it that' usually what we wantand is how objects change their state in generalbut awareness of this issue becomes especially critical when changing class attributes because all instances generated from class share the class' namespaceany changes at the class level are reflected in all instancesunless they have their own versions of the changed class attributes because classesmodulesand instances are all just objects with attribute namespacesyou can normally change their attributes at runtime by assignments consider the following class inside the class bodythe assignment to the name generates an attribute awhich lives in the class object at runtime and will be inherited by all of ' instancesclass xa class attribute ( inherited by instance advanced class topics
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 valueregardless of what the class' source code saysx ( may change more than changes too inherits from ' runtime values (but assigning to changes in jnot or iis this useful feature or dangerous trapyou be the judge as we learned in you can actually get work done by changing class attributes without ever making single instance-- technique that can simulate the use of "recordsor "structsin other languages as refresherconsider the following unusual but legal python programclass xpass class ypass make few attribute namespaces use class attributes as variables no instances anywhere to be found for in range( )print( iprints herethe classes and work like "filelessmodules--namespaces for storing variables we don' want to clash this is perfectly legal python programming trickbut it' less appropriate when applied to classes written by othersyou can' always be sure that class attributes you change aren' critical to the class' internal behavior if you're out to simulate structyou may be better off changing instances than classesas that way only one object is affectedclass recordpass record( name 'bobx job 'pizza makerchanging mutable class attributes can have side effectstoo this gotcha is really an extension of the prior because class attributes are shared by all instancesif class attribute references mutable objectchanging that object in place from any instance impacts all instances at onceclass gotchas
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 stored on class and shared this effect is no different than many we've seen in this book alreadymutable objects are shared by simple variablesglobals are shared by functionsmodule-level objects are shared by multiple importersand mutable function arguments are shared by the caller and the callee all of these are cases of general behavior--multiple references to mutable object--and all are impacted if the shared object is changed in place from any reference herethis occurs in class attributes shared by all instances via inheritancebut it' the same phenomenon at work it may be made more subtle by the different behavior of assignments to instance attributes themselvesx shared append('spam' shared 'spamchanges shared object attached to class in place changed or creates instance attribute attached to but againthis is not problemit' just something to be aware ofshared mutable class attributes can have many valid uses in python programs multiple inheritanceorder matters this may be obvious by nowbut it' worth underscoringif you use multiple inheritancethe order in which superclasses are listed in the class statement header can be critical python always searches superclasses from left to rightaccording to their order in the header line for instancein the multiple inheritance example we studied in suppose that the super class implemented __str__ methodtooclass listtreedef __str__(self)class superdef __str__(self)class sub(listtreesuper) advanced class topics get listtree' __str__ by listing it first
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 __str__ (indeedwe had to do this in when mixing this class with tkinter button that had __str__ of its ownbut now suppose super and listtree have their own versions of other same-named attributestoo if we want one name from super and another from listtreethe order in which we list them in the class header won' help--we will have to override inheritance by manually assigning to the attribute name in the sub classclass listtreedef __str__(self)def other(self)class superdef __str__(self)def other(self)class sub(listtreesuper)other super other def __init__(self)get listtree' __str__ by listing it first but explicitly pick super' version of other sub(inheritance searches sub before listtree/super herethe assignment to other within the sub class creates sub other-- reference back to the super other object because it is lower in the treesub other effectively hides listtree otherthe attribute that the inheritance search would normally find similarlyif we listed super first in the class header to pick up its otherwe would need to select listtree' method explicitlyclass sub(superlisttree)__str__ lister __str__ get super' other by order explicitly pick lister __str__ multiple inheritance is an advanced tool even if you understood the last paragraphit' still good idea to use it sparingly and carefully otherwisethe meaning of name may come to depend on the order in which classes are mixed in an arbitrarily farremoved subclass (for another example of the technique shown here in actionsee the discussion of explicit conflict resolution in "the 'new-styleclass model"as well as the earlier super coverage as rule of thumbmultiple inheritance works best when your mix-in classes are as self-contained as possible--because they may be used in variety of contextsthey should not make assumptions about names related to other classes in tree the pseudoprivate __x attributes feature we studied in can help by localizing names that class relies on owning and limiting the names that your mix-in classes add to the mix in this examplefor instanceif listtree only means to export its custom class gotchas
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 its codethe class name spam is assigned in the gener ate function' local scopeand hence is visible to any further nested functionsincluding code inside methodit' the in the "legbscope lookup ruledef generate()class spamcount def method(self)print(spam countreturn spam(spam is name in generate' local scope visible in generate' scopeper legb rule (egenerate(method(this example works in python since version because the local scopes of all enclosing function defs are automatically visible to nested defs (including nested method defsas in this exampleeven sokeep in mind that method defs cannot see the local scope of the enclosing classthey can see only the local scopes of enclosing defs that' why methods must go through the self instance or the class name to reference methods and other attributes defined in the enclosing class statement for examplecode in the method must use self count or spam countnot just count to avoid nestingwe could restructure this code such that the class spam is defined at the top level of the modulethe nested method function and the top-level generate will then both find spam in their global scopesit' not localized to function' scopebut is still local to single moduledef generate()return spam(class spamcount def method(self)print(spam countdefine at top level of module worksin global (enclosing modulegenerate(method(in factthis approach is recommended for all python releases--code tends to be simpler in general if you avoid nesting classes and functions on the other handclass nesting is useful in closure contextswhere the enclosing function' scope retains state used by the class or its methods in the followingthe nested method has access to its own scope advanced class topics
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 similar notebe careful when you decide whether an attribute should be stored on class or its instancesthe former is shared by all instancesand the latter will differ per instance this can be crucial design issue in practice in gui programfor instanceif you want information to be shared by all of the window class objects your application will create ( the last directory used for save operationor an already entered password)it must be stored as class-level dataif stored in the instance as self attributesit will vary per window or be missing entirely when looked up by inheritance you usually want to call superclass constructors remember that python runs only one __init__ constructor method when an instance is made--the lowest in the class inheritance tree it does not automatically run the constructors of all superclasses higher up because constructors normally perform required startup workyou'll usually need to run superclass constructor from subclass constructor--using manual call through the superclass' name (or super)passing along whatever arguments are required--unless you mean to replace the super' constructor altogetheror the superclass doesn' have or inherit constructor at all delegation-based classes in x__getattr__ and built-ins another reminderas described earlier in this and elsewhereclasses that use the __getattr__ operator overloading method to delegate attribute fetches to wrapped objects may fail in python (and when new-style classes are usedunless operator overloading methods are redefined in the wrapper class the names of operator overloading methods implicitly fetched by built-in operations are not routed through generic attribute-interception methods to work around thisyou must redefine such class gotchas
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 classes to discover what an operation does for examplei once worked in +shop with thousands of classes (some machinegenerated)and up to levels of inheritance deciphering method calls in such complex system was often monumental taskmultiple classes had to be consulted for even the most basic of operations in factthe logic of the system was so deeply wrapped that understanding piece of code in some cases required days of wading through related files this obviously isn' ideal for programmer productivitythe most general rule of thumb of python programming applies heretoodon' make things complicated unless they truly must be wrapping your code in multiple layers of classes to the point of incomprehensibility is always bad idea abstraction is the basis of polymorphism and encapsulationand it can be very effective tool when used well howeveryou'll simplify debugging and aid maintainability if you make your class interfaces intuitiveavoid making your code overly abstractand keep your class hierarchies short and flat unless there is good reason to do otherwise remembercode you write is generally code that others must read see for more on kiss summary this presented an assortment of advanced class-related topicsincluding subclassing built-in typesnew-style classesstatic methodsand decorators most of these are optional extensions to the oop model in pythonbut they may become more useful as you start writing larger object-oriented programsand are fair game if they appear in code you must understand as mentioned earlierour discussion of some of the more advanced class tools continues in the final part of this bookbe sure to look ahead if you need more details on propertiesdescriptorsdecoratorsand metaclasses this is the end of the class part of this bookso you'll find the usual lab exercises at the end of the be sure to work through them to get some practice coding real classes in the next we'll begin our look at our last core language topicexceptions--python' mechanism for communicating errors and other conditions to your code this is relatively lightweight topicbut 've saved it for last because new exceptions are supposed to be coded as classes today before we tackle that final core subjectthoughtake look at this quiz and the lab exercises advanced class topics
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 "holy hand grenade"test your knowledgeanswers you can embed built-in object in wrapper classor subclass the built-in type directly the latter approach tends to be simpleras most original behavior is automatically inherited function decorators are generally used to manage function or methodor add to it layer of logic that is run each time the function or method is called they can be used to log or count calls to functioncheck its argument typesand so on they are also used to "declarestatic methods (simple functions in class that are not passed an instance when called)as well as class methods and properties class decorators are similarbut manage whole objects and their interfaces instead of function call new-style classes are coded by inheriting from the object built-in class (or any other built-in typein python xall classes are new-style automaticallyso this derivation is not required (but doesn' hurt)in xclasses with this explicit derivation are new-style and those without it are "classic new-style classes search the diamond pattern of multiple inheritance trees differently--they essentially search breadth-first (across)instead of depth-first (upin diamond trees new-style classes also change the result of the type built-in for instances and classesdo not run generic attribute fetch methods such as __get attr__ for built-in operation methodsand support set of advanced extra tools including propertiesdescriptorssuperand __slots__ instance attribute lists normal (instancemethods receive self argument (the implied instance)but static methods do not static methods are simple functions nested in class objects to make method staticit must either be run through special built-in function or be decorated with decorator syntax python allows simple functions in class to be called through the class without this stepbut calls through instances still require static method declaration of coursebut you shouldn' use advanced tools automatically without carefully considering their implications slotsfor examplecan break codesuper can mask test your knowledgeanswers
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 objectively analyzing them-- task often given too low priority in the software field three seconds (ormore accurately"and the lord spakesaying'first shalt thou take out the holy pin thenshalt thou count to threeno moreno less three shalt be the number thou shalt countand the number of the counting shall be three four shalt thou not countnor either count thou twoexcepting that thou then proceed to three five is right out once the number threebeing the third numberbe reachedthen lobbest thou thy holy hand grenade of antioch towards thy foewhobeing naughty in my sightshall snuff it '") test your knowledgepart vi exercises these exercises ask you to write few classes and experiment with some existing code of coursethe problem with existing code is that it must be existing to work with the set class in exercise either pull the class source code off this book' website (see the preface for pointeror type it up by hand (it' fairly briefthese programs are starting to get more sophisticatedso be sure to check the solutions at the end of the book for pointers you'll find them in appendix dunder part vi inheritance write class called adder that exports method add(selfxythat prints "not implementedmessage thendefine two subclasses of adder that implement the add methodlistadder with an add method that returns the concatenation of its two list arguments dictadder with an add method that returns new dictionary containing the items in both its two dictionary arguments (any definition of dictionary addition will doexperiment by making instances of all three of your classes interactively and calling their add methods nowextend your adder superclass to save an object in the instance with constructor ( assign self data list or dictionary)and overload the operator with an __add__ method to automatically dispatch to your add methods ( triggers add( data, )where is the best place to put the constructors and this quote is from monty python and the holy grail (and if you didn' know thatit may be time to find copy! advanced class topics
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-oriented" operator overloading write class called mylist that shadows ("wraps" python listit should overload most list operators and operationsincluding +indexingiterationslicingand list methods such as append and sort see the python reference manual or other documentation for list of all possible methods to support alsoprovide constructor for your class that takes an existing list (or mylist instanceand copies its components into an instance attribute experiment with your class interactively things to explorea why is copying the initial value important hereb can you use an empty slice ( start[:]to copy the initial value if it' mylist instancec is there general way to route list method calls to the wrapped listd can you add mylist and regular listhow about list and mylist instancee what type of object should operations like and slicing returnwhat about indexing operationsf if you are working with reasonably recent python release (version or later)you may implement this sort of wrapper class by embedding real list in standalone classor by extending the built-in list type with subclass which is easierand why subclassing make subclass of mylist from exercise called mylistsubwhich extends mylist to print message to stdout before each call to the overloaded operation and counts the number of such calls mylistsub should inherit basic method behavior from mylist adding sequence to mylistsub should print messageincrement the counter for callsand perform the superclass' method alsointroduce new method that prints the operation counters to stdoutand experiment with your class interactively do your counters count calls per instanceor per class (for all instances of the class)how would you program the other option(hintit depends on which object the count members are assigned toclass members are shared by instancesbut self members are per-instance data attribute methods write class called attrs with methods that intercept every attribute qualification (both fetches and assignments)and print messages listing their arguments to stdout create an attrs instanceand experiment with qualifying it interactively what happens when you try to use the instance in expressionstry addingindexingand slicing the instance of your class (notea fully generic approach based upon __getattr__ will work in ' classic classes but not in ' new-style classes--which are optional in --for reasons noted in chaptest your knowledgepart vi exercises
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 class are calledc try iterating through the items in your string set using for loop which methods run this timed try computing the intersection and union of your string set and simple python string does it worke nowextend your set by subclassing to handle arbitrarily many operands using the *args argument form (hintsee the function versions of these algorithms in compute intersections and unions of multiple operands with your set subclass how can you intersect three or more setsgiven that has only two sidesf how would you go about emulating other list operations in the set class(hint__add__ can catch concatenationand __getattr__ can pass most named list method calls like append to the wrapped list class tree links in "namespacesthe whole storyin and in "multiple inheritance'mix-inclassesin we learned that classes have __bases__ attribute that returns tuple of their superclass objects (the ones listed in parentheses in the class headeruse __bases__ to extend the lister py mix-in classes we wrote in so that they print the names of the immediate superclasses of the instance' class when you're donethe first line of the string representation should look like this (your address will almost certainly vary)<instance of sub(superlister)address composition simulate fast-food ordering scenario by defining four classeslunch container and controller class customer the actor who buys food employee the actor from whom customer orders food what the customer buys to get you startedhere are the classes and methods you'll be definingclass lunchdef __init__(self advanced class topics make/embed customer and employee
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 class fooddef __init__(selfnamestore food name the order simulation should work as followsa the lunch class' constructor should make and embed an instance of cus tomer and an instance of employeeand it should export method called order when calledthis order method should ask the customer to place an order by calling its placeorder method the customer' placeorder method should in turn ask the employee object for new food object by calling employee' takeorder method food objects should store food name string ( "burritos")passed down from lunch orderto customer placeorderto employee takeorderand finally to food' constructor the top-level lunch class should also export method called resultwhich asks the customer to print the name of the food it received from the employee via the order (this can be used to test your simulationnote that lunch needs to pass either the employee or itself to the customer to allow the customer to call employee methods experiment with your classes interactively by importing the lunch classcalling its order method to run an interactionand then calling its result method to verify that the customer got what he or she ordered if you preferyou can also simply code test cases as self-test code in the file where your classes are definedusing the module __name__ trick of in this simulationthe customer is the active agenthow would your classes change if employee were the object that initiated customer/employee interaction instead zoo animal hierarchy consider the class tree shown in figure - code set of six class statements to model this taxonomy with python inheritance thenadd speak method to each of your classes that prints unique messageand reply method in your top-level animal superclass that simply calls self speak to invoke the category-specific message printer in subclass below (this will kick off an independent inheritance search from selffinallyremove the speak method from your hacker class so that it picks up the default above it when you're finishedyour classes should work this waypython from zoo import cathacker test your knowledgepart vi exercises
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 parrot sketch consider the object embedding structure captured in figure - code set of python classes to implement this structure with composition code your scene object to define an action methodand embed instances of the cus tomerclerkand parrot classes (each of which should define line method that prints unique messagethe embedded objects may either inherit from common superclass that defines line and simply provide message textor define line themselves in the endyour classes should operate like thispython import parrot parrot scene(action(customer"that' one ex-bird!clerk"no it isn' parrotnone advanced class topics activate nested objects
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 the classpeople who have used oop in the past are following along intenselywhile people who have not are beginning to glaze over (or nod off completelythe point behind the technology just isn' apparent in book like thisi have the luxury of including material like the new big picture overview in and the gradual tutorial of --in factyou should probably review that section if you're starting to feel like oop is just some computer science mumbo-jumbo though it adds much more structure than the generators we met earlieroop similarly relies on some magic (inheritance search and special first argumentthat beginners can find difficult to rationalize in real classeshoweverto help get the newcomers on board (and keep them awake) have been known to stop and ask the experts in the audience why they use oop the answers they've given might help shed some light on the purpose of oopif you're new to the subject herethenwith only few embellishmentsare the most common reasons to use oopas cited by my students over the yearscode reuse this one' easy (and is the main reason for using oopby supporting inheritanceclasses allow you to program by customization instead of starting each project from scratch encapsulation wrapping up implementation details behind object interfaces insulates users of class from code changes structure classes provide new local scopeswhich minimizes name clashes they also provide natural place to write and look for implementation codeand to manage object state test your knowledgepart vi exercises
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 codethis eases debuggingcomprehensionand maintenance polymorphism this is more property of oop than reason for using itbut by supporting code generalitypolymorphism makes code more flexible and widely applicableand hence more reusable other andof coursethe number one reason students gave for using oopit looks good on resume(oki threw this one in as jokebut it is important to be familiar with oop if you plan to work in the software field today finallykeep in mind what said at the beginning of this part of the bookyou won' fully appreciate oop until you've used it for while pick projectstudy larger exampleswork through the exercises--do whatever it takes to get your feet wet with oo codeit' worth the effort advanced class topics
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 which has two variations (listed separately hereand the last of which was an optional extension until python and try/except catch and recover from exceptions raised by pythonor by you try/finally perform cleanup actionswhether exceptions occur or not raise trigger an exception manually in your code assert conditionally trigger an exception in your code with/as implement context managers in python and later (optional in this topic was saved until nearly the end of the book because you need to know about classes to code exceptions of your own with few exceptions (pun intended)thoughyou'll find that exception handling is simple in python because it' integrated into the language itself as another high-level tool why use exceptionsin nutshellexceptions let us jump out of arbitrarily large chunks of program consider the hypothetical pizza-making robot we discussed earlier in the book suppose we took the idea seriously and actually built such machine to make pizzaour culinary automaton would need to execute planwhich we would implement as
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 caseswe might as well abandon the entire plan that' exactly what exceptions let you doyou can jump to an exception handler in single stepabandoning all function calls begun since the exception handler was entered code in the exception handler can then respond to the raised exception as appropriate (by calling the fire departmentfor instance!one way to think of an exception is as sort of structured "super go to an exception handler try statementleaves marker and executes some code somewhere further ahead in the programan exception is raised that makes python jump back to that markerabandoning any active functions that were called after the marker was left this protocol provides coherent way to respond to unusual events moreoverbecause python jumps to the handler statement immediatelyyour code is simpler--there is usually no need to check status codes after every call to function that could possibly fail exception roles in python programsexceptions are typically used for variety of purposes here are some of their most common roleserror handling python raises exceptions whenever it detects errors in programs at runtime you can catch and respond to the errors in your codeor ignore the exceptions that are raised if an error is ignoredpython' default exception-handling behavior kicks init stops the program and prints an error message if you don' want this default behaviorcode try statement to catch and recover from the exception--python will jump to your try handler when the error is detectedand your program will resume execution after the try event notification exceptions can also be used to signal valid conditions without you having to pass result flags around program or test them explicitly for instancea search routine might raise an exception on failurerather than returning an integer result code-and hoping that the code will never be valid resultspecial-case handling sometimes condition may occur so rarely that it' hard to justify convoluting your code to handle it in multiple places you can often eliminate special-case code by handling unusual cases in exception handlers in higher levels of your program an exception basics
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 control flows finallybecause exceptions are sort of high-level and structured "go to,you can use them as the basis for implementing exotic control flows for instancealthough the language does not explicitly support backtrackingyou can implement it in python by using exceptions and bit of support logic to unwind assignments there is no "go tostatement in python (thankfully!)but exceptions can sometimes serve similar rolesa raisefor instancecan be used to jump out of multiple loops we saw some of these roles briefly earlierand will study typical exception use cases in action later in this part of the book for nowlet' get started with look at python' exception-processing tools exceptionsthe short story compared to some other core language topics we've met in this bookexceptions are fairly lightweight tool in python because they are so simplelet' jump right into some code default exception handler suppose we write the following functiondef fetcher(objindex)return obj[indexthere' not much to this function--it simply indexes an object on passed-in index in normal operationit returns the result of legal indexx 'spamfetcher( 'mlike [ but true backtracking is not part of the python language backtracking undoes all computations before it jumpsbut python exceptions do notvariables assigned between the time try statement is entered and the time an exception is raised are not reset to their prior values even the generator functions and expressions we met in don' do full backtracking--they simply respond to next(grequests by restoring state and resuming for more on backtrackingsee books on artificial intelligence or the prolog or icon programming languages exceptionsthe short story
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 because our code does not explicitly catch this exceptionit filters back up to the top level of the program and invokes the default exception handlerwhich simply prints the standard error message by this point in the bookyou've probably seen your share of standard error messages they include the exception that was raisedalong with stack trace-- list of all the lines and functions that were active when the exception occurred the error message text here was printed by python it can vary slightly per releaseand even per interactive shellso you shouldn' rely upon its exact form--in either this book or your code when you're coding interactively in the basic shell interfacethe filename is just ",meaning the standard input stream when working in the idle gui' interactive shellthe filename is ",and source lines are displayedtoo either wayfile line numbers are not very meaningful when there is no file (we'll see more interesting error messages later in this part of the book)fetcher( traceback (most recent call last)file ""line in fetcher( file ""line in fetcher return obj[indexindexerrorstring index out of range default handler idle gui interface in more realistic program launched outside the interactive promptafter printing an error message the default handler at the top also terminates the program immediately that course of action makes sense for simple scriptserrors often should be fataland the best you can do when they occur is inspect the standard error message catching exceptions sometimesthis isn' what you wantthough server programsfor instancetypically need to remain active even after internal errors if you don' want the default exception behaviorwrap the call in try statement to catch exceptions yourselftryfetcher( except indexerrorprint('got exception' exception basics catch and recover
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 thisafter the except clause runswe wind up back at the python prompt in more realistic programtry statements not only catch exceptionsbut also recover from themdef catcher()tryfetcher( except indexerrorprint('got exception'print('continuing'catcher(got exception continuing this timeafter the exception is caught and handledthe program resumes execution after the entire try statement that caught it--which is why we get the "continuingmessage here we don' see the standard error messageand the program continues on its way normally notice that there' no way in python to go back to the code that triggered the exception (short of rerunning the code that reached that point all over againof courseonce you've caught the exceptioncontrol continues after the entire try that caught the exceptionnot after the statement that kicked it off in factpython clears the memory of any functions that were exited as result of the exceptionlike fetcher in our examplethey're not resumable the try both catches exceptionsand is where the program resumes presentation notethe interactive prompt' reappears in this part for some top-level try statementsbecause their code won' work if cut and pasted unless nested in function or class (the except and other lines must align with the tryand not have extra preceding spaces that are needed to illustrate their indentation structureto runsimply type or paste statements with prompts one line at time raising exceptions so farwe've been letting python raise exceptions for us by making mistakes (on purpose this time!)but our scripts can raise exceptions too--that isexceptions can be raised by python or by your programand can be caught or not to trigger an exception exceptionsthe short story
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 propagated up to the toplevel default exception handler and terminate the program with standard error messageraise indexerror traceback (most recent call last)file ""line in indexerror as we'll see in the next the assert statement can be used to trigger exceptionstoo--it' conditional raiseused mostly for debugging purposes during developmentassert false'nobody expects the spanish inquisition!traceback (most recent call last)file ""line in assertionerrornobody expects the spanish inquisitionuser-defined exceptions the raise statement introduced in the prior section raises built-in exception defined in python' built-in scope as you'll learn later in this part of the bookyou can also define new exceptions of your own that are specific to your programs user-defined exceptions are coded with classeswhich inherit from built-in exception classusually the class named exceptionclass alreadygotone(exception)pass user-defined exception def grail()raise alreadygotone(raise an instance trygrail(except alreadygotoneprint('got exception'got exception catch class name as we'll see in the next an as clause on an except can gain access to the exception object itself class-based exceptions allow scripts to build exception categorieswhich can inherit behaviorand have attached state information and methods they can also customize their error message text displayed if they're not caught exception basics
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 specifies termination actions that always execute "on the way out,regardless of whether an exception occurs in the try block or nottryfetcher( finallyprint('after fetch''mafter fetch termination actions hereif the try block finishes without an exceptionthe finally block will runand the program will resume after the entire try in this casethis statement seems bit silly --we might as well have simply typed the print right after call to the functionand skipped the try altogetherfetcher( print('after fetch'there is problem with coding this waythoughif the function call raises an exceptionthe print will never be reached the try/finally combination avoids this pitfall--when an exception does occur in try blockfinally blocks are executed while the program is being unwounddef after()tryfetcher( finallyprint('after fetch'print('after try?'after(after fetch traceback (most recent call last)file ""line in file ""line in after file ""line in fetcher indexerrorstring index out of range exceptionsthe short story
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 continues after the trydef after()tryfetcher( finallyprint('after fetch'print('after try?'after(after fetch after tryin practicetry/except combinations are useful for catching and recovering from exceptionsand try/finally combinations come in handy to guarantee that termination actions will fire regardless of any exceptions that may occur in the try block' code for instanceyou might use try/except to catch errors raised by code that you import from third-party libraryand try/finally to ensure that calls to close files or terminate server connections are always run we'll see some such practical examples later in this part of the book although they serve conceptually distinct purposesas of python we can mix except and finally clauses in the same try statement--the finally is run on the way out regardless of whether an exception was raisedand regardless of whether the exception was caught by an except clause as we'll learn in the next python and both provide an alternative to try/finally when using some types of objects the with/as statement runs an object' context management logic to guarantee that termination actions occurirrespective of any exceptions in its nested blockwith open('lumberjack txt'' 'as filefile write('the larch!\ 'always close file on exit although this option requires fewer lines of codeit' applicable only when processing certain object typesso try/finally is more general termination structureand is often simpler than coding class in cases where with is not already supported on the other handwith/as may also run startup actions tooand supports user-defined context management code with access to python' full oop toolset why you will careerror checks one way to see how exceptions are useful is to compare coding styles in python and languages without exceptions for instanceif you want to write robust programs in the languageyou generally have to test return values or status codes after every exception basics
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 factrealistic programs often have as much code devoted to error detection as to doing actual work but in pythonyou don' have to be so methodical (and neurotic!you can instead wrap arbitrarily vast pieces of program in exception handlers and simply write the parts that do the actual workassuming all is normally welldef dostuff()dofirstthing(donextthing(dolastthing(python code we don' care about exceptions hereso we don' need to detect them if __name__ ='__main__'trydostuff(this is where we care about resultsexceptso it' the only place we must check badending(elsegoodending(because control jumps immediately to handler when an exception occursthere' no need to instrument all your code to guard for errorsand there' no extra performance overhead to run all the tests moreoverbecause python detects errors automaticallyyour code often doesn' need to check for errors in the first place the upshot is that exceptions let you largely ignore the unusual cases and avoid error-checking code that can distract from your program' goals summary and that is the majority of the exception storyexceptions really are simple tool to summarizepython exceptions are high-level control flow device they may be raised by pythonor by your own programs in both casesthey may be ignored (to trigger the default error message)or caught by try statements (to be processed by your summary
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 termination actions are carried out for objects that support it in the rest of this part of the bookwe'll fill in some of the details about the statements involvedexamine the other sorts of clauses that can appear under tryand discuss class-based exception objects the next begins our tour by taking closer look at the statements we introduced here before you turn the pagethoughhere are few quiz questions to review test your knowledgequiz name three things that exception processing is good for what happens to an exception if you don' do anything special to handle it how can your script recover from an exception name two ways to trigger exceptions in your script name two ways to specify actions to be run at termination timewhether an exception occurs or not test your knowledgeanswers exception processing is useful for error handlingtermination actionsand event notification it can also simplify the handling of special cases and can be used to implement alternative control flows as sort of structured "go tooperation in generalexception processing also cuts down on the amount of error-checking code your program may require--because all errors filter up to handlersyou may not need to test the outcome of every operation any uncaught exception eventually filters up to the default exception handler python provides at the top of your program this handler prints the familiar error message and shuts down your program if you don' want the default message and shutdownyou can code try/except statements to catch and recover from exceptions that are raised within its nested code block once an exception is caughtthe exception is terminated and your program continues after the try the raise and assert statements can be used to trigger an exceptionexactly as if it had been raised by python itself in principleyou can also raise an exception by making programming mistakebut that' not usually an explicit goal exception basics
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 these statements are mostly straightforwardthey offer powerful tools for dealing with exceptional conditions in python code one procedural note up frontthe exception story has changed in major ways in recent years as of python the finally clause can appear in the same try statement as except and else clauses (previouslythey could not be combinedalsoas of python and the new with context manager statement has become officialand user-defined exceptions must now be coded as class instanceswhich should inherit from built-in exception superclass moreover sports slightly modified syntax for the raise statement and except clausessome of which is available in and will focus on the state of exceptions in recent python and releases in this editionbut because you are still very likely to see the original techniques in code for some time to comealong the way 'll point out how things have evolved in this domain the try/except/else statement now that we've seen the basicsit' time for the details in the following discussioni'll first present try/except/else and try/finally as separate statementsbecause in versions of python prior to they serve distinct roles and cannot be combinedand still are at least logically distinct today per the preceding notein python and later except and finally can be mixed in single try statementwe'll see the implications of that merging after we've explored the two original forms in isolation
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' the general and most complete format in python xtrystatements except name statements except (name name )statements except name as varstatements exceptstatements elsestatements run this main action first run if name is raised during try block run if any of these exceptions occur run if name is raisedassign instance raised to var run for all other exceptions raised run if no exception was raised during try block semanticallythe block under the try header in this statement represents the main action of the statement--the code you're trying to run and wrap in error processing logic the except clauses define handlers for exceptions raised during the try blockand the else clause (if codedprovides handler to be run if no exceptions occur the var entry here has to do with feature of raise statements and exception classeswhich we will discuss in full later in this how try statements work operationallyhere' how try statements are run when try statement is enteredpython marks the current program context so it can return to it if an exception occurs the statements nested under the try header are run first what happens next depends on whether exceptions are raised while the try block' statements are runningand whether they match those that the try is watching forif an exception occurs while the try block' statements are runningand the exception matches one that the statement namespython jumps back to the try and runs the statements under the first except clause that matches the raised exceptionafter assigning the raised exception object to the variable named after the as keyword in the clause (if presentafter the except block runscontrol then resumes below the entire try statement (unless the except block itself raises another exceptionin which case the process is started anew from this point in the codeif an exception occurs while the try block' statements are runningbut the exception does not match one that the statement namesthe exception is propagated up to the next most recently entered try statement that matches the exceptionif no such matching try statement can be found and the search reaches the top level of the processpython kills the program and prints default error message exception coding details
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 exceptions named in except clauses by superclass relationships we'll explore in the next and the empty except clause (with no exception namematches all (or all otherexceptions the except clauses are focused exception handlers--they catch exceptions that occur only within the statements in the associated try block howeveras the try block' statements can call functions coded elsewhere in programthe source of an exception may be outside the try statement itself in facta try block might invoke arbitrarily large amounts of program code--including code that may have try statements of its ownwhich will be searched first when exceptions occur that istry statements can nest at runtimea topic 'll have more to say about in try statement clauses when you write try statementa variety of clauses can appear after the try header table - summarizes all the possible forms--you must use at least one we've already met some of theseas you knowexcept clauses catch exceptionsfinally clauses run on the way outand else clauses run if no exceptions are encountered formallythere may be any number of except clausesbut you can code else only if there is at least one exceptand there can be only one else and one finally through python the finally clause must appear alone (without else or except)the tryfinally is really different statement as of python howevera finally can appear in the same statement as except and else (more on the ordering rules later in this when we meet the unified try statementtable - try statement clause forms clause form interpretation exceptcatch all (or all otherexception types except namecatch specific exception only except name as valuecatch the listed exception and assign its instance except (name name )catch any of the listed exceptions except (name name as valuecatch any listed exception and assign its instance elserun if no exceptions are raised in the try block finallyalways perform this block on exit the try/except/else statement
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 set of exceptions in parentheses (except ( ):catch any of the listed exceptions because python looks for match within given try by inspecting the except clauses from top to bottomthe parenthesized version has the same effect as listing each exception in its own except clausebut you have to code the statement body associated with each only once here' an example of multiple except clauses at workwhich demonstrates just how specific your handlers can betryaction(except nameerrorexcept indexerrorexcept keyerrorexcept (attributeerrortypeerrorsyntaxerror)elsein this exampleif an exception is raised while the call to the action function is runningpython returns to the try and searches for the first except that names the exception raised it inspects the except clauses from top to bottom and left to rightand runs the statements under the first one that matches if none matchthe exception is propagated past this try note that the else runs only when no exception occurs in action--it does not run when an exception without matching except is raised catching allthe empty except and exception if you really want general "catchallclausean empty except does the tricktryaction(except nameerrorexcept indexerrorexcepthandle nameerror handle indexerror handle all other exceptions exception coding details
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 without listing anythingtryaction(exceptcatch all possible exceptions empty excepts also raise some design issuesthough although convenientthey may catch unexpected system exceptions unrelated to your codeand they may inadvertently intercept exceptions meant for another handler for exampleeven system exit calls and ctrl- key combinations in python trigger exceptionsand you usually want these to pass even worsethe empty except may also catch genuine programming mistakes for which you probably want to see an error message we'll revisit this as gotcha at the end of this part of the book for nowi'll just say"use with care python more strongly supports an alternative that solves one of these problems-catching an exception named exception has almost the same effect as an empty exceptbut ignores exceptions related to system exitstryaction(except exceptioncatch all possible exceptionsexcept exits we'll explore how this form works its voodoo formally in the next when we study exception classes in shortit works because exceptions match if they are subclass of one named in an except clauseand exception is superclass of all the exceptions you should generally catch this way this form has most of the same convenience of the empty exceptwithout the risk of catching exit events though betterit also has some of the same dangers--especially with regard to masking programming errors version skew notesee also the raise statement ahead for more on the as portion of except clauses in try syntacticallypython requires the except as vhandler clause form listed in table - and used in this bookrather than the older except evform the latter form is still available (but not recommendedin python and if usedit' converted to the former the change was made to eliminate confusion regarding the dual role of commas in the older form in this formtwo alternate exceptions are properly coded as except ( )because supports the as form onlycommas in handler clause are always taken to mean tupleregardless of whether parentheses are used or notand the values are interpreted as alternative exceptions to be caught the try/except/else statement
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 setting and checking boolean flagswhether the flow of control has proceeded past try statement because no exception was raisedor because an exception occurred and was handled either waywe wind up after the trytryrun code except indexerrorhandle exception did we get here because the try failed or notmuch like the way else clauses in loops make the exit cause more apparentthe else clause provides syntax in try that makes what has happened obvious and unambiguoustryrun code except indexerrorhandle exception elseno exception occurred you can almost emulate an else clause by moving its code into the try blocktryrun code no exception occurred except indexerrorhandle exception this can lead to incorrect exception classificationsthough if the "no exception occurredaction triggers an indexerrorit will register as failure of the try block and erroneously trigger the exception handler below the try (subtlebut true!by using an explicit else clause insteadyou make the logic more obvious and guarantee that except handlers will run only for real failures in the code you're wrapping in trynot for failures in the else no-exception case' action exampledefault behavior because the control flow through program is easier to capture in python than in englishlet' run some examples that further illustrate exception basics in the context of larger code samples in files exception coding details
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 the exception it triggerspython kills the program and prints messagepython bad py traceback (most recent call last)file "bad py"line in gosouth( file "bad py"line in gosouth print(gobad( )file "bad py"line in gobad return zerodivisionerrordivision by zero ran this in shell window with python the message consists of stack trace ("traceback"and the name of and details about the exception that was raised the stack trace lists all lines active when the exception occurredfrom oldest to newest note that because we're not working at the interactive promptin this case the file and line number information is more useful for examplehere we can see that the bad divide happens at the last entry in the trace--line of the file bad pya return statement because python detects and reports all errors at runtime by raising exceptionsexceptions are intimately bound up with the ideas of error handling and debugging in general if you've worked through this book' examplesyou've undoubtedly seen an exception or two along the way--even typos usually generate syntaxerror or other exception when file is imported or executed (that' when the compiler is runby defaultyou get useful error display like the one just shownwhich helps you track down the problem oftenthis standard error message is all you need to resolve problems in your code for more heavy-duty debugging jobsyou can catch exceptions with try statements as mentioned in the prior the text of error messages and stack traces tends to vary slightly over time and shells don' be alarmed if your error messages don' exactly match mine when ran this example in python ' idle guifor instanceits error message text showed filenames with full absolute directory paths the try/except/else statement
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 in your code sometimesthoughyou'll want to catch errors and recover from them instead if you don' want your program terminated when python raises an exceptionsimply catch it by wrapping the program logic in try this is an important capability for programs such as network serverswhich must keep running persistently for examplethe following codein the file kaboom pycatches and recovers from the typeerror python raises immediately when you try to concatenate list and string (rememberthe operator expects the same sequence type on both sides)def kaboom(xy)print( ytrigger typeerror trykaboom([ ]'spam'except typeerrorprint('hello world!'print('resuming here'catch and recover here continue here if exception or not when the exception occurs in the function kaboomcontrol jumps to the try statement' except clausewhich prints message since an exception is "deadafter it' been caught like thisthe program continues executing below the try rather than being terminated by python in effectthe code processes and clears the errorand your script recoverspython kaboom py hello worldresuming here keep in mind that once you've caught an errorcontrol resumes at the place where you caught it ( after the try)there is no direct way to go back to the place where the exception occurred (herein the function kaboomin sensethis makes exceptions more like simple jumps than function calls--there is no way to return to the code that triggered the error the try/finally statement the other flavor of the try statement is specialization that has to do with finalization ( terminationactions if finally clause is included in trypython will always run its block of statements "on the way outof the try statementwhether an exception occurred while the try block was running or not its general form is exception coding details
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 block is runningpython continues on to run the finally blockand then continues execution past the try statement if an exception does occur during the try block' runpython still comes back and runs the finally blockbut it then propagates the exception up to previously entered try or the top-level default handlerthe program does not resume execution below the finally clause' try statement that isthe finally block is run even if an exception is raisedbut unlike an exceptthe finally does not terminate the exception--it continues being raised after the finally block runs the try/finally form is useful when you want to be completely sure that an action will happen after some code runsregardless of the exception behavior of the program in practiceit allows you to specify cleanup actions that always must occursuch as file closes and server disconnects where required note that the finally clause cannot be used in the same try statement as except and else in python and earlierso the try/finally is best thought of as distinct statement form if you are using an older release in python and laterhoweverfinally can appear in the same statement as except and elseso today there is really single try statement with many optional clauses (more about this shortlywhichever version you usethoughthe finally clause still serves the same purpose--to specify "cleanupactions that must always be runregardless of any exceptions as we'll also see later in this as of python and the new with statement and its context managers provide an object-based way to do similar work for exit actions unlike finallythis new statement also supports entry actionsbut it is limited in scope to objects that implement the context manager protocol it leverages examplecoding termination actions with try/finally we saw some simple try/finally examples in the prior here' more realistic example that illustrates typical role for this statementclass myerror(exception)pass def stuff(file)raise myerror(file open('data'' 'open an output file (this can fail toothe try/finally statement
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 try or the default top-level handlerwhich prints the standard error message and shuts down the program hencethe statement after this try is never reached if the function here did not raise an exceptionthe program would still execute the finally block to close the filebut it would then continue below the entire try statement in this specific casewe've wrapped call to file-processing function in try with finally clause to make sure that the file is always closedand thus finalizedwhether the function triggers an exception or not this waylater code can be sure that the file' output buffer' content has been flushed from memory to disk similar code structure can guarantee that server connections are closedand so on as we learned in file objects are automatically closed on garbage collection in standard python (cpython)this is especially useful for temporary files that we don' assign to variables howeverit' not always easy to predict when garbage collection will occurespecially in larger programs or alternative python implementations with differing garbage collection policies ( jythonpypythe try statement makes file closes more explicit and predictable and pertains to specific block of code it ensures that the file will be closed on block exitregardless of whether an exception occurs or not this particular example' function isn' all that useful (it just raises an exception)but wrapping calls in try/finally statements is good way to ensure that your closing-time termination activities always run againpython always runs the code in your finally blocksregardless of whether an exception happens in the try block notice how the user-defined exception here is again defined with class--as we'll see more formally in the next exceptions today must all be class instances in and later releases in both lines unified try/except/finally in all versions of python prior to release (for its first years of lifemore or less)the try statement came in two flavors and was really two separate statements--we could either use finally to ensure that cleanup code was always runor write unless python crashes completelyof course it does good job of avoiding thisthoughby checking all possible errors as program runs when program does crash hardit is usually due to bug in linkedin extension codeoutside of python' scope exception coding details
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 actions in python and laterthoughthe two statements have merged todaywe can mix finallyexceptand else clauses in the same statement--in part because of similar utility in the java language that iswe can now write statement of this formtrymain-action except exception handler except exception handler elseelse-block finallyfinally-block merged form catch exceptions no-exception handler the finally encloses all else the code in this statement' main-action block is executed firstas usual if that code raises an exceptionall the except blocks are testedone after anotherlooking for match to the exception raised if the exception raised is exception the handler block is executedif it' exception handler is runand so on if no exception is raisedthe else-block is executed no matter what' happened previouslythe finally-block is executed once the main action block is complete and any raised exceptions have been handled in factthe code in the finally-block will be run even if there is an error in an exception handler or the else-block and new exception is raised as alwaysthe finally clause does not end the exception--if an exception is active when the finally-block is executedit continues to be propagated after the finallyblock runsand control jumps somewhere else in the program (to another tryor to the default top-level handlerif no exception is active when the finally is runcontrol resumes after the entire try statement the net effect is that the finally is always runregardless of whetheran exception occurred in the main action and was handled an exception occurred in the main action and was not handled no exceptions occurred in the main action new exception was triggered in one of the handlers againthe finally serves to specify cleanup actions that must always occur on the way out of the tryregardless of what exceptions have been raised or handled unified try/except/finally
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 two partsexcepts with an optional elseand/or the finally in factit' more accurate to describe the merged statement' syntactic form this way (square brackets mean optional and star means zero-or-more here)trystatements except [type [as value]]statements [except [type [as value]]statements][elsestatements[finallystatementstrystatements finallystatements format [type [value]in python format because of these rulesthe else can appear only if there is at least one exceptand it' always possible to mix except and finallyregardless of whether an else appears or not it' also possible to mix finally and elsebut only if an except appears too (though the except can omit an exception name to catch everything and run raise statementdescribed laterto reraise the current exceptionif you violate any of these ordering rulespython will raise syntax error exception before your code runs combining finally and except by nesting prior to python it is actually possible to combine finally and except clauses in try by syntactically nesting try/except in the try block of try/finally statement we'll explore this technique more fully in but the basics may help clarify the meaning of combined try--the following has the same effect as the new merged form shown at the start of this sectionnested equivalent to merged form trytrymain-action except exception handler except exception handler exception coding details
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 form even sports the same mixing constraints of the unified statement form outlined in the preceding section howeverthis nested equivalent seems more obscure to someand requires more code than the new merged form--though just one four-character line plus extra indentation mixing finally into the same statement makes your code arguably easier to write and readand is generally preferred technique today unified try example here' demonstration of the merged try statement form at work the following filemergedexc pycodes four common scenarioswith print statements that describe the meaning of eachfile mergedexc py (python xsep '- '\nprint(sep 'exception raised and caught'tryx 'spam'[ except indexerrorprint('except run'finallyprint('finally run'print('after run'print(sep 'no exception raised'tryx 'spam'[ except indexerrorprint('except run'finallyprint('finally run'print('after run'print(sep 'no exception raisedwith else'tryx 'spam'[ except indexerrorprint('except run'elseunified try/except/finally
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 itemthough the error message text varies slightly trace through the code to see how exception handling produces the output of each of the four tests herec:\codepy - mergedexc py exception raised and caught except run finally run after run no exception raised finally run after run no exception raisedwith else else run finally run after run exception raised but not caught finally run traceback (most recent call last)file "mergedexc py"line in zerodivisionerrordivision by zero this example uses built-in operations in the main action to trigger exceptions (or not)and it relies on the fact that python always checks for errors as code is running the next section shows how to raise exceptions manually instead the raise statement to trigger exceptions explicitlyyou can code raise statements their general form is simple-- raise statement consists of the word raiseoptionally followed by the class to be raised or an instance of it exception coding details
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 raise or within the raise statement itself if we pass class insteadpython calls the class with no constructor argumentsto create an instance to be raisedthis form is equivalent to adding parentheses after the class reference the last form reraises the most recently raised exceptionit' commonly used in exception handlers to propagate exceptions that have been caught version skew notepython no longer supports the raise excargs form that is still available in python in xuse the raise exc(argsinstance-creation call form described in this book instead the equivalent comma form in is legacy syntax provided for compatibility with the now-defunct string-based exceptions modeland it' deprecated in if usedit is converted to the call form as in earlier releasesa raise exc form is also allowed to name class-it is converted to raise exc(in both versionscalling the class constructor with no arguments besides its defunct comma syntaxpython ' raise also allowed for either string or class exceptionsbut the former is removed in deprecated in and not covered here except for brief mention in the next use classes for new exceptions today raising exceptions to make this clearerlet' look at some examples with built-in exceptionsthe following two forms are equivalent--both raise an instance of the exception class namedbut the first creates the instance implicitlyraise indexerror raise indexerror(class (instance createdinstance (created in statementwe can also create the instance ahead of time--because the raise statement accepts any kind of object referencethe following two examples raise indexerror just like the prior twoexc indexerror(raise exc create instance ahead of time excs [indexerrortypeerrorraise excs[ when an exception is raisedpython sends the raised instance along with the exception if try includes an except name as xclausethe variable will be assigned the instance provided in the raisethe raise statement
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 code with classes--the followingfor examplepasses to the exception class constructor arguments that become available in the handler through the assigned instanceclass myexc(exception)pass raise myexc('spam'exception class with constructor args tryexcept myexc as xinstance attributes available in handler print( argsbecause this encroaches on the next topicthoughi'll defer further details until then regardless of how you name themexceptions are always identified by class instance objectsand at most one is active at any given time once caught by an except clause anywhere in the programan exception dies ( won' propagate to another try)unless it' reraised by another raise statement or error scopes and try except variables we'll study exception objects in more detail in the next now that we've seen the as variable in actionthoughwe can finally clarify the related version-specific scope issue summarized in in python xthe exception reference variable name in an except clause is not localized to the clause itselfand is available after the associated block runsc:\codepy - try except exception as does not localize either way print integer division or modulo by zero zerodivisionerror('integer division or modulo by zero',this is true in whether we use the -style as or the earlier comma syntaxtry except exceptionx exception coding details
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 comma syntaxas noted earlier) :\codepy - try except exceptionxsyntaxerrorinvalid syntax try except exception as xprint(xdivision by zero nameerrorname 'xis not defined localizes 'asnames to except block unlike compression loop variablesthoughthis variable is removed after the except block exits in it does so because it would otherwise retain reference to the runtime call stackwhich would defer garbage collection and thus retain excess memory space this removal occursthougheven if you're using the name elsewhereand is more extreme policy than that used for comprehensionsx try except exception as xprint(xdivision by zero nameerrorname 'xis not defined { for in 'spam'{' '' '' '' ' localizes _and_ removes on exit / localizes onlynot removed because of thisyou should generally use unique variable names in your try statement' except clauseseven if they are localized by scope if you do need to reference the exception instance after the try statementsimply assign it to another name that won' be automatically removedthe raise statement
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 does not include an exception name or extra data value simply reraises the current exception this form is typically used if you need to catch and handle an exception but don' want the exception to die in your codetryraise indexerror('spam'except indexerrorprint('propagating'raise propagating traceback (most recent call last)file ""line in indexerrorspam exceptions remember arguments reraise most recent exception running raise this way reraises the exception and propagates it to higher handler (or the default handler at the topwhich stops the program with standard error messagenotice how the argument we passed to the exception class shows up in the error messagesyou'll learn why this happens in the next python exception chainingraise from exceptions can sometimes be triggered in response to other exceptions--both deliberately and by new program errors to support full disclosure in such casespython (but not xalso allows raise statements to have an optional from clauseraise newexception from otherexception when the from is used in an explicit raise requestthe expression following from specifies another exception class or instance to attach to the __cause__ attribute of the new exception being raised if the raised exception is not caughtpython prints both exceptions as part of the standard error messagetry except exception as eraise typeerror('bad'from exception coding details explicitly chained exceptions
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 followed automaticallythe previous exception is attached to the new exception' __context__ attribute and is again displayed in the standard error message if the exception goes uncaughttry exceptbadname traceback (most recent call last)file ""line in zerodivisionerrordivision by zero implicitly chained exceptions during handling of the above exceptionanother exception occurredtraceback (most recent call last)file ""line in nameerrorname 'badnameis not defined in both casesbecause the original exception objects thus attached to new exception objects may themselves have attached causesthe causality chain can be arbitrary longand is displayed in full in error messages that iserror messages might give more than two exceptions the net effect in both explicit and implicit contexts is to allow programmers to know all exceptions involvedwhen one exception triggers anothertrytryraise indexerror(except exception as eraise typeerror(from except exception as eraise syntaxerror(from traceback (most recent call last)file ""line in indexerror the above exception was the direct cause of the following exceptiontraceback (most recent call last)file ""line in typeerror the raise statement
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 clear which languages were borrowers in pythonit' still somewhat obscure extensionso we'll defer to python' manuals for more details in factpython adds way to stop exceptions from chainingper the following note python chained exception suppressionraise from none python introduces new syntax form--using none as the exception name in the raise from statementraise newexception from none this allows the display of the chained exception context described in the preceding section to be disabled this makes for less cluttered error messages in applications that convert between exception types while processing exception chains the assert statement as somewhat special case for debugging purposespython includes the assert statement it is mostly just syntactic shorthand for common raise usage patternand an assert can be thought of as conditional raise statement statement of the formassert testdata the data part is optional works like the following codeif __debug__if not testraise assertionerror(datain other wordsif the test evaluates to falsepython raises an exceptionthe data item (if it' providedis used as the exception' constructor argument like all exceptionsthe assertionerror exception will kill your program if it' not caught with tryin which case the data item shows up as part of the standard error message exception coding details
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 exampletrapping constraints (but not errors!assertions are typically used to verify program conditions during development when displayedtheir error message text automatically includes source code line information and the value listed in the assert statement consider the file asserter pydef ( )assert ' must be negativereturn * python import asserter asserter ( traceback (most recent call last)file ""line in file \asserter py"line in assert ' must be negativeassertionerrorx must be negative it' important to keep in mind that assert is mostly intended for trapping user-defined constraintsnot for catching genuine programming errors because python traps programming errors itselfthere is usually no need to code assert to catch things like outof-bounds indexestype mismatchesand zero dividesdef reciprocal( )assert ! return generally useless assertpython checks for zero automatically such assert use cases are usually superfluous--because python raises exceptions on errors automaticallyyou might as well let it do the job for you as ruleyou don' need to do error checking explicitly in your own code of coursethere are exceptions for most rules--as suggested earlier in the bookif function has to perform long-running or unrecoverable actions before it reaches the place where an exception will be triggeredyou still might want to test for errors even in this casethoughbe careful not to make your tests overly specific or restrictiveor you will limit your code' utility for another example of common assert usagesee the abstract superclass example in therewe used assert to make calls to undefined methods fail with message it' rare but useful tool the assert statement
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 an option in but must be enabled there with an import of this formfrom __future__ import with_statement the with statement is also similar to "usingstatement in the clanguage although somewhat optional and advanced tools-oriented topic (and once candidate for the next part of the book)context managers are lightweight and useful enough to group with the rest of the exception toolset here in shortthe with/as statement is designed to be an alternative to common tryfinally usage idiomlike that statementwith is in large part intended for specifying termination-time or "cleanupactivities that must run regardless of whether an exception occurs during processing step unlike try/finallythe with statement is based upon an object protocol for specifying actions to be run around block of code this makes with less generalqualifies it as redundant in termination rolesand requires coding classes for objects that do not support its protocol on the other handwith also handles entry actionscan reduce code sizeand allows code contexts to be managed with full oop python enhances some built-in tools with context managerssuch as files that automatically close themselves and thread locks that automatically lock and unlockbut programmers can code context managers of their own with classestoo let' take brief look at the statement and its implicit protocol basic usage the basic format of the with statement looks like thiswith an optional part in square brackets herewith expression [as variable]with-block the expression here is assumed to return an object that supports the context management protocol (more on this protocol in momentthis object may also return value that will be assigned to the name variable if the optional as clause is present note that the variable is not necessarily assigned the result of the expressionthe result of the expression is the object that supports the context protocoland the variable may be assigned something else intended to be used inside the statement the object returned by the expression may then run startup code before the with-block is startedas well as termination code after the block is doneregardless of whether the block raised an exception or not exception coding details
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\data'as myfilefor line in myfileprint(linemore code here herethe call to open returns simple file object that is assigned to the name myfile we can use myfile with the usual file tools--in this casethe file iterator reads line by line in the for loop howeverthis object also supports the context management protocol used by the with statement after this with statement has runthe context management machinery guarantees that the file object referenced by myfile is automatically closedeven if the for loop raised an exception while processing the file although file objects may be automatically closed on garbage collectionit' not always straightforward to know when that will occurespecially when using alternative python implementations the with statement in this role is an alternative that allows us to be sure that the close will occur after execution of specific block of code as we saw earlierwe can achieve similar effect with the more general and explicit try/finally statementbut it requires three more lines of administrative code in this case (four instead of just one)myfile open( ' :\misc\data'tryfor line in myfileprint(linemore code here finallymyfile close(we won' cover python' multithreading modules in this book (for more on that topicsee follow-up application-level texts such as programming pythonbut the lock and condition synchronization objects they define may also be used with the with statementbecause they support the context management protocol--in this case adding both entry and exit actions around blocklock threading lock(with lockcritical section of code access shared resources afterimport threading herethe context management machinery guarantees that the lock is automatically acquired before the block is executed and released once the block is completeregardless of exception outcomes with/as context managers
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 what it was before the statement began to do the same with tryfinallywe would need to save the context before and restore it manually after the nested block the context management protocol although some built-in types come with context managerswe can also write new ones of our own to implement context managersclasses use special methods that fall into the operator overloading category to tap into the with statement the interface expected of objects used in with statements is somewhat complexand most programmers only need to know how to use existing context managers for tool builders who might want to write new application-specific context managersthoughlet' take quick look at what' involved here' how the with statement actually works the expression is evaluatedresulting in an object known as context manager that must have __enter__ and __exit__ methods the context manager' __enter__ method is called the value it returns is assigned to the variable in the as clause if presentor simply discarded otherwise the code in the nested with block is executed if the with block raises an exceptionthe __exit__(typevaluetracebackmethod is called with the exception details these are the same three values returned by sys exc_infodescribed in the python manuals and later in this part of the book if this method returns false valuethe exception is reraisedotherwisethe exception is terminated the exception should normally be reraised so that it is propagated outside the with statement if the with block does not raise an exceptionthe __exit__ method is still calledbut its typevalueand traceback arguments are all passed in as none let' look at quick demo of the protocol in action the followingfile withas pydefines context manager object that traces the entry and exit of the with block in any with statement it is used forclass traceblockdef message(selfarg)print('running argdef __enter__(self) exception coding details
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 reached'notice that this class' __exit__ method returns false to propagate the exceptiondeleting the return statement would have the same effectas the default none return value of functions is false by definition also notice that the __enter__ method returns self as the object to assign to the as variablein other use casesthis might return completely different object instead when runthe context manager traces the entry and exit of the with statement block with its __enter__ and __exit__ methods here' the script in action being run under either python or (as usualmileage varies slightly in some displaysand this runs on and if enabled) :\codepy - withas py starting with block running test reached exited normally starting with block running test raise an exceptiontraceback (most recent call last)file "withas py"line in raise typeerror typeerror context managers can also utilize oop state information and inheritancebut are somewhat advanced devices for tool buildersso we'll skip additional details here (see python' standard manuals for the full story--for examplethere' new contextlib standard module that provides additional tools for coding context managersfor simpler purposesthe try/finally statement provides sufficient support for terminationtime activities without coding classes with/as context managers
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 exitsregardless of exception outcomeswith open('data'as finopen('res'' 'as foutfor line in finif 'some keyin linefout write(lineany number of context manager items may be listedand multiple items work the same as nested with statements in pythons that support thisthe following codewith (as ab(as bstatements is equivalent to the followingwhich also works in and with (as awith (as bstatements python ' release notes have additional detailsbut here' quick look at the extension in action--to implement parallel lines scan of two filesthe following uses with to open two files at once and zip together their lineswithout having to manually close when finished (assuming manual closes are required)with open('script py'as open('script py'as for pair in zip( )print(pair(' first python script\ ''import sys\ '('import sys load library module\ ''print(sys path)\ '('print(sys platform)\ '' \ '('print( * raise to power\ ''print( * )\ 'you might use this coding structure to do line-by-line comparison of two text filesfor example--replace the print with an if for simple file comparison operationand use enumerate for line numberswith open('script py'as open('script py'as for (linenum(line line )in enumerate(zip( ))if line !line print('% \ % \ % (linenumline line )stillthe preceding technique isn' all that useful in cpythonbecause input file objects don' require buffer flushand file objects are closed automatically when reclaimed if still open in cpythonthe files would be reclaimed immediately if the parallel scan were coded the following simpler wayfor pair in zip(open('script py')open('script py'))print(pair exception coding details same effectauto close
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 finfout write(line upper()print(open('upper py'read()import sys print(sys pathx print( * in both caseswe can instead simply open files in individual statements and close after processing if neededand in some scripts we probably should--there' no point in using statements that catch an exception if it means your program is out of business anyhowfin open('script py'fout open('upper py'' 'for line in finfout write(line upper()same effect as preceding codeauto close howeverin cases where programs must continue after exceptionsthe with forms also implicitly catch exceptionsand thereby also avoid try/finally in cases where close is required the equivalent without with is more explicitbut requires noticeably more codefin open('script py'fout open('upper py'' 'tryfor line in finfout write(line upper()finallyfin close(fout close(same effect but explicit close on error on the other handthe try/finally is single tool that applies to all finalization caseswhereas the with adds second tool that can be more concisebut applies to only certain objects typesand doubles the required knowledge base of programmers as usualyou'll have to weigh the tradeoffs for yourself summary in this we took more detailed look at exception processing by exploring the statements related to exceptions in pythontry to catch themraise to trigger themassert to raise them conditionallyand with to wrap code blocks in context managers that specify entry and exit actions summary
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 short quiz on the basics covered here test your knowledgequiz what is the try statement for what are the two common variations of the try statement what is the raise statement for what is the assert statement designed to doand what other statement is it like what is the with/as statement designed to doand what other statement is it liketest your knowledgeanswers the try statement catches and recovers from exceptions--it specifies block of code to runand one or more handlers for exceptions that may be raised during the block' execution the two common variations on the try statement are try/except/else (for catching exceptionsand try/finally (for specifying cleanup actions that must occur whether an exception is raised or notthrough python these were separate statements that could be combined by syntactic nestingin and laterexcept and finally blocks may be mixed in the same statementso the two statement forms are merged in the merged formthe finally is still run on the way out of the tryregardless of what exceptions may have been raised or handled in factthe merged form is equivalent to nesting try/except/else in try/finallyand the two still have logically distinct roles the raise statement raises (triggersan exception python raises built-in exceptions on errors internallybut your scripts can trigger built-in or user-defined exceptions with raisetoo the assert statement raises an assertionerror exception if condition is false it works like conditional raise statement wrapped up in an if statementand can be disabled with - switch the with/as statement is designed to automate startup and termination activities that must occur around block of code it is roughly like try/finally statement in that its exit actions run whether an exception occurred or notbut it allows richer object-based protocol for specifying entry and exit actionsand may reduce exception coding details
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 against exceptions named in try statements although this means you must use object-oriented programming to define new exceptions in your programs--and introduces knowledge dependency that deferred full exception coverage to this part of the book--basing exceptions on classes and oop offers number of benefits among themclass-based exceptionscan be organized into categories exceptions coded as classes support future changes by providing categories--adding new exceptions in the future won' generally require changes in try statements have state information and behavior exception classes provide natural place for us to store context information and tools for use in the try handler--instances have access to both attached state information and callable methods support inheritance class-based exceptions can participate in inheritance hierarchies to obtain and customize common behavior--inherited display methodsfor examplecan provide common look and feel for error messages because of these advantagesclass-based exceptions support program evolution and larger systems well as we'll findall built-in exceptions are identified by classes and are organized into an inheritance treefor the reasons just listed you can do the same with user-defined exceptions of your own in factin python the built-in exceptions we'll study here turn out to be integral to new exceptions you define because requires user-defined exceptions to inherit from built-in exception superclasses that provide useful defaults for printing and state retentionthe task of coding user-defined exceptions also involves understanding the roles of these built-ins
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 normal exception types--naming it in handler will thus catch everything most programs should python allows standalone classic classes to serve as exceptionstoobut it requires new-style classes to be derived from built-in exception classesthe same as exceptionsback to the future once upon time (wellprior to python and )it was possible to define exceptions in two different ways this complicated try statementsraise statementsand python in general todaythere is only one way to do it this is good thingit removes from the language substantial cruft accumulated for the sake of backward compatibility because the old way helps explain why exceptions are as they are todaythoughand because it' not really possible to completely erase the history of something that has been used by on the order of million people over the course of nearly two decadeslet' begin our exploration of the present with brief look at the past string exceptions are right outprior to python and it was possible to define exceptions with both class instances and string objects string-based exceptions began issuing deprecation warnings in and were removed in and so today you should use class-based exceptionsas shown in this book if you work with legacy codethoughyou might still come across string exceptions they might also appear in bookstutorialsand web resources written few years ago (which qualifies as an eternity in python years!string exceptions were straightforward to use--any string would doand they matched by object identitynot value (that isusing isnot ==) :\codec:\python \python myexc "my exception stringtryraise myexc except myexcprint('caught'caught were we ever this youngthis form of exception was removed because it was not as good as classes for larger programs and code maintenance in modern pythonsstring exceptions trigger exceptions insteadc:\codepy - raise 'spam exception objects
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 earlierhoweverclasses have some added advantages that merit quick look most prominentlythey allow us to identify exception categories that are more flexible to use and maintain than simple strings moreoverclasses naturally allow for attached exception details and support inheritance because they are seen by many as the better approachthey are now required coding details asidethe chief difference between string and class exceptions has to do with the way that exceptions raised are matched against except clauses in try statementsstring exceptions were matched by simple object identitythe raised exception was matched to except clauses by python' is test class exceptions are matched by superclass relationshipsthe raised exception matches an except clause if that except clause names the exception instance' class or any superclass of it that iswhen try statement' except clause lists superclassit catches instances of that superclassas well as instances of all its subclasses lower in the class tree the net effect is that class exceptions naturally support the construction of exception hierarchiessuperclasses become category namesand subclasses become specific kinds of exceptions within category by naming general exception superclassan except clause can catch an entire category of exceptions--any more specific subclass will match string exceptions had no such conceptbecause they were matched by simple object identitythere was no direct way to organize exceptions into more flexible categories or groups the net result was that exception handlers were coupled with exception sets in way that made changes difficult in addition to this category ideaclass-based exceptions better support exception state information (attached to instancesand allow exceptions to participate in inheritance hierarchies (to obtain common behaviorsbecause they offer all the benefits of classes and oop in generalthey provide more powerful alternative to the now-defunct string-based exceptions model in exchange for small amount of additional code exceptionsback to the future
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 exceptions within the category handlers that catch general will also catch any subclasses of itincluding specific and specific class general(exception)pass class specific (general)pass class specific (general)pass def raiser () general(raise raise superclass instance def raiser () specific (raise raise subclass instance def raiser () specific (raise raise different subclass instance for func in (raiser raiser raiser )tryfunc(except generalmatch general or any subclass of it import sys print('caught%ssys exc_info()[ ] :\codepython classexc py caughtcaughtcaughtthis code is mostly straightforwardbut here are few points to noticeexception superclass classes used to build exception category trees have very few requirements--in factin this example they are mostly emptywith bodies that do nothing but pass noticethoughhow the top-level class here inherits from the built-in exception class this is required in python xpython allows standalone classic classes to serve as exceptions toobut it requires new-style classes to be derived from built-in exception classes just as in although we don' employ it herebecause excep tion provides some useful behavior we'll meet laterit' good idea to inherit from it in either python raising instances in this codewe call classes to make instances for the raise statements in the class exception modelwe always raise and catch class instance object if we list class exception objects
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 exceptions the same try also catches the two specific exceptionsbecause they are subclasses of general--members of its category exception details the exception handler here uses the sys exc_info call--as we'll see in more detail in the next it' how we can grab hold of the most recently raised exception in generic fashion brieflythe first item in its result is the class of the exception raisedand the second is the actual instance raised in general except clause like the one here that catches all classes in categorysys exc_info is one way to determine exactly what' occurred in this particular caseit' equivalent to fetching the instance' __class__ attribute as we'll see in the next the sys exc_info scheme is also commonly used with empty except clauses that catch everything the last point merits further explanation when an exception is caughtwe can be sure that the instance raised is an instance of the class listed in the exceptor one of its more specific subclasses because of thisthe __class__ attribute of the instance also gives the exception type the following variant in classexc pyfor exampleworks the same as the prior example--it uses the as extension in its except clause to assign variable to the instance actually raisedclass general(exception)pass class specific (general)pass class specific (general)pass def raiser ()raise general(def raiser ()raise specific (def raiser ()raise specific (for func in (raiser raiser raiser )tryfunc(except general as xprint('caught%sx __class__x is the raised instance same as sys exc_info()[ because __class__ can be used like this to determine the specific type of exception raisedsys exc_info is more useful for empty except clauses that do not otherwise have way to access the instance or its class furthermoremore realistic programs usually should not have to care about which specific exception was raised at all--by calling methods of the exception class instance genericallywe automatically dispatch to behavior tailored for the exception raised exceptionsback to the future
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 coding list of exception names in parentheses within the except clausetryfunc(except (generalspecific specific )catch any of these this approach worked for the defunct string exception model too for large or high exception hierarchieshoweverit may be easier to catch categories using class-based categories than to list every member of category in single except clause perhaps more importantlyyou can extend exception hierarchies as software needs evolve by adding new subclasses without breaking existing code supposefor exampleyou code numeric programming library in pythonto be used by large number of people while you are writing your libraryyou identify two things that can go wrong with numbers in your code--division by zeroand numeric overflow you document these as the two standalone exceptions that your library may raisemathlib py class divzero(exception)pass class oflow(exception)pass def func()raise divzero(and so on nowwhen people use your librarythey typically wrap calls to your functions or classes in try statements that catch your two exceptionsafter allif they do not catch your exceptionsexceptions from your library will kill their codeclient py import mathlib trymathlib funcexcept (mathlib divzeromathlib oflow)handle and recover exception objects
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 for your users if they've listed your exceptions explicitlythey now have to go back and change every place they call your library to include the newly added exception nameclient py trymathlib funcexcept (mathlib divzeromathlib oflowmathlib uflow)handle and recover this may not be the end of the world if your library is used only in-houseyou can make the changes yourself you might also ship python script that tries to fix such code automatically (it would probably be only few dozen linesand it would guess right at least some of the timeif many people have to change all their try statements each time you alter your exception setthoughthis is not exactly the most polite of upgrade policies your users might try to avoid this pitfall by coding empty except clauses to catch all possible exceptionsclient py trymathlib funcexcepthandle and recover catch everything here (or catch exception superbut this workaround might catch more than they bargained for--things like running out of memorykeyboard interrupts (ctrl- )system exitsand even typos in their own try block' code will all trigger exceptionsand such things should passnot be caught and erroneously classified as library errors catching the exception super class improves on thisbut still intercepts--and thus may mask--program errors and reallyin this scenario users want to catch and recover from only the specific exceptions the library is defined and documented to raise if any other exception occurs during library callit' likely genuine bug in the library (and probably time to contact the vendor!as rule of thumbit' usually better to be specific than general in exception handlers--an idea we'll revisit as "gotchain the next why exception hierarchies
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 list the common superclass ( categoryto catch all of your library' exceptionsboth now and in the futureclient py import mathlib trymathlib funcexcept mathlib numerrreport and recover when you go back and hack (updateyour code againyou can add new exceptions as new subclasses of the common superclassmathlib py class uflow(numerr)pass the end result is that user code that catches your library' exceptions will keep workingunchanged in factyou are free to adddeleteand change exceptions arbitrarily in the future--as long as clients name the superclassand that superclass remains intactthey are insulated from changes in your exceptions set in other wordsclass exceptions provide better answer to maintenance issues than strings could class-based exception hierarchies also support state retention and inheritance in ways that make them ideal in larger programs to understand these rolesthoughwe first as clever student of mine suggestedthe library module could also provide tuple object that contains all the exceptions the library can possibly raise--the client could then import the tuple and name it in an except clause to catch all the library' exceptions (recall that including tuple in an except means catch any of its exceptionswhen new exceptions are added laterthe library can just expand the exported tuple this would workbut you' still need to keep the tuple up-to-date with raised exceptions inside the library module alsoclass hierarchies offer more benefits than just categories--they also support inherited state and methods and customization model that individual exceptions do not exception objects
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 prior section' exceptions class tree in python xall the familiar exceptions you've seen ( syntaxerrorare really just predefined classesavailable as built-in names in the module named builtinsin python xthey instead live in __builtin__ and are also attributes of the standard library module exceptions in additionpython organizes the built-in exceptions into hierarchyto support variety of catching modes for examplebaseexceptiontopmost rootprinting and constructor defaults the top-level root superclass of exceptions this class is not supposed to be directly inherited by user-defined classes (use exception insteadit provides default printing and state retention behavior inherited by subclasses if the str built-in is called on an instance of this class ( by print)the class returns the display strings of the constructor arguments passed when the instance was created (or an empty string if there were no argumentsin additionunless subclasses replace this class' constructorall of the arguments passed to this class at instance construction time are stored in its args attribute as tuple exceptionroot of user-defined exceptions the top-level root superclass of application-related exceptions this is an immediate subclass of baseexception and is superclass to every other built-in exceptionexcept the system exit event classes (systemexitkeyboardinterruptand genera torexitnearly all user-defined classes should inherit from this classnot baseex ception when this convention is followednaming exception in try statement' handler ensures that your program will catch everything but system exit eventswhich should normally be allowed to pass in effectexception becomes catchall in try statements and is more accurate than an empty except arithmeticerrorroot of numeric errors subclass of exceptionand the superclass of all numeric errors its subclasses identify specific numeric errorsoverflowerrorzerodivisionerrorand floating pointerror lookuperrorroot of indexing errors subclass of exceptionand the superclass category for indexing errors for both sequences and mappings--indexerror and keyerror--as well as some unicode lookup errors built-in exception classes
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 exceptions class tree in the help text of the exceptions module in python only (see and for help on help)import exceptions help(exceptionslots of text omitted this module is removed in xwhere you'll find up-to-date help in the other resources mentioned built-in exception categories the built-in class tree allows you to choose how specific or general your handlers will be for examplebecause the built-in exception arithmeticerror is superclass for more specific exceptions such as overflowerror and zerodivisionerrorby listing arithmeticerror in tryyou will catch any kind of numeric error raised by listing zerodivisionerroryou will intercept just that specific type of errorand no others similarlybecause exception is the superclass of all application-level exceptions in python xyou can generally use it as catchall--the effect is much like an empty exceptbut it allows system exit exceptions to pass and propagate as they usually shouldtryaction(except exceptionhandle all application exceptions elsehandle no-exception case exits not caught here this doesn' quite work universally in python xhoweverbecause standalone userdefined exceptions coded as classic classes are not required to be subclasses of the exception root class this technique is more reliable in python xsince it requires all classes to derive from built-in exceptions even in python xthoughthis scheme suffers most of the same potential pitfalls as the empty exceptas described in the prior -it might intercept exceptions intended for elsewhereand it might mask genuine programming errors since this is such common issuewe'll revisit it as "gotchain the next exception objects
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 others related to operating system calls under the oserror category superclass former exception names are retained for backward compatibility prior to thisprograms inspect the data attached to the exception instance to see what specific error occurredand possibly reraise others to be propagated (the errno module has names preset to the error codes for convenienceand the error number is available in both the generic tuple as args[ and attribute errno) :\temppy - tryf open('nonesuch txt'except ioerror as vif errno = print('no such file'elseraise no such file or errno nv args[ propagate others this code still works in but with the new classesprograms in and later can be more specific about the exceptions they mean to processand ignore othersc:\temppy - tryf open('nonesuch txt'except filenotfounderrorprint('no such file'no such file for full details on this extension and its classessee the other resources listed earlier default printing and state built-in exceptions also provide default print displays and state retentionwhich is often as much logic as user-defined classes require unless you redefine the constructors your classes inherit from themany constructor arguments you pass to these classes are automatically saved in the instance' args tuple attributeand are automatically displayed when the instance is printed an empty tuple and display string are used if no constructor arguments are passedand single argument displays as itself (not as tuplebuilt-in exception classes
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 argument attachedprinted indexerror('spam' args ('spam',print(ispam available in object attribute displays args when printed manually the same holds true for user-defined exceptions in python (and for new-style classes in )because they inherit the constructor and display methods present in their builtin superclassesclass (exception)pass raise traceback (most recent call last)file ""line in __main__ raise ('spam'traceback (most recent call last)file ""line in __main__ espam ('spam' args ('spam',print(ispam when intercepted in try statementthe exception instance object gives access to both the original constructor arguments and the display methodtryraise ('spam'except as xprint(xprint( argsprint(repr( )spam ('spam', ('spam', exception objects displays and saves constructor arguments
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 stringsperform manual conversionsstr( 'as tr''%sxand the like although this automatic state and display support is useful by itselffor more specific display and state retention needs you can always redefine inherited methods such as __str__ and __init__ in exception subclasses--as the next section shows custom print displays as we saw in the preceding sectionby defaultinstances of class-based exceptions display whatever you passed to the class constructor when they are caught and printedclass mybad(exception)pass tryraise mybad('sorry--my mistake!'except mybad as xprint(xsorry--my mistakethis inherited default display model is also used if the exception is displayed as part of an error message when the exception is not caughtraise mybad('sorry--my mistake!'traceback (most recent call last)file ""line in __main__ mybadsorry--my mistakefor many rolesthis is sufficient to provide more custom displaythoughyou can define one of two string-representation overloading methods in your class (__repr__ or __str__to return the string you want to display for your exception the string the method returns will be displayed if the exception either is caught and printed or reaches the default handlerclass mybad(exception)def __str__(self)return 'always look on the bright side of life tryraise mybad(except mybad as xprint(xcustom print displays
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 here to illustratebut it can also perform arbitrary text processingpossibly using state information attached to the instance object the next section looks at state information options subtle point hereyou generally must redefine __str__ for exception display purposesbecause the built-in exception superclasses already have __str__ methodand __str__ is preferred to __repr__ in some contexts--including error message displays if you define __repr__printing will happily call the built-in superclass' __str__ insteadclass (exception)def __repr__(self)return 'not called!raise ('spam'__main__ espam class (exception)def __str__(self)return 'called!raise ('spam'__main__ ecalledsee for more details on these special operator overloading methods custom data and behavior besides supporting flexible hierarchiesexception classes also provide storage for extra state information as instance attributes as we saw earlierbuilt-in exception superclasses provide default constructor that automatically saves constructor arguments in an instance tuple attribute named args although the default constructor is adequate for many casesfor more custom needs we can provide constructor of our own in additionclasses may define methods for use in handlers that provide precoded exception processing logic providing exception details when an exception is raisedit may cross arbitrary file boundaries--the raise statement that triggers an exception and the try statement that catches it may be in completely different module files it is not generally feasible to store extra details in global exception objects
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 an extra variable after the as keyword in an except handler this provides natural hook for supplying data and behavior to the handler for examplea program that parses data files might signal formatting error by raising an exception instance that is filled out with extra details about the errorclass formaterror(exception)def __init__(selflinefile)self line line self file file def parser()raise formaterror( file='spam txt'when error found tryparser(except formaterror as xprint('error at% % ( filex line)error atspam txt in the except clause herethe variable is assigned reference to the instance that was generated when the exception was raised this gives access to the attributes attached to the instance by the custom constructor although we could rely on the default state retention of built-in superclassesit' less relevant to our application (and doesn' support the keyword arguments used in the prior example)class formaterror(exception)pass inherited constructor def parser()raise formaterror( 'spam txt'no keywords allowedtryparser(except formaterror as xprint('error at:' args[ ] args[ ]error at spam txt not specific to this app providing exception methods besides enabling application-specific state informationcustom constructors also better support extra behavior for exception objects that isthe exception class can also define methods to be called in the handler the following code in excparse pyfor exampleadds method that uses exception state information to log errors to file automaticallycustom data and behavior
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 script writes its error message to file in response to method calls in the exception handlerc:\codedel formaterror txt :\codepy - excparse py :\codepy - excparse py :\codetype formaterror txt error atspam txt error atspam txt in such classmethods (like logerrormay also be inherited from superclassesand instance attributes (like line and fileprovide place to save state information that provides extra context for use in later method calls moreoverexception classes are free to customize and extend inherited behaviorclass customformaterror(formaterror)def logerror(self)something unique here raise customformaterrorin other wordsbecause they are defined with classesall the benefits of oop that we studied in part vi are available for use with exceptions in python two final notes herefirstthe raised instance object assigned to exc in this code is also available generically as the second item in the result tuple of the sys exc_info(call- tool that returns information about the most recently raised exception this interface must be used if you do not list an exception name in an except clause but still need access to the exception that occurredor to any of its attached state information or methods secondalthough our class' logerror method appends custom message to logfileit could also generate python' standard error message with stack trace using tools in the traceback standard library modulewhich uses traceback objects exception objects
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 hierarchies that ease maintenanceallow data and behavior to be attached to exceptions as instance attributes and methodsand allow exceptions to inherit data and behavior from superclasses we saw that in try statementcatching superclass catches that class as well as all subclasses below it in the class tree--superclasses become exception category namesand subclasses become more specific exception types within those categories we also saw that the built-in exception superclasses we must inherit from provide usable defaults for printing and state retentionwhich we can override if desired the next wraps up this part of the book by exploring some common use cases for exceptions and surveying tools commonly used by python programmers before we get therethoughhere' this quiz test your knowledgequiz what are the two new constraints on user-defined exceptions in python how are raised class-based exceptions matched to handlers name two ways that you can attach context information to exception objects name two ways that you can specify the error message text for exception objects why should you not use string-based exceptions anymore todaytest your knowledgeanswers in xexceptions must be defined by classes (that isa class instance object is raised and caughtin additionexception classes must be derived from the builtin class baseexceptionmost programs inherit from its exception subclassto support catchall handlers for normal kinds of exceptions class-based exceptions match by superclass relationshipsnaming superclass in an exception handler will catch instances of that classas well as instances of any of its subclasses lower in the class tree because of thisyou can think of superclasses as general exception categories and subclasses as more specific types of exceptions within those categories test your knowledgeanswers
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 through this name to access attached state information and call any methods defined in the class the error message text in class-based exceptions can be specified with custom __str__ operator overloading method for simpler needsbuilt-in exception superclasses automatically display anything you pass to the class constructor operations like print and str automatically fetch the display string of an exception object when it is printed either explicitly or as part of an error message because guido said so--they have been removed as of both python and there are arguably good reasons for thisstring-based exceptions did not support categoriesstate informationor behavior inheritance in the way class-based exceptions do in practicethis made string-based exceptions easier to use at first when programs were smallbut more complex to use as programs grew larger the downsides of requiring exceptions to be classes are to break existing codeand create forward knowledge dependency--beginners must first learn classes and oop before they can code new exceptionsor even truly understand exceptions at all in factthis is why this relatively straightforward topic was largely postponed until this point in the book for better or worsesuch dependencies are not uncommon in python today (see the preface and conclusion for more on such things exception objects
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 you as you make the migration from python beginner to python application developer nesting exception handlers most of our examples so far have used only single try to catch exceptionsbut what happens if one try is physically nested inside anotherfor that matterwhat does it mean if try calls function that runs another trytechnicallytry statements can nestin terms of both syntax and the runtime control flow through your code 've mentioned this brieflybut let' clarify the idea here both of these cases can be understood if you realize that python stacks try statements at runtime when an exception is raisedpython returns to the most recently entered try statement with matching except clause because each try statement leaves markerpython can jump back to earlier trys by inspecting the stacked markers this nesting of active handlers is what we mean when we talk about propagating exceptions up to "higherhandlers--such handlers are simply try statements entered earlier in the program' execution flow figure - illustrates what occurs when try statements with except clauses nest at runtime the amount of code that goes into try block can be substantialand it may contain function calls that invoke other code watching for the same exceptions when an exception is eventually raisedpython jumps back to the most recently entered try statement that names that exceptionruns that statement' except clauseand then resumes execution after that try once the exception is caughtits life is over--control does not jump back to all matching trys that name the exceptiononly the first ( most recentone is given the opportunity to handle it in figure - for instancethe raise statement in the func
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 to the most recently entered try to run its finally statementbut then the exception keeps propagating to all finallys in all active try statements and eventually reaches the default top-level handlerwhere an error message is printed finally clauses intercept (but do not stopan exception--they are for actions to be performed "on the way out tion func sends control back to the handler in func and then the program continues within func by contrastwhen try statements that contain only finally clauses are nestedeach finally block is run in turn when an exception occurs--python continues propagating the exception up to other trysand eventually perhaps to the top-level default handler (the standard error message printeras figure - illustratesthe finally clauses do not kill the exception--they just specify code to be run on the way out of each try during the exception propagation process if there are many try/finally clauses active when an exception occursthey will all be rununless try/except catches the exception somewhere along the way in other wordswhere the program goes when an exception is raised depends entirely upon where it has been--it' function of the runtime flow of control through the scriptnot just its syntax the propagation of an exception essentially proceeds backward through time to try statements that have been entered but not yet exited this propagation stops as soon as control is unwound to matching except clausebut not as it passes through finally clauses on the way designing with exceptions
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 typeerrorprint('inner try'generate typeerror most recent matching try tryaction (except typeerrorprint('outer try'hereonly if action re-raises python nestexc py inner try noticethoughthat the top-level module code at the bottom of the file wraps call to action in try handlertoo when action triggers the typeerror exceptionthere will be two active try statements--the one in action and the one at the top level of the module file python picks and runs just the most recent try with matching except-which in this case is the try inside action againthe place where an exception winds up jumping to depends on the control flow through the program at runtime because of thisto know where you will goyou need to know where you've been in this casewhere exceptions are handled is more function of control flow than of statement syntax howeverwe can also nest exception handlers syntactically--an equivalent case we turn to next examplesyntactic nesting as mentioned when we looked at the new unified try/except/finally statement in it is possible to nest try statements syntactically by their position in your source codetrytryaction (except typeerrorprint('inner try'except typeerrorprint('outer try'most recent matching try hereonly if nested handler re-raises nesting exception handlers
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 exceptionwhether they are nested syntactically or by means of the runtime flow through physically separated parts of your codetrytryraise indexerror finallyprint('spam'finallyprint('spam'spam spam traceback (most recent call last)file ""line in indexerror see figure - for graphic illustration of this code' operationthe effect is the samebut the function logic has been inlined as nested statements here for more useful example of syntactic nesting at workconsider the following fileexcept-finally pydef raise ()raise indexerror def noraise()return def raise ()raise syntaxerror for func in (raise noraiseraise )print('func __name__trytryfunc(except indexerrorprint('caught indexerror'finallyprint('finally run'print('this code catches an exception if one is raised and performs finally terminationtime action regardless of whether an exception occurs this may take few moments to digestbut the effect is the same as combining an except and finally clause in single try statement in python and laterpython except-finally py caught indexerror finally run finally run designing with exceptions