id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
1,800 | that these descriptors store base values as instance stateso they must use leading underscores again so as not to clash with the names of descriptorsas we'll see in the final example of this we could avoid this renaming requirement by storing base values as descriptor state insteadbut that doesn' as directly address data that must vary per client class instancesamebut with descriptors (per-instance stateclass descsquare(object)def __get__(selfinstanceowner)return instance _square * def __set__(selfinstancevalue)instance _square value class desccube(object)def __get__(selfinstanceowner)return instance _cube * class powers(object)square descsquare(cube desccube(def __init__(selfsquarecube)self _square square self _cube cube powers( print( squareprint( cubex square print( squareneed all (objectin only "self square squareworks toobecause it triggers desc __set__ * * * to achieve the same result with __getattr__ fetch interceptionwe again store base values with underscore-prefixed names so that accesses to managed names are undefined and thus invoke our methodwe also need to code __setattr__ to intercept assignmentsand take care to avoid its potential for loopingsamebut with generic __getattr__ undefined attribute interception class powersdef __init__(selfsquarecube)self _square square self _cube cube def __getattr__(selfname)if name ='square'return self _square * elif name ='cube'return self _cube * elseraise typeerror('unknown attr:namedef __setattr__(selfnamevalue)if name ='square'__getattr__ and __getattribute__ |
1,801 | elseself __dict__[namevalue powers( print( squareprint( cubex square print( squareor use object * * * the final optioncoding this with __getattribute__is similar to the prior version because we catch every attribute nowthoughwe must also route base value fetches to superclass to avoid looping or extra calls--fetching self _square directly works toobut runs second __getattribute__ callsamebut with generic __getattribute__ all attribute interception class powers(object)def __init__(selfsquarecube)self _square square self _cube cube need (objectin only def __getattribute__(selfname)if name ='square'return object __getattribute__(self'_square'* elif name ='cube'return object __getattribute__(self'_cube'* elsereturn object __getattribute__(selfnamedef __setattr__(selfnamevalue)if name ='square'object __setattr__(self'_square'valueelseobject __setattr__(selfname valuex powers( print( squareprint( cubex square print( squareor use __dict__ * * * as you can seeeach technique takes different form in codebut all four produce the same result when run for more on how these alternatives compareand other coding optionsstay tuned for more realistic application of them in the attribute validation example in the section "exampleattribute validationson page firstthoughwe need to take short side trip to study new-style-class pitfall associated with two of these tools--the generic attribute interceptors presented in this section managed attributes |
1,802 | if you've been reading this book linearlysome of this section is review and elaboration on material covered earlierespecially in for othersthis topic is presented in this context here when introduced __getattr__ and __getattribute__i stated that they intercept undefined and all attribute fetchesrespectivelywhich makes them ideal for delegationbased coding patterns while this is true for both normally named and explicitly called attributestheir behavior needs some additional clarificationfor method-name attributes implicitly fetched by built-in operationsthese methods may not be run at all this means that operator overloading method calls cannot be delegated to wrapped objects unless wrapper classes somehow redefine these methods themselves for exampleattribute fetches for the __str____add__and __getitem__ methods run implicitly by printingexpressionsand indexingrespectivelyare not routed to the generic attribute interception methods in specificallyin python xneither __getattr__ nor __getattribute__ is run for such attributes in python classic classes__getattr__ is run for such attributes if they are undefined in the class in python x__getattribute__ is available for new-style classes only and works as it does in in other wordsin all python classes (and new-style classes)there is no direct way to generically intercept built-in operations like printing and addition in python ' default classic classesthe methods such operations invoke are looked up at runtime in instanceslike all other attributesin python ' new-style classes such methods are looked up in classes instead since mandates new-style classes and defaults to classicthis is understandably attributed to xbut it can happen in new-style code too in xthoughyou at least have way to avoid this changein xyou do not per the official (though tersely documentedrationale for this change appears to revolve around metaclassses and optimization of built-in operations regardlessgiven that all attributes--both normally named and others--still dispatch generically through the instance and these methods when accessed explicitly by namethis does not seem meant to preclude delegation in generalit seems more an optimization step for built-in operationsimplicit behavior this doeshowevermake delegationbased coding patterns more complex in xbecause object interface proxies cannot generically intercept operator overloading method calls and route them to an embedded object this is an inconveniencebut is not necessarily showstopper--wrapper classes can work around this constraint by redefining all relevant operator overloading methods in the wrapper itselfin order to delegate calls these extra methods can be added either __getattr__ and __getattribute__ |
1,803 | this doeshowevermake object wrappers more work than they used to be when operator overloading methods are part of wrapped object' interface keep in mind that this issue applies only to __getattr__ and __getattribute__ because properties and descriptors are defined for specific attributes onlythey don' really apply to delegation-based classes at all-- single property or descriptor cannot be used to intercept arbitrary attributes moreovera class that defines both operator overloading methods and attribute interception will work correctlyregardless of the type of attribute interception defined our concern here is only with classes that do not have operator overloading methods definedbut try to intercept them generically consider the following examplethe file getattr-bultins pywhich tests various attribute types and built-in operations on instances of classes containing __getattr__ and __get attribute__ methodsclass getattreggs eggs stored on classspam on instance def __init__(self)self spam def __len__(self)len hereelse __getattr__ called with __len__ print('__len__ 'return def __getattr__(selfattr)provide __str__ if askedelse dummy func print('getattrattrif attr ='__str__'return lambda *args'[getattr str]elsereturn lambda *argsnone class getattribute(object)object required in ximplied in eggs in all are isinstance(objectauto def __init__(self)but must derive to get new-style toolsself spam incl __getattribute__some __x__ defaults def __len__(self)print('__len__ 'return def __getattribute__(selfattr)print('getattributeattrif attr ='__str__'return lambda *args'[getattribute str]elsereturn lambda *argsnone for class in getattrgetattributeprint('\nclass __name__ ljust( '=') class( eggs spam other len( managed attributes class attr instance attr missing attr __len__ defined explicitly |
1,804 | tryx[ __getitem__exceptprint('fail []'tryx __add__exceptprint('fail +'tryx(__call__(implicit via built-inexceptprint('fail ()' __call__(print( __str__()print(x__call__(explicitnot inherited__str__(explicitinherited from type__str__(implicit via built-inwhen run under python as coded__getattr__ does receive variety of implicit attribute fetches for built-in operationsbecause python looks up such attributes in instances normally conversely__getattribute__ is not run for any of the operator overloading names invoked by built-in operationsbecause such names are looked up in classes only in the new-style class modelc:\codepy - getattr-builtins py getattr==========================================getattrother __len__ getattr__getitem__ getattr__coerce__ getattr__add__ getattr__call__ getattr__call__ getattr__str__ [getattr strgetattr__str__ [getattr strgetattribute=====================================getattributeeggs getattributespam getattributeother __len__ fail [fail fail (getattribute__call__ getattribute__str__ [getattribute strnote how __getattr__ intercepts both implicit and explicit fetches of __call__ and __str__ in here by contrast__getattribute__ fails to catch implicit fetches of either attribute name for built-in operations __getattr__ and __getattribute__ |
1,805 | must be made new-style by deriving from object to use this method this code' object derivation is optional in because all classes are new-style when run under python xthoughresults for __getattr__ differ--none of the implicitly run operator overloading methods trigger either attribute interception method when their attributes are fetched by built-in operations python (and new-style classes in generalskips the normal instance lookup mechanism when resolving such namesthough normally named methods are still intercepted as beforec:\codepy - getattr-builtins py getattr==========================================getattrother __len__ fail [fail fail (getattr__call__ getattribute=====================================getattributeeggs getattributespam getattributeother __len__ fail [fail fail (getattribute__call__ getattribute__str__ [getattribute strtrace these outputs back to prints in the script to see how this works some highlights__str__ access fails to be caught twice by __getattr__ in xonce for the built-in printand once for explicit fetches because default is inherited from the class (reallyfrom the built-in objectwhich is an automatic superclass to every class in x__str__ fails to be caught only once by the __getattribute__ catchallduring the built-in print operationexplicit fetches bypass the inherited version __call__ fails to be caught in both schemes in for built-in call expressionsbut it is intercepted by both when fetched explicitlyunlike __str__there is no inherited __call__ default for object instances to defeat __getattr__ __len__ is caught by both classessimply because it is an explicitly defined method in the classes themselves--though its name it is not routed to either __getattr__ or __getattribute__ in if we delete the class' __len__ methods all other built-in operations fail to be intercepted by both schemes in managed attributes |
1,806 | operations are never routed through either attribute interception method in xpython ' new-style classes search for such attributes in classes and skip instance lookup entirely normally named attributes do not this makes delegation-based wrapper classes more difficult to code in ' new-style classes--if wrapped classes may contain operator overloading methodsthose methods must be redefined redundantly in the wrapper class in order to delegate to the wrapped object in general delegation toolsthis can add dozens of extra methods of coursethe addition of such methods can be partly automated by tools that augment classes with new methods (the class decorators and metaclasses of the next two might help heremoreovera superclass might be able to define all these extra methods oncefor inheritance in delegation-based classes stilldelegation coding patterns require extra work in ' classes for more realistic illustration of this phenomenon as well as its workaroundsee the private decorator example in the following therewe'll explore alternatives for coding the operator methods required of proxies in ' classes--including reusable mix-in superclass models we'll also see there that it' possible to insert __getat tribute__ in the client class to retain its original typealthough this method still won' be called for operator overloading methodsprinting still runs __str__ defined in such class directlyfor exampleinstead of routing the request through __getattribute__ as more realistic example of thisthe next section resurrects our class tutorial example now that you understand how attribute interception worksi'll be able to explain one of its stranger bits delegation-based managers revisited the object-oriented tutorial of presented manager class that used object embedding and method delegation to customize its superclassrather than inheritance here is the code again for referencewith some irrelevant testing removedclass persondef __init__(selfnamejob=nonepay= )self name name self job job self pay pay def lastname(self)return self name split()[- def giveraise(selfpercent)self pay int(self pay ( percent)def __repr__(self)return '[person% % ](self nameself payclass managerdef __init__(selfnamepay)self person person(name'mgr'paydef giveraise(selfpercentbonus )embed person object __getattr__ and __getattribute__ |
1,807 | def __getattr__(selfattr)return getattr(self personattrdef __repr__(self)return str(self personintercept and delegate delegate all other attrs must overload again (in xif __name__ ='__main__'sue person('sue jones'job='dev'pay= print(sue lastname()sue giveraise print(suetom manager('tom jones' manager __init__ print(tom lastname()manager __getattr__ -person lastname tom giveraise manager giveraise -person giveraise print(tommanager __repr__ -person __repr__ comments at the end of this file show which methods are invoked for line' operation in particularnotice how lastname calls are undefined in managerand thus are routed into the generic __getattr__ and from there on to the embedded person object here is the script' output--sue receives raise from personbut tom gets because giveraise is customized in managerc:\codepy - getattr-delegate py jones [personsue jones jones [persontom jones by contrastthoughnotice what occurs when we print manager at the end of the scriptthe wrapper class' __repr__ is invokedand it delegates to the embedded person object' __repr__ with that in mindwatch what happens if we delete the man ager __repr__ method in this codedelete the manager __str__ method class managerdef __init__(selfnamepay)self person person(name'mgr'paydef giveraise(selfpercentbonus )self person giveraise(percent bonusdef __getattr__(selfattr)return getattr(self personattrembed person object intercept and delegate delegate all other attrs now printing does not route its attribute fetch through the generic __getattr__ interceptor under python ' new-style classes for manager objects insteada default __repr__ display method inherited from the class' implicit object superclass is looked up and run (sue still prints correctlybecause person has an explicit __repr__) :\codepy - getattr-delegate py jones [personsue jones jones managed attributes |
1,808 | default classic classesbecause operator overloading attributes are routed through this methodand such classes do not inherit default for __repr__c:\codepy - getattr-delegate py jones [personsue jones jones [persontom jones switching to __getattribute__ won' help here either--like __getattr__it is not run for operator overloading attributes implied by built-in operations in either python or xreplace __getattr_ with __getattribute__ class manager(object)def __init__(selfnamepay)self person person(name'mgr'paydef giveraise(selfpercentbonus )self person giveraise(percent bonusdef __getattribute__(selfattr)print('**'attrif attr in ['person''giveraise']return object __getattribute__(selfattrelsereturn getattr(self personattruse "(object)in embed person object intercept and delegate fetch my attrs delegate all others regardless of which attribute interception method is used in xwe still must include redefined __repr__ in manager (as shown previouslyin order to intercept printing operations and route them to the embedded person objectc:\codepy - getattr-delegate py jones [personsue jones *lastname *person jones *giveraise *person notice that __getattribute__ gets called twice here for methods--once for the method nameand again for the self person embedded object fetch we could avoid that with different codingbut we would still have to redefine __repr__ to catch printingalbeit differently here (self person would cause this __getattribute__ to fail)code __getattribute__ differently to minimize extra calls class managerdef __init__(selfnamepay)self person person(name'mgr'paydef __getattribute__(selfattr)print('**'attrperson object __getattribute__(self'person'__getattr__ and __getattribute__ |
1,809 | return lambda percentperson giveraise(percent elsereturn getattr(personattrdef __repr__(self)person object __getattribute__(self'person'return str(personwhen this alternative runsour object prints properlybut only because we've added an explicit __repr__ in the wrapper--this attribute is still not routed to our generic attribute interception methodjones [personsue jones *lastname jones *giveraise [persontom jones that short story here is that delegation-based classes like manager must redefine some operator overloading methods (like __repr__ and __str__to route them to embedded objects in python xbut not in python unless new-style classes are used our only direct options seem to be using __getattr__ and python xor redefining operator overloading methods in wrapper classes redundantly in againthis isn' an impossible taskmany wrappers can predict the set of operator overloading methods requiredand tools and superclasses can automate part of this task--in factwe'll study coding patterns that can fill this need in the next moreovernot all classes use operator overloading methods (indeedmost application classes usually should notit ishoweversomething to keep in mind for delegation coding models used in python xwhen operator overloading methods are part of an object' interfacewrappers must accommodate them portably by redefining them locally exampleattribute validations to close out this let' turn to more realistic examplecoded in all four of our attribute management schemes the example we will use defines cardholder object with four attributesthree of which are managed the managed attributes validate or transform values when fetched or stored all four versions produce the same results for the same test codebut they implement their attributes in very different ways the examples are included largely for self-studyalthough won' go through their code in detailthey all use concepts we've already explored in this using properties to validate our first coding in the file that follows uses properties to manage three attributes as usualwe could use simple methods instead of managed attributesbut properties help managed attributes |
1,810 | used to intercept all attributes generically to understand this codeit' crucial to notice that the attribute assignments inside the __init__ constructor method trigger property setter methods too when this method assigns to self namefor exampleit automatically invokes the setname methodwhich transforms the value and assigns it to an instance attribute called __name so it won' clash with the property' name this renaming (sometimes called name manglingis necessary because properties use common instance state and have none of their own data is stored in an attribute called __nameand the attribute called name is always propertynot data as we saw in names like __name are known as pseudoprivate attributesand are changed by python to include the enclosing class' name when stored in the instance' namespaceherethis helps keep the implementation-specific attributes distinct from othersincluding that of the property that manages them in the endthis class manages attributes called nameageand acctallows the attribute addr to be accessed directlyand provides read-only attribute called remain that is entirely virtual and computed on demand for comparison purposesthis propertybased coding weighs in at lines of codenot counting its two initial linesand includes the object derivation required in but optional in xfile validate_properties py class cardholder(object)acctlen retireage need "(object)for setter in class data def __init__(selfacctnameageaddr)self acct acct instance data self name name these trigger prop setters tooself age age __x mangled to have class name self addr addr addr is not managed remain has no data def getname(self)return self __name def setname(selfvalue)value value lower(replace('' 'self __name value name property(getnamesetnamedef getage(self)return self __age def setage(selfvalue)if value raise valueerror('invalid age'elseself __age value age property(getagesetageexampleattribute validations |
1,811 | return self __acct[:- '***def setacct(selfvalue)value value replace('-'''if len(value!self acctlenraise typeerror('invald acct number'elseself __acct value acct property(getacctsetacctdef remainget(self)return self retireage self age remain property(remaingetcould be methodnot attr unless already using as attr testing code the following codevalidate_tester pytests our classrun this script with the name of the class' module (sans py"as single command-line argument (you could also add most of its test code to the bottom of each fileor interactively import it from module after importing the classwe'll use this same testing code for all four versions of this example when it runsit makes two instances of our managed-attribute class and fetches and changes their various attributes operations expected to fail are wrapped in try statementsand identical behavior on is supported by enabling the print functionfile validate_tester py from __future__ import print_function def loadclass()import sysimportlib modulename sys argv[ module importlib import_module(modulenameprint('[using% ]module cardholderreturn module cardholder module name in command line import module by name string no need for getattr(here def printholder(who)print(who acctwho namewho agewho remainwho addrsep='if __name__ ='__main__'cardholder loadclass(bob cardholder(' - ''bob smith' ' main st'printholder(bobbob name 'bob smithbob age bob acct '- printholder(bobsue cardholder('''sue jones' ' main st'printholder(suetrysue age exceptprint('bad age for sue' managed attributes |
1,812 | sue remain exceptprint("can' set sue remain"trysue acct ' exceptprint('bad acct for sue'here is the output of our self-test code on both python and xagainthis is the same for all versions of this exampleexcept for the tested class' name trace through this code to see how the class' methods are invokedaccounts are displayed with some digits hiddennames are converted to standard formatand time remaining until retirement is computed when fetched using class attribute cutoffc:\codepy - validate_tester py validate_properties [using **bob_smith main st **bob_q _smith main st **sue_jones main st bad age for sue can' set sue remain bad acct for sue using descriptors to validate nowlet' recode our example using descriptors instead of properties as we've seendescriptors are very similar to properties in terms of functionality and rolesin factproperties are basically restricted form of descriptor like propertiesdescriptors are designed to handle specific attributesnot generic attribute access unlike propertiesdescriptors can also have their own stateand are more general scheme option validating with shared descriptor instance state to understand the following codeit' again important to notice that the attribute assignments inside the __init__ constructor method trigger descriptor __set__ methods when the constructor method assigns to self namefor exampleit automatically invokes the name __set__(methodwhich transforms the value and assigns it to descriptor attribute called name in the endthis class implements the same attributes as the prior versionit manages attributes called nameageand acctallows the attribute addr to be accessed directlyand provides read-only attribute called remain that is entirely virtual and computed on demand notice how we must catch assignments to the remain name in its descriptor and raise an exceptionas we learned earlierif we did not do thisassigning to this attribute of an instance would silently create an instance attribute that hides the class attribute descriptor exampleattribute validations |
1,813 | added the required object derivation to the main descriptor classes for compatibility (they can be omitted for code to be run in onlybut don' hurt in xand aid portability if present)file validate_descriptors pyusing shared descriptor state class cardholder(object)acctlen retireage def __init__(selfacctnameageaddr)self acct acct self name name self age age self addr addr need all "(object)in only class data instance data these trigger __set__ calls too__x not neededin descriptor addr is not managed remain has no data class name(object)def __get__(selfinstanceowner)class namescardholder locals return self name def __set__(selfinstancevalue)value value lower(replace('' 'self name value name name(class age(object)def __get__(selfinstanceowner)return self age def __set__(selfinstancevalue)if value raise valueerror('invalid age'elseself age value age age(class acct(object)def __get__(selfinstanceowner)return self acct[:- '***def __set__(selfinstancevalue)value value replace('-'''if len(value!instance acctlenraise typeerror('invald acct number'elseself acct value acct acct(class remain(object)def __get__(selfinstanceowner)return instance retireage instance age def __set__(selfinstancevalue)raise typeerror('cannot set remain'remain remain( managed attributes use descriptor data use instance class data triggers age __get__ else set allowed here |
1,814 | output as shown for properties earlierexcept that the name of the class in the first line variesc:\codepython validate_tester py validate_descriptors same output as propertiesexcept class name option validating with per-client-instance state unlike in the prior property-based variantthoughin this case the actual name value is attached to the descriptor objectnot the client class instance although we could store this value in either instance or descriptor statethe latter avoids the need to mangle names with underscores to avoid collisions in the cardholder client classthe attribute called name is always descriptor objectnot data importantlythe downside of this scheme is that state stored inside descriptor itself is class-level data that is effectively shared by all client class instancesand so cannot vary between them that isstoring state in the descriptor instance instead of the owner (clientclass instance means that the state will be the same in all owner class instances descriptor state can vary only per attribute appearance to see this at workin the preceding descriptor-based cardholder exampletry printing attributes of the bob instance after creating the second instancesue the values of sue' managed attributes (nameageand acctoverwrite those of the earlier object bobbecause both share the samesingle descriptor instance attached to their classfile validate_tester py from __future__ import print_function from validate_tester import loadclass cardholder loadclass(bob cardholder(' - ''bob smith' ' main st'print('bob:'bob namebob acctbob agebob addrsue cardholder('''sue jones' ' main st'print('sue:'sue namesue acctsue agesue addraddr differsclient data print('bob:'bob namebob acctbob agebob addrname,acct,age overwrittenthe results confirm the suspicion--in terms of managed attributesbob has morphed into suec:\codepy - validate_tester py validate_descriptors [usingbobbob_smith ** main st suesue_jones ** main st bobsue_jones ** main st there are valid uses for descriptor stateof course--to manage descriptor implementation and data that spans all instance--and this code was implemented to illustrate the technique moreoverthe state scope implications of class versus instance attributes should be more or less given at this point in the book exampleattribute validations |
1,815 | stored as per-instance data instead of descriptor instance dataperhaps using the same __x naming convention as the property-based equivalent to avoid name clashes in the instance-- more important factor this timeas the client is different class with its own state attributes here are the required coding changesit doesn' change line counts (we're still at )file validate_descriptors pyusing per-client-instance state class cardholder(object)acctlen retireage def __init__(selfacctnameageaddr)self acct acct self name name self age age self addr addr need all "(object)in only class data client instance data these trigger __set__ calls too__x neededin client instance addr is not managed remain managed but has no data class name(object)def __get__(selfinstanceowner)class namescardholder locals return instance __name def __set__(selfinstancevalue)value value lower(replace('' 'instance __name value name name(class name vs mangled attr class age(object)def __get__(selfinstanceowner)return instance __age def __set__(selfinstancevalue)if value raise valueerror('invalid age'elseinstance __age value age age(class acct(object)def __get__(selfinstanceowner)return instance __acct[:- '***def __set__(selfinstancevalue)value value replace('-'''if len(value!instance acctlenraise typeerror('invald acct number'elseinstance __acct value acct acct(class remain(object)def __get__(selfinstanceowner)return instance retireage instance age def __set__(selfinstancevalue)raise typeerror('cannot set remain'remain remain( managed attributes use descriptor data class age vs mangled attr use instance class data class acct vs mangled name triggers age __get__ else set allowed here |
1,816 | (bob remains bob)and other tests work as beforec:\codepy - validate_tester py validate_descriptors [usingbobbob_smith ** main st suesue_jones ** main st bobbob_smith ** main st :\codepy - validate_tester py validate_descriptors same output as propertiesexcept class name one small caveat hereas codedthis version doesn' support through-class descriptor accessbecause such access passes none to the instance argument (also notice the attribute __x name mangling to _name__name in the error message when the fetch attempt is made)from validate_descriptors import cardholder bob cardholder(' - ''bob smith' ' main st'bob name 'bob_smithcardholder name 'bob_smithfrom validate_descriptors import cardholder bob cardholder(' - ''bob smith' ' main st'bob name 'bob_smithcardholder name attributeerror'nonetypeobject has no attribute '_name__namewe could detect this with minor amount of additional code to trigger the error more explicitlybut there' probably no point--because this version stores data in the client instancethere' no meaning to its descriptors unless they're accompanied by client instance (much like normal unbound instance methodin factthat' really the entire point of this version' changebecause they are classesdescriptors are useful and powerful toolbut they present choices that can deeply impact program' behavior as always in oopchoose your state retention policies carefully using __getattr__ to validate as we've seenthe __getattr__ method intercepts all undefined attributesso it can be more generic than using properties or descriptors for our examplewe simply test the attribute name to know when managed attribute is being fetchedothers are stored physically on the instance and so never reach __getattr__ although this approach is more general than using properties or descriptorsextra work may be required to imitate the specific-attribute focus of other tools we need to check names at runtimeand we must code __setattr__ in order to intercept and validate attribute assignments exampleattribute validations |
1,817 | as for the property and descriptor versions of this exampleit' critical to notice that the attribute assignments inside the __init__ constructor method trigger the class' __setattr__ method too when this method assigns to self namefor exampleit automatically invokes the __setattr__ methodwhich transforms the value and assigns it to an instance attribute called name by storing name on the instanceit ensures that future accesses will not trigger __getattr__ in contrastacct is stored as _acctso that later accesses to acct do invoke __getattr__ in the endthis classlike the prior twomanages attributes called nameageand acctallows the attribute addr to be accessed directlyand provides read-only attribute called remain that is entirely virtual and is computed on demand for comparison purposesthis alternative comes in at lines of code-- fewer than the property-based versionand fewer than the version using descriptors clarity matters more than code sizeof coursebut extra code can sometimes imply extra development and maintenance work probably more important here are rolesgeneric tools like __getattr__ may be better suited to generic delegationwhile properties and descriptors are more directly designed to manage specific attributes also note that the code here incurs extra calls when setting unmanaged attributes ( addr)although no extra calls are incurred for fetching unmanaged attributessince they are defined though this will likely result in negligible overhead for most programsthe more narrowly focused properties and descriptors incur an extra call only when managed attributes are accessedand also appear in dir results when needed by generic tools here' the __getattr__ version of our validations codefile validate_getattr py class cardholderacctlen retireage def __init__(selfacctnameageaddr)self acct acct self name name self age age self addr addr def __getattr__(selfname)if name ='acct'return self _acct[:- '***elif name ='remain'return self retireage self age elseraise attributeerror(nameclass data instance data these trigger __setattr__ too _acct not mangledname tested addr is not managed remain has no data on undefined attr fetches nameageaddr are defined doesn' trigger __getattr__ def __setattr__(selfnamevalue)if name ='name'on all attr assignments value value lower(replace('' 'addr stored directly managed attributes |
1,818 | acct mangled to _acct if value raise valueerror('invalid age'elif name ='acct'name '_acctvalue value replace('-'''if len(value!self acctlenraise typeerror('invald acct number'elif name ='remain'raise typeerror('cannot set remain'self __dict__[namevalue avoid looping (or via objectwhen this code is run with either test scriptit produces the same output (with different class name) :\codepy - validate_tester py validate_getattr same output as propertiesexcept class name :\codepy - validate_tester py validate_getattr same output as instance-state descriptorsexcept class name using __getattribute__ to validate our final variant uses the __getattribute__ catchall to intercept attribute fetches and manage them as needed every attribute fetch is caught hereso we test the attribute names to detect managed attributes and route all others to the superclass for normal fetch processing this version uses the same __setattr__ to catch assignments as the prior version the code works very much like the __getattr__ versionso won' repeat the full description here notethoughthat because every attribute fetch is routed to __getat tribute__we don' need to mangle names to intercept them here (acct is stored as accton the other handthis code must take care to route nonmanaged attribute fetches to superclass to avoid looping or extra calls also notice that this version incurs extra calls for both setting and fetching unmanaged attributes ( addr)if speed is paramountthis alternative may be the slowest of the bunch for comparison purposesthis version amounts to lines of codejust like the prior versionand includes the requisite object derivation for compatibilitylike properties and descriptors__getattribute__ is new-style class toolfile validate_getattribute py class cardholder(object)acctlen retireage def __init__(selfacctnameageaddr)self acct acct self name name self age age self addr addr need "(object)in only class data instance data these trigger __setattr__ too acct not mangledname tested addr is not managed exampleattribute validations |
1,819 | def __getattribute__(selfname)superget object __getattribute__ don' loopone level up if name ='acct'on all attr fetches return superget(self'acct')[:- '***elif name ='remain'return superget(self'retireage'superget(self'age'elsereturn superget(selfnamenameageaddrstored def __setattr__(selfnamevalue)if name ='name'on all attr assignments value value lower(replace('' 'addr stored directly elif name ='age'if value raise valueerror('invalid age'elif name ='acct'value value replace('-'''if len(value!self acctlenraise typeerror('invald acct number'elif name ='remain'raise typeerror('cannot set remain'self __dict__[namevalue avoid loopsorig names both the getattr and getattribute scripts work the same as the property and per-clientinstance descriptor versionswhen run by both tester scripts on either or -four ways to achieve the same goal in pythonthough they vary in structureand are perhaps less redundant in some other roles be sure to study and run this section' code on your own for more pointers on managed attribute coding techniques summary this covered the various techniques for managing access to attributes in pythonincluding the __getattr__ and __getattribute__ operator overloading methodsclass propertiesand class attribute descriptors along the wayit compared and contrasted these tools and presented handful of use cases to demonstrate their behavior continues our tool-building survey with look at decorators--code run automatically at function and class creation timerather than on attribute access before we continuethoughlet' work through set of questions to review what we've covered here test your knowledgequiz how do __getattr__ and __getattribute__ differ how do properties and descriptors differ how are properties and decorators related managed attributes |
1,820 | bute__ and properties and descriptors isn' all this feature comparison just kind of argumenttest your knowledgeanswers the __getattr__ method is run for fetches of undefined attributes only ( those not present on an instance and not inherited from any of its classesby contrastthe __getattribute__ method is called for every attribute fetchwhether the attribute is defined or not because of thiscode inside __getattr__ can freely fetch other attributes if they are definedwhereas __getattribute__ must use special code for all such attribute fetches to avoid looping or extra calls (it must route fetches to superclass to skip itself properties serve specific rolewhile descriptors are more general properties define getsetand delete functions for specific attributedescriptors provide class with methods for these actionstoobut they provide extra flexibility to support more arbitrary actions in factproperties are really simple way to create specific kind of descriptor--one that runs functions on attribute accesses coding differs tooa property is created with built-in functionand descriptor is coded with classthusdescriptors can leverage all the usual oop features of classessuch as inheritance moreoverin addition to the instance' state informationdescriptors have local state of their ownso they can sometimes avoid name collisions in the instance properties can be coded with decorator syntax because the property built-in accepts single function argumentit can be used directly as function decorator to define fetch access property due to the name rebinding behavior of decoratorsthe name of the decorated function is assigned to property whose get accessor is set to the original function decorated (name property(name)property setter and deleter attributes allow us to further add set and delete accessors with decoration syntax--they set the accessor to the decorated function and return the augmented property the __getattr__ and __getattribute__ methods are more genericthey can be used to catch arbitrarily many attributes in contrasteach property or descriptor provides access interception for only one specific attribute--we can' catch every attribute fetch with single property or descriptor on the other handproperties and descriptors handle both attribute fetch and assignment by design__get attr__ and __getattribute__ handle fetches onlyto intercept assignments as well__setattr__ must also be coded the implementation is also different__get attr__ and __getattribute__ are operator overloading methodswhereas properties and descriptors are objects manually assigned to class attributes unlike the othersproperties and descriptors can also sometimes avoid extra calls on assignment to unmanaged namesand show up in dir results automaticallybut are also test your knowledgequiz |
1,821 | new features tend to offer alternativesbut do not fully subsume what came before no it isn' to quote from python namesake monty python' flying circusan argument is connected series of statements intended to establish proposition no it isn' yes it isit' not just contradiction lookif argue with youi must take up contrary position yesbut that' not just saying "no it isn' yes it isno it isn'tyes it isno it isn' argument is an intellectual process contradiction is just the automatic gainsaying of any statement the other person makes (short pauseno it isn' it is not at all now look managed attributes |
1,822 | decorators in the advanced class topics of this book ()we met static and class methodstook quick look at the decorator syntax python offers for declaring themand previewed decorator coding techniques we also met function decorators briefly in while exploring the property built-in' ability to serve as oneand in while studying the notion of abstract superclasses this picks up where this previous decorator coverage left off herewe'll dig deeper into the inner workings of decorators and study more advanced ways to code new decorators ourselves as we'll seemany of the concepts we studied earlier--especially state retention--show up regularly in decorators this is somewhat advanced topicand decorator construction tends to be of more interest to tool builders than to application programmers stillgiven that decorators are becoming increasingly common in popular python frameworksa basic understanding can help demystify their roleeven if you're just decorator user besides covering decorator construction detailsthis serves as more realistic case study of python in action because its examples grow somewhat larger than most of the others we've seen in this bookthey better illustrate how code comes together into more complete systems and tools as an extra perksome of the code we'll write here may be used as general-purpose tools in your day-to-day programs what' decoratordecoration is way to specify management or augmentation code for functions and classes decorators themselves take the form of callable objects ( functionsthat process other callable objects as we saw earlier in this bookpython decorators come in two related flavorsneither of which requires or new-style classesfunction decoratorsadded in python do name rebinding at function definition timeproviding layer of logic that can manage functions and methodsor later calls to them |
1,823 | timeproviding layer of logic that can manage classesor the instances created by later calls to them in shortdecorators provide way to insert automatically run code at the end of function and class definition statements--at the end of def for function decoratorsand at the end of class for class decorators such code can play variety of rolesas described in the following sections managing calls and instances in typical usethis automatically run code may be used to augment calls to functions and classes it arranges this by installing wrapper ( proxyobjects to be invoked latercall proxies function decorators install wrapper objects to intercept later function calls and process them as neededusually passing the call on to the original function to run the managed action interface proxies class decorators install wrapper objects to intercept later instance creation calls and process them as requiredusually passing the call on to the original class to create managed instance decorators achieve these effects by automatically rebinding function and class names to other callablesat the end of def and class statements when later invokedthese callables can perform tasks such as tracing and timing function callsmanaging access to class instance attributesand so on managing functions and classes although most examples in this deal with using wrappers to intercept later calls to functions and classesthis is not the only way decorators can be usedfunction managers function decorators can also be used to manage function objectsinstead of or in addition to later calls to them--to register function to an apifor instance our primary focus herethoughwill be on their more commonly used call wrapper application class managers class decorators can also be used to manage class objects directlyinstead of or in addition to instance creation calls--to augment class with new methodsfor example because this role intersects strongly with that of metaclasseswe'll see additional use cases in the next as we'll findboth tools run at the end of the class creation processbut class decorators often offer lighter-weight solution decorators |
1,824 | function objectsand class decorators can be used to manage both class instances and classes themselves by returning the decorated object itself instead of wrapperdecorators become simple post-creation step for functions and classes regardless of the role they playdecorators provide convenient and explicit way to code tools useful both during program development and in live production systems using and defining decorators depending on your job descriptionyou might encounter decorators as user or provider (you might also be maintainerbut that just means you straddle the fenceas we've seenpython itself comes with built-in decorators that have specialized roles --static and class method declarationproperty creationand more in additionmany popular python toolkits include decorators to perform tasks such as managing database or user-interface logic in such caseswe can get by without knowing how the decorators are coded for more general tasksprogrammers can code arbitrary decorators of their own for examplefunction decorators may be used to augment functions with code that adds call tracing or loggingperforms argument validity testing during debuggingautomatically acquires and releases thread lockstimes calls made to functions for optimizationand so on any behavior you can imagine adding to--reallywrapping around-- function call is candidate for custom function decorators on the other handfunction decorators are designed to augment only specific function or method callnot an entire object interface class decorators fill the latter role better --because they can intercept instance creation callsthey can be used to implement arbitrary object interface augmentation or management tasks for examplecustom class decorators can tracevalidateor otherwise augment every attribute reference made for an object they can also be used to implement proxy objectssingleton classesand other common coding patterns in factwe'll find that many class decorators bear strong resemblance to--and in fact are prime application of--the delegation coding pattern we met in why decoratorslike many advanced python toolsdecorators are never strictly required from purely technical perspectivewe can often implement their functionality instead using simple helper function calls or other techniques and at base levelwe can always manually code the name rebinding that decorators perform automatically that saiddecorators provide an explicit syntax for such taskswhich makes intent clearercan minimize augmentation code redundancyand may help ensure correct api usagewhat' decorator |
1,825 | function calls that may be arbitrarily far-removed from the subject functions or classes decorators are applied oncewhen the subject function or class is definedit' not necessary to add extra code at every call to the class or functionwhich may have to be changed in the future because of both of the prior pointsdecorators make it less likely that user of an api will forget to augment function or class according to api requirements in other wordsbeyond their technical modeldecorators offer some advantages in terms of both code maintenance and consistency moreoveras structuring toolsdecorators naturally foster encapsulation of codewhich reduces redundancy and makes future changes easier decorators do have some potential drawbackstoo--when they insert wrapper logicthey can alter the types of the decorated objectsand they may incur extra calls when used as call or interface proxies on the other handthe same considerations apply to any technique that adds wrapping logic to objects we'll explore these tradeoffs in the context of real code later in this although the choice to use decorators is still somewhat subjectivetheir advantages are compelling enough that they are quickly becoming best practice in the python world to help you decide for yourselflet' turn to the details decorators versus macrospython' decorators bear similarities to what some call aspect-oriented programming in other languages--code inserted to run automatically before or after function call runs their syntax also very closely resembles (and is likely borrowed fromjava' annotationsthough python' model is usually considered more flexible and general some liken decorators to macros toobut this isn' entirely aptand might even be misleading macros ( ' #define preprocessor directiveare typically associated with textual replacement and expansionand designed for generating code by contrastpython' decorators are runtime operationbased upon name rebindingcallable objectsand oftenproxies while the two may have use cases that sometimes overlapdecorators and macros are fundamentally different in scopeimplementationand coding patterns comparing the two seems akin to comparing python' import with #includewhich similarly confuses runtime object-based operation with text insertion of coursethe term macro has been bit diluted over time--to someit now can also refer to any canned series of steps or procedure--and users of other languages might find the analogy to descriptors useful anyhow but they should probably also keep in mind that decorators are about callable objects managing callable objectsnot text expansion python tends to be best understood and used in terms of python idioms decorators |
1,826 | let' get started with first-pass look at decoration behavior from symbolic perspective we'll write real and more substantial code soonbut since most of the magic of decorators boils down to an automatic rebinding operationit' important to understand this mapping first function decorators function decorators have been available in python since version as we saw earlier in this bookthey are largely just syntactic sugar that runs one function through another at the end of def statementand rebinds the original function name to the result usage function decorator is kind of runtime declaration about the function whose definition follows the decorator is coded on line just before the def statement that defines function or methodand it consists of the symbol followed by reference to metafunction-- function (or other callable objectthat manages another function in terms of codefunction decorators automatically map the following syntax@decorator def (arg)decorate function ( call function into this equivalent formwhere decorator is one-argument callable object that returns callable object with the same number of arguments as (in not itself)def (arg) decorator(frebind function name to decorator result ( essentially calls decorator( )( this automatic name rebinding works on any def statementwhether it' for simple function or method within class when the function is later calledit' actually calling the object returned by the decoratorwhich may be either another object that implements required wrapping logicor the original function itself in other wordsdecoration essentially maps the first of the following into the second --though the decorator is really run only onceat decoration timefunc( decorator(func)( this automatic name rebinding accounts for the static method and property decoration syntax we met earlier in the bookthe basics |
1,827 | @staticmethod def meth)meth staticmethod(methclass @property def name(self)name property(namein both casesthe method name is rebound to the result of built-in function decoratorat the end of the def statement calling the original name later invokes whatever object the decorator returns in these specific casesthe original names are rebound to static method router and property descriptorbut the process is much more general than this --as the next section explains implementation decorator itself is callable that returns callable that isit returns the object to be called later when the decorated function is invoked through its original name--either wrapper object to intercept later callsor the original function augmented in some way in factdecorators can be any type of callable and return any type of callableany combination of functions and classes may be usedthough some are better suited to certain contexts for exampleto tap into the decoration protocol in order to manage function just after it is createdwe might code decorator of this formdef decorator( )process function return @decorator def func()func decorator(funcbecause the original decorated function is assigned back to its namethis simply adds post-creation step to function definition such structure might be used to register function to an apiassign function attributesand so on in more typical useto insert logic that intercepts later calls to functionwe might code decorator to return different object than the original function-- proxy for later callsdef decorator( )save or use function return different callablenested defclass with __call__etc @decorator def func()func decorator(functhis decorator is invoked at decoration timeand the callable it returns is invoked when the original function name is later called the decorator itself receives the decorated functionthe callable returned receives whatever arguments are later passed to the decorated function' name when coded properlythis works the same for class-level decorators |
1,828 | in skeleton termshere' one common coding pattern that captures this idea--the decorator returns wrapper that retains the original function in an enclosing scopedef decorator( )def wrapper(*args)use and args (*argscalls original function return wrapper on decoration on wrapped function call @decorator def func(xy)func decorator(funcfunc is passed to decorator' func( are passed to wrapper' *args when the name func is later calledit really invokes the wrapper function returned by decoratorthe wrapper function can then run the original func because it is still available in an enclosing scope when coded this wayeach decorated function produces new scope to retain state to do the same with classeswe can overload the call operation and use instance attributes instead of enclosing scopesclass decoratordef __init__(selffunc)on decoration self func func def __call__(self*args)on wrapped function call use self func and args self func(*argscalls original function @decorator def func(xy)func decorator(funcfunc is passed to __init__ func( are passed to __call__' *args when the name func is later called nowit really invokes the __call__ operator overloading method of the instance created by decoratorthe __call__ method can then run the original func because it is still available in an instance attribute when coded this wayeach decorated function produces new instance to retain state supporting method decoration one subtle point about the prior class-based coding is that while it works to intercept simple function callsit does not quite work when applied to class-level method functionsclass decoratordef __init__(selffunc)self func func def __call__(self*args)func is method without instance self is decorator instance the basics |
1,829 | class @decorator def method(selfxy) instance not in argsmethod decorator(methodrebound to decorator instance when coded this waythe decorated method is rebound to an instance of the decorator classinstead of simple function the problem with this is that the self in the decorator' __call__ receives the decora tor class instance when the method is later runand the instance of class is never included in *args this makes it impossible to dispatch the call to the original method --the decorator object retains the original method functionbut it has no instance to pass to it to support both functions and methodsthe nested function alternative works betterdef decorator( )def wrapper(*args) is func or method without instance class instance in args[ for method (*argsruns func or method return wrapper @decorator def func(xy)func( func decorator(funcreally calls wrapper( class @decorator def method(selfxy)method decorator(methodrebound to simple function ( method( really calls wrapper( when coded this way wrapper receives the class instance in its first argumentso it can dispatch to the original method and access state information technicallythis nested-function version works because python creates bound method object and thus passes the subject class instance to the self argument only when method attribute references simple functionwhen it references an instance of callable class insteadthe callable class' instance is passed to self to give the callable class access to its own state information we'll see how this subtle difference can matter in more realistic examples later in this also note that nested functions are perhaps the most straightforward way to support decoration of both functions and methodsbut not necessarily the only way the prior descriptorsfor examplereceive both the descriptor and subject class instance when called though more complexlater in this we'll see how this tool can be leveraged in this context as well decorators |
1,830 | function decorators proved so useful that the model was extended to allow class decoration as of python and they were initially resisted because of role overlap with metaclassesin the endthoughthey were adopted because they provide simpler way to achieve many of the same goals class decorators are strongly related to function decoratorsin factthey use the same syntax and very similar coding patterns rather than wrapping individual functions or methodsthoughclass decorators are way to manage classesor wrap up instance construction calls with extra logic that manages or augments instances created from class in the latter rolethey may manage full object interfaces usage syntacticallyclass decorators appear just before class statementsin the same way that function decorators appear just before def statements in symbolic termsfor decora tor that must be one-argument callable that returns callablethe class decorator syntax@decorator class cdecorate class ( make an instance is equivalent to the following--the class is automatically passed to the decorator functionand the decorator' result is assigned back to the class nameclass cc decorator(crebind class name to decorator result ( essentially calls decorator( )( the net effect is that calling the class name later to create an instance winds up triggering the callable returned by the decoratorwhich may or may not call the original class itself implementation new class decorators are coded with many of the same techniques used for function decoratorsthough some may involve two levels of augmentation--to manage both instance construction callsas well as instance interface access because class decorator is also callable that returns callablemost combinations of functions and classes suffice however it' codedthe decorator' result is what runs when an instance is later created for exampleto simply manage class just after it is createdreturn the original class itselfthe basics |
1,831 | process class return @decorator class cc decorator(cto instead insert wrapper layer that intercepts later instance creation callsreturn different callable objectdef decorator( )save or use class return different callablenested defclass with __call__etc @decorator class cc decorator(cthe callable returned by such class decorator typically creates and returns new instance of the original classaugmented in some way to manage its interface for examplethe following inserts an object that intercepts undefined attributes of class instancedef decorator(cls)on decoration class wrapperdef __init__(self*args)on instance creation self wrapped cls(*argsdef __getattr__(selfname)on attribute fetch return getattr(self wrappednamereturn wrapper @decorator class cdef __init__(selfxy)self attr 'spamc decorator(crun by wrapper __init__ ( print( attrreally calls wrapper( runs wrapper __getattr__prints "spamin this examplethe decorator rebinds the class name to another classwhich retains the original class in an enclosing scope and creates and embeds an instance of the original class when it' called when an attribute is later fetched from the instanceit is intercepted by the wrapper' __getattr__ and delegated to the embedded instance of the original class moreovereach decorated class creates new scopewhich remembers the original class we'll flesh out this example into some more useful code later in this like function decoratorsclass decorators are commonly coded as either "factoryfunctions that create and return callablesclasses that use __init__ or __call__ methods to intercept call operationsor some combination thereof factory functions typically retain state in enclosing scope referencesand classes in attributes decorators |
1,832 | as for function decoratorssome callable type combinations work better for class decorators than others consider the following invalid alternative to the class decorator of the prior exampleclass decoratordef __init__(selfc)on decoration self def __call__(self*args)on instance creation self wrapped self (*argsreturn self def __getattr__(selfattrname)on atrribute fetch return getattr(self wrappedattrname@decorator class cc decorator(cx ( (overwrites xthis code handles multiple decorated classes (each makes new decorator instanceand will intercept instance creation calls (each runs __call__unlike the prior versionhoweverthis version fails to handle multiple instances of given class--each instance creation call overwrites the prior saved instance the original version does support multiple instancesbecause each instance creation call makes new independent wrapper object more generallyeither of the following patterns supports multiple wrapped instancesdef decorator( )class wrapperdef __init__(self*args)self wrapped (*argsreturn wrapper class wrapperdef decorator( )def oncall(*args)return wrapper( (*args)return oncall on decoration on instance creationnew wrapper embed instance in instance on decoration on instance creationnew wrapper embed instance in instance we'll study this phenomenon in more realistic context later in the tooin practicethoughwe must be careful to combine callable types properly to support our intentand choose state policies wisely decorator nesting sometimes one decorator isn' enough for instancesuppose you've coded two function decorators to be used during development--one to test argument types before function callsand another to test return value types after function calls you can use either independentlybut what to do if you want to employ both on single functionwhat you really need is way to nest the twosuch that the result of one decorator is the basics |
1,833 | run on later calls to support multiple nested steps of augmentation this waydecorator syntax allows you to add multiple layers of wrapper logic to decorated function or method when this feature is usedeach decorator must appear on line of its own decorator syntax of this form@ @ @ def )runs the same as the followingdef ) ( ( ( ))herethe original function is passed through three different decoratorsand the resulting callable object is assigned back to the original name each decorator processes the result of the priorwhich may be the original function or an inserted wrapper if all the decorators insert wrappersthe net effect is that when the original function name is calledthree different layers of wrapping object logic will be invokedto augment the original function in three different ways the last decorator listed is the first appliedand is the most deeply nested when the original function name is later called (insert joke about python "interior decoratorsherejust as for functionsmultiple class decorators result in multiple nested function callsand possibly multiple levels and steps of wrapper logic around instance creation calls for examplethe following code@spam @eggs class cx (is equivalent to the followingclass cc spam(eggs( ) (againeach decorator is free to return either the original class or an inserted wrapper object with wrapperswhen an instance of the original class is finally requestedthe call is redirected to the wrapping layer objects provided by both the spam and eggs decoratorswhich may have arbitrarily different roles--they might trace and validate attribute accessfor exampleand both steps would be run on later requests decorators |
1,834 | def ( )return def ( )return def ( )return @ @ @ def func()print('spam'func(func ( ( (func))prints "spamthe same syntax works on classesas do these same do-nothing decorators when decorators insert wrapper function objectsthoughthey may augment the original function when called--the following concatenates to its result in the decorator layersas it runs the layers from inner to outerdef ( )return lambda'xf(def ( )return lambda'yf(def ( )return lambda'zf(@ @ @ def func()return 'spamprint(func()func ( ( (func))prints "xyzspamwe use lambda functions to implement wrapper layers here (each retains the wrapped function in an enclosing scope)in practicewrappers can take the form of functionscallable classesand more when designed welldecorator nesting allows us to combine augmentation steps in wide variety of ways decorator arguments both function and class decorators can also seem to take argumentsalthough really these arguments are passed to callable that in effect returns the decoratorwhich in turn returns callable by naturethis usually sets up multiple levels of state retention the followingfor instance@decorator(abdef (arg) ( the basics |
1,835 | returns the actual decorator the returned decorator in turn returns the callable run later for calls to the original function namedef (arg) decorator(ab)(frebind to result of decorator' return value ( essentially calls decorator(ab)( )( decorator arguments are resolved before decoration ever occursand they are usually used to retain state information for use in later calls the decorator function in this examplefor instancemight take form like the followingdef decorator(ab)save or use ab def actualdecorator( )save or use function return callablenested defclass with __call__etc return callable return actualdecorator the outer function in this structure generally saves the decorator arguments away as state informationfor use in the actual decoratorthe callable it returnsor both this code snippet retains the state information argument in enclosing function scope referencesbut class attributes are commonly used as well in other wordsdecorator arguments often imply three levels of callablesa callable to accept decorator argumentswhich returns callable to serve as decoratorwhich returns callable to handle calls to the original function or class each of the three levels may be function or class and may retain state in the form of scopes or class attributes decorator arguments can be used to provide attribute initialization valuescall trace message labelsattribute names to be validatedand much more--any sort of configuration parameter for objects or their proxies is candidate we'll see concrete examples of decorator arguments employed later in this decorators manage functions and classestoo although much of the rest of this focuses on wrapping later calls to functions and classesit' important to remember that the decorator mechanism is more general than this--it is protocol for passing functions and classes through any callable immediately after they are created as suchit can also be used to invoke arbitrary postcreation processingdef decorator( )save or augment function or class return @decorator def () decorators decorator( |
1,836 | class cc decorator(cas long as we return the original decorated object this way instead of proxywe can manage functions and classes themselvesnot just later calls to them we'll see more realistic examples later in this that use this idea to register callable objects to an api with decoration and assign attributes to functions when they are created coding function decorators on to the code--in the rest of this we are going to study working examples that demonstrate the decorator concepts we just explored this section presents handful of function decorators at workand the next shows class decorators in action following thatwe'll close out with some larger case studies of class and function decorator usage--complete implementations of class privacy and argument range tests tracing calls to get startedlet' revive the call tracer example we met in the following defines and applies function decorator that counts the number of calls made to the decorated function and prints trace message for each callfile decorator py class tracerdef __init__(selffunc)on decorationsave original func self calls self func func def __call__(self*args)on later callsrun original func self calls + print('call % to % (self callsself func __name__)self func(*args@tracer def spam(abc)print( cspam tracer(spamwraps spam in decorator object notice how each function decorated with this class will create new instancewith its own saved function object and calls counter also observe how the *args argument syntax is used to pack and unpack arbitrarily many passed-in arguments this generality enables this decorator to be used to wrap any function with any number of positional argumentsthis version doesn' yet work on keyword arguments or class-level methodsand doesn' return resultsbut we'll fix these shortcomings later in this section nowif we import this module' function and test it interactivelywe get the following sort of behavior--each call generates trace message initiallybecause the decorator class intercepts it this code runs as is under both python and xas does all code coding function decorators |
1,837 | do not require new-style classessome hex addresses have also been shortened to protect the sighted)from decorator import spam spam( call to spam really calls the tracer wrapper object spam(' '' '' 'call to spam abc invokes __call__ in class spam calls number calls in wrapper state information spam when runthe tracer class saves away the decorated functionand intercepts later calls to itin order to add layer of logic that counts and prints each call notice how the total number of calls shows up as an attribute of the decorated function--spam is really an instance of the tracer class when decorateda finding that may have ramifications for programs that do type checkingbut is generally benign (decorators might copy the original function' __name__but such forgery is limitedand could lead to confusionfor function callsthe decoration syntax can be more convenient than modifying each call to account for the extra logic leveland it avoids accidentally calling the original function directly consider nondecorator equivalent such as the followingcalls def tracer(func*args)global calls calls + print('call % to % (callsfunc __name__)func(*argsdef spam(abc)print(abcspam( normal nontraced callaccidentaltracer(spam call to spam special traced call without decorators this alternative can be used on any function without the special syntaxbut unlike the decorator versionit requires extra syntax at every place where the function is called in your code furthermoreits intent may not be as obviousand it does not ensure that the extra layer will be invoked for normal calls although decorators are never required (we can always rebind names manually)they are often the most convenient and uniform option decorators |
1,838 | the last example of the prior section raises an important issue function decorators have variety of options for retaining state information provided at decoration timefor use during the actual function call they generally need to support multiple decorated objects and multiple callsbut there are number of ways to implement these goalsinstance attributesglobal variablesnonlocal closure variablesand function attributes can all be used for retaining state class instance attributes for examplehere is an augmented version of the prior examplewhich adds support for keyword arguments with *syntaxand returns the wrapped function' result to support more use cases (for nonlinear readerswe first studied keyword arguments in and for readers working with the book examples packagesome filenames in this are again implied by the command-lines that follow their listings)class tracerstate via instance attributes def __init__(selffunc)on decorator self calls save func for later call self func func def __call__(self*args**kwargs)on call to original function self calls + print('call % to % (self callsself func __name__)return self func(*args**kwargs@tracer def spam(abc)print( csame asspam tracer(spamtriggers tracer __init__ @tracer def eggs(xy)print( *ysame aseggs tracer(eggswraps eggs in tracer object spam( spam( = = = really calls tracer instanceruns tracer __call__ spam is an instance attribute eggs( eggs( = really calls tracer instanceself func is eggs self calls is per-decoration here like the originalthis uses class instance attributes to save state explicitly both the wrapped function and the calls counter are per-instance information--each decoration gets its own copy when run as script under either or xthe output of this version is as followsnotice how the spam and eggs functions each have their own calls counterbecause each decoration creates new class instancec:\codepython decorator py call to spam call to spam call to eggs coding function decorators |
1,839 | call to eggs while useful for decorating functionsthis coding scheme still has issues when applied to methods-- shortcoming we'll address in later revision enclosing scopes and globals closure functions--with enclosing def scope references and nested defs--can often achieve the same effectespecially for static data like the decorated original function in this examplethoughwe would also need counter in the enclosing scope that changes on each calland that' not possible in python (recall from that the nonlocal statement is -onlyin xwe can still use either classes and attributes per the prior sectionor other options moving state variables out to the global scope with declarations is one candidateand works in both and xcalls def tracer(func)state via enclosing scope and global def wrapper(*args**kwargs)instead of class attributes global calls calls is globalnot per-function calls + print('call % to % (callsfunc __name__)return func(*args**kwargsreturn wrapper @tracer def spam(abc)print( csame asspam tracer(spam@tracer def eggs(xy)print( *ysame aseggs tracer(eggsspam( spam( = = = really calls wrapperassigned to spam wrapper calls spam eggs( eggs( = really calls wrapperassigned to eggs global calls is not per-decoration hereunfortunatelymoving the counter out to the common global scope to allow it to be changed like this also means that it will be shared by every wrapped function unlike class instance attributesglobal counters are cross-programnot per-function--the counter is incremented for any traced function call you can tell the difference if you compare this version' output with the prior version' --the singleshared global call counter is incorrectly updated by calls to every decorated functionc:\codepython decorator py call to spam call to spam decorators |
1,840 | call to eggs call to eggs enclosing scopes and nonlocals shared global state may be what we want in some cases if we really want per-function counterthoughwe can either use classes as beforeor make use of closure ( factoryfunctions and the nonlocal statement in python xdescribed in because this new statement allows enclosing function scope variables to be changedthey can serve as per-decoration and changeable data in onlydef tracer(func)state via enclosing scope and nonlocal calls instead of class attrs or global def wrapper(*args**kwargs)calls is per-functionnot global nonlocal calls calls + print('call % to % (callsfunc __name__)return func(*args**kwargsreturn wrapper @tracer def spam(abc)print( csame asspam tracer(spam@tracer def eggs(xy)print( *ysame aseggs tracer(eggsspam( spam( = = = really calls wrapperbound to func wrapper calls spam eggs( eggs( = really calls wrapperbound to eggs nonlocal calls _is_ per-decoration here nowbecause enclosing scope variables are not cross-program globalseach wrapped function gets its own counter againjust as for classes and attributes here' the new output when run under xc:\codepy - decorator py call to spam call to spam call to eggs call to eggs coding function decorators |
1,841 | finallyif you are not using python and don' have nonlocal statement--or you want your code to work portably on both and --you may still be able to avoid globals and classes by making use of function attributes for some changeable state instead in all pythons since we can assign arbitrary attributes to functions to attach themwith func attr=value because factory function makes new function on each callits attributes become per-call state moreoveryou need to use this technique only for state variables that must changeenclosing scope references are still retained and work normally in our examplewe can simply use wrapper calls for state the following works the same as the preceding nonlocal version because the counter is again per-decoratedfunctionbut it also runs in python xdef tracer(func)state via enclosing scope and func attr def wrapper(*args**kwargs)calls is per-functionnot global wrapper calls + print('call % to % (wrapper callsfunc __name__)return func(*args**kwargswrapper calls return wrapper @tracer def spam(abc)print( csame asspam tracer(spam@tracer def eggs(xy)print( *ysame aseggs tracer(eggsspam( spam( = = = really calls wrapperassigned to spam wrapper calls spam eggs( eggs( = really calls wrapperassigned to eggs wrapper calls _is_ per-decoration here as we learned in this works only because the name wrapper is retained in the enclosing tracer function' scope when we later increment wrapper callswe are not changing the name wrapper itselfso no nonlocal declaration is required this version runs in either python linec:\codepy - decorator py same output as prior versionbut works on too this scheme was almost relegated to footnotebecause it may be more obscure than nonlocal in and might be better saved for cases where other schemes don' help howeverfunction attributes also have substantial advantages for onethey allow access to the saved state from outside the decorator' codenonlocals can only be seen inside the nested function itselfbut function attributes have wider visibility for anotherthey are far more portablethis scheme also works in xmaking it versionneutral decorators |
1,842 | questionswhere their visibility outside callables becomes an asset as changeable state associated with context of usethey are equivalent to enclosing scope nonlocals as usualchoosing from multiple tools is an inherent part of the programming task because decorators often imply multiple levels of callablesyou can combine functions with enclosing scopesclasses with attributesand function attributes to achieve variety of coding structures as we'll see laterthoughthis sometimes may be subtler than you expect--each decorated function should have its own stateand each decorated class may require state both for itself and for each generated instance in factas the next section will explain in more detailif we want to apply function decorators to class-level methodstoowe also have to be careful about the distinction python makes between decorators coded as callable class instance objects and decorators coded as functions class blunders idecorating methods when wrote the first class-based tracer function decorator in decorator py earlieri naively assumed that it could also be applied to any method--decorated methods should work the samei reasonedbut the automatic self instance argument would simply be included at the front of *args the only real downside to this assumption is that it is completely wrongwhen applied to class' methodthe first version of the tracer failsbecause self is the instance of the decorator class and the instance of the decorated subject class is not included in *args at all this is true in both python and introduced this phenomenon earlier in this but now we can see it in the context of realistic working code given the class-based tracing decoratorclass tracerdef __init__(selffunc)on decorator self calls save func for later call self func func def __call__(self*args**kwargs)on call to original function self calls + print('call % to % (self callsself func __name__)return self func(*args**kwargsdecoration of simple functions works as advertised earlier@tracer def spam(abc)print( cspam( call to spam spam( = = = call to spam spam tracer(spamtriggers tracer __init__ runs tracer __call__ spam saved in an instance attribute coding function decorators |
1,843 | recognize this as an adaptation of our person class resurrected from the object-oriented tutorial in )class persondef __init__(selfnamepay)self name name self pay pay @tracer def giveraise(selfpercent)self pay *( percentgiveraise tracer(giveraise@tracer def lastname(self)return self name split()[- lastname tracer(lastnamebob person('bob smith' tracer remembers method funcs bob giveraise runs tracer __call__(??? call to giveraise typeerrorgiveraise(missing required positional argument'percentprint(bob lastname()runs tracer __call__(???call to lastname typeerrorlastname(missing required positional argument'selfthe root of the problem here is in the self argument of the tracer class' __call__ method--is it tracer instance or person instancewe really need both as it' codedthe tracer for decorator stateand the person for routing on to the original method reallyself must be the tracer objectto provide access to tracer' state information (its calls and func)this is true whether decorating simple function or method unfortunatelywhen our decorated method name is rebound to class instance object with __call__python passes only the tracer instance to selfit doesn' pass along the person subject in the arguments list at all moreoverbecause the tracer knows nothing about the person instance we are trying to process with method callsthere' no way to create bound method with an instanceand thus no way to correctly dispatch the call this isn' bugbut it' wildly subtle in the endthe prior listing winds up passing too few arguments to the decorated methodand results in an error add line to the decorator' __call__ to print all its arguments to verify this--as you can seeself is the tracer instanceand the person instance is entirely absentbob giveraise ( ,{call to giveraise traceback (most recent call last)file ""line in file ""line in __call__ typeerrorgiveraise(missing required positional argument'percent decorators |
1,844 | to self when method name is bound to simple function onlywhen it is an instance of callable classthat class' instance is passed instead technicallypython makes bound method object containing the subject instance only when the method is simple functionnot when it is callable instance of another class using nested functions to decorate methods if you want your function decorators to work on both simple functions and class-level methodsthe most straightforward solution lies in using one of the other state retention solutions described earlier--code your function decorator as nested defsso that you don' depend on single self instance argument to be both the wrapper class instance and the subject class instance the following alternative applies this fix using python nonlocalsrecode this to use function attributes for the changeable calls to use in because decorated methods are rebound to simple functions instead of instance objectspython correctly passes the person object as the first argumentand the decorator propagates it on in the first item of *args to the self argument of the realdecorated methodsa call tracer decorator for both functions and methods def tracer(func)use functionnot class with __call__ calls else "selfis decorator instance onlydef oncall(*args**kwargs)or in + xuse [oncall calls + nonlocal calls calls + print('call % to % (callsfunc __name__)return func(*args**kwargsreturn oncall if __name__ ='__main__'applies to simple functions @tracer def spam(abc)print( cspam tracer(spamoncall remembers spam @tracer def eggs( )return * spam( spam( = = = print(eggs( )runs oncall( applies to class-level method functions tooclass persondef __init__(selfnamepay)self name name self pay pay coding function decorators |
1,845 | def giveraise(selfpercent)self pay *( percent@tracer def lastname(self)return self name split()[- print('methods 'bob person('bob smith' sue person('sue jones' print(bob namesue namesue giveraise print(int(sue pay)print(bob lastname()sue lastname()giveraise tracer(giveraiseoncall remembers giveraise lastname tracer(lastnameruns oncall(sue runs oncall(bob)lastname in scopes we've also indented the file' self-test code under __name__ test so the decorator can be imported and used elsewhere this version works the same on both functions and methodsbut runs in only due to its nonlocalc:\codepy - calltracer py call to spam call to spam call to eggs methods bob smith sue jones call to giveraise call to lastname call to lastname smith jones trace through these results to make sure you have handle on this modelthe next section provides an alternative to it that supports classesbut is also substantially more complex using descriptors to decorate methods although the nested function solution illustrated in the prior section is the most straightforward way to support decorators that apply to both functions and class-level methodsother schemes are possible the descriptor feature we explored in the prior for examplecan help here as well recall from our discussion in that that descriptor is normally class attribute assigned to an object with __get__ method run automatically whenever that attribute is referenced and fetchednew-style class object derivation is required for descriptors in python xbut not xclass descriptor(object)def __get__(selfinstanceowner) decorators |
1,846 | attr descriptor( subject( attr roughly runs descriptor __get__(subject attrxsubjectdescriptors may also have __set__ and __del__ access methodsbut we don' need them here more relevant to this topicbecause the descriptor' __get__ method receives both the descriptor class instance and subject class instance when invokedit' well suited to decorating methods when we need both the decorator' state and the original class instance for dispatching calls consider the following alternative tracing decoratorwhich also happens to be descriptor when used for class-level methodclass tracer(object) decorator+descriptor def __init__(selffunc)on decorator self calls save func for later call self func func def __call__(self*args**kwargs)on call to original func self calls + print('call % to % (self callsself func __name__)return self func(*args**kwargsdef __get__(selfinstanceowner)on method attribute fetch return wrapper(selfinstanceclass wrapperdef __init__(selfdescsubj)save both instances self desc desc route calls back to deco/desc self subj subj def __call__(self*args**kwargs)return self desc(self subj*args**kwargsruns tracer __call__ @tracer def spam(abc)same as prior spam tracer(spamuses __call__ only class person@tracer def giveraise(selfpercent)same as prior giveraise tracer(giveraisemakes giveraise descriptor this works the same as the preceding nested function coding its operation varies by usage contextdecorated functions invoke only its __call__and never invoke its __get__ decorated methods invoke its __get__ first to resolve the method name fetch (on method)the object returned by __get__ retains the subject class instance and is then invoked to complete the call expressionthereby triggering the decorator' __call__ (on ()for examplethe test code' call tocoding function decorators |
1,847 | runs __get__ then __call__ runs tracer __get__ firstbecause the giveraise attribute in the person class has been rebound to descriptor by the method function decorator the call expression then triggers the __call__ method of the returned wrapper objectwhich in turn invokes tracer __call__ in other wordsdecorated method calls trigger four-step processtracer __get__followed by three call operations-wrapper __call__tracer __call__and finally the original wrapped method the wrapper object retains both descriptor and subject instancesso it can route control back to the original decorator/descriptor class instance in effectthe wrapper object saves the subject class instance available during method attribute fetch and adds it to the later call' arguments listwhich is passed to the decorator__call__ routing the call back to the descriptor class instance this way is required in this application so that all calls to wrapped method use the same calls counter state information in the descriptor instance object alternativelywe could use nested function and enclosing scope references to achieve the same effect--the following version works the same as the preceding oneby swapping class and object attributes for nested function and scope references it requires noticeably less codebut follows the same four-step process on each decorated method callclass tracer(object)def __init__(selffunc)on decorator self calls save func for later call self func func def __call__(self*args**kwargs)on call to original func self calls + print('call % to % (self callsself func __name__)return self func(*args**kwargsdef __get__(selfinstanceowner)on method fetch def wrapper(*args**kwargs)retain both inst return self(instance*args**kwargsruns __call__ return wrapper add print statements to these alternativesmethods to trace the multistep get/call process on your ownand run them with the same test code as in the nested function alternative shown earlier (see file calltracer-descr py for their sourcein either codingthis descriptor-based scheme is also substantially subtler than the nested function optionand so is probably second choice here to be more bluntif its complexity doesn' send you screaming into the nightits performance costs probably shouldstillthis may be useful coding pattern in other contexts it' also worth noting that we might code this descriptor-based decorator more simply as followsbut it would then apply only to methodsnot to simple functions--an intrinsic limitation of attribute descriptors (and just the inverse of the problem we're trying to solveapplication to both functions and methodsclass tracer(object)def __init__(selfmeth) decorators for methodsbut not functionson decorator |
1,848 | self calls self meth meth def __get__(selfinstanceowner)on method fetch def wrapper(*args**kwargs)on method callproxy with self+inst self calls + print('call % to % (self callsself meth __name__)return self meth(instance*args**kwargsreturn wrapper class person@tracer def giveraise(selfpercent)applies to class methods giveraise tracer(giveraisemakes giveraise descriptor @tracer def spam(abc)but fails for simple functions spam tracer(spamno attribute fetch occurs here in the rest of this we're going to be fairly casual about using classes or functions to code our function decoratorsas long as they are applied only to functions some decorators may not require the instance of the original classand will still work on both functions and methods if coded as class--something like python' own staticme thod decoratorfor examplewouldn' require an instance of the subject class (indeedits whole point is to remove the instance from the callthe moral of this storythoughis that if you want your decorators to work on both simple functions and methodsyou're probably better off using the nested-functionbased coding pattern outlined here instead of class with call interception timing calls to sample the fuller flavor of what function decorators are capable oflet' turn to different use case our next decorator times calls made to decorated function--both the time for one calland the total time among all calls the decorator is applied to two functionsin order to compare the relative speed of list comprehensions and the map built-in callfile timerdeco py caveatrange still differs list in xan iterable in caveattimer won' work on methods as coded (see quiz solutionimport timesys force list if sys version_info[ = else (lambda xxclass timerdef __init__(selffunc)self func func self alltime def __call__(self*args**kargs)start time clock(result self func(*args**kargscoding function decorators |
1,849 | self alltime +elapsed print('% (self func __name__elapsedself alltime)return result @timer def listcomp( )return [ for in range( )@timer def mapcall( )return force(map((lambda xx )range( ))result listcomp( time for this callall callsreturn value listcomp( listcomp( listcomp( print(resultprint('alltime %slistcomp alltimetotal time for all listcomp calls print(''result mapcall( mapcall( mapcall( mapcall( print(resultprint('alltime %smapcall alltimetotal time for all mapcall calls print('\ **map/comp %sround(mapcall alltime listcomp alltime )when run in either python or xthe output of this file' self-test code is as follows --giving for each function call the function nametime for this calland time for all calls so faralong with the first call' return valuecumulative time for each functionand the map-to-comprehension time ratio at the endc:\codepy - timerdeco py listcomp listcomp listcomp listcomp [ alltime mapcall mapcall mapcall mapcall [ alltime **map/comp times vary per python line and test machineof courseand cumulative time is available as class instance attribute here as usualmap calls are almost twice as slow as list decorators |
1,850 | decorators versus per-call timing for comparisonsee for nondecorator approach to timing iteration alternatives like these as reviewwe saw two per-call timing techniques therehomegrown and library--here deployed to time the list comprehension case of the decorator' test codethough incurring extra costs for management code including an outer loop and function callsdef listcomp( )[ for in range( ) techniques import timer timer total( listcomp ( noneimport timeit timeit timeit(number= stmt=lambdalistcomp( ) in this specific casea nondecorator approach would allow the subject functions to be used with or without timingbut it would also complicate the call signature when timing is desired--we' need to add code at every call instead of once at the def moreoverin the nondecorator scheme there would be no direct way to guarantee that all list builder calls in program are routed through timer logicshort of finding and potentially changing them all this may make it difficult to collect cumulative data for all calls in generaldecorators may be preferred when functions are already deployed as part of larger systemand may not be easily passed to analysis functions at calls on the other handbecause decorators charge each call to function with augmentation logica nondecorator approach may be better if you wish to augment calls more selectively as usualdifferent tools serve different roles timer call portability and new options in also see ' more complete handling and selection of time module functionsas well as its sidebar concerning the new and improved timer functions in this module available as of python ( perf_counterwe're taking simplistic approach here for both brevity and version neutralitybut time clock may not be best on some platforms even prior to and platform or version tests may be required outside windows testing subtleties notice how this script uses its force setting to make it portable between and as described in the map built-in returns an iterable that generates results on demand in xbut an actual list in hence ' map by itself doesn' compare directly to list comprehension' work in factwithout wrapping it in list call to coding function decorators |
1,851 | iterable without iteratingat the same timeadding this list call in too charges map with an unfair penalty-the map test' results would include the time required to build two listsnot one to work around thisthe script selects map enclosing function per the python version number in sysin xpicking listand in using no-op function that simply returns its input argument unchanged this adds very minor constant time in xwhich is probably fully overshadowed by the cost of the inner loop iterations in the timed function while this makes the comparison between list comprehensions and map more fair in either or xbecause range is also an iterator in xthe results for and won' compare directly unless you also hoist this call out of the timed code they'll be relatively comparable--and will reflect best practice code in each line anyhow--but range iteration adds extra time in only for more on all such thingssee ' benchmark recreationsproducing comparable numbers is often nontrivial task finallyas we did for the tracer decorator earlierwe could make this timing decorator reusable in other modules by indenting the self-test code at the bottom of the file under __name__ test so it runs only when the file is runnot when it' imported we won' do this herethoughbecause we're about to add another feature to our code adding decorator arguments the timer decorator of the prior section worksbut it would be nice if it were more configurable--providing an output label and turning trace messages on and offfor instancemight be useful in general-purpose tool like this decorator arguments come in handy herewhen they're coded properlywe can use them to specify configuration options that can vary for each decorated function labelfor instancemight be added as followsdef timer(label='')def decorator(func)def oncall(*args)func(*argsprint(labelreturn oncall return decorator multilevel state retentionargs passed to function func retained in enclosing scope label retained in enclosing scope @timer('==>'def listcomp( )like listcomp timer('==>')(listcomplistcomp is rebound to new oncall listcompreally calls oncall returns the actual decorator this code adds an enclosing scope to retain decorator argument for use on later actual call when the listcomp function is definedpython really invokes decorator- decorators |
1,852 | the decorator argument and the original functionand returns the callable oncallwhich ultimately invokes the original function on later calls because this structure creates new decorator and oncall functionstheir enclosing scopes are per-decoration state retention we can put this structure to use in our timer to allow label and trace control flag to be passed in at decoration time here' an example that does just thatcoded in module file named timerdeco py so it can be imported as general toolit uses class for the second state retention level instead of nested functionbut the net result is similarimport time def timer(label=''trace=true)on decorator argsretain args class timerdef __init__(selffunc)on @retain decorated func self func func self alltime def __call__(self*args**kargs)on callscall original start time clock(result self func(*args**kargselapsed time clock(start self alltime +elapsed if traceformat '% % fvalues (labelself func __name__elapsedself alltimeprint(format valuesreturn result return timer mostly all we've done here is embed the original timer class in an enclosing functionin order to create scope that retains the decorator arguments per deployment the outer timer function is called before decoration occursand it simply returns the timer class to serve as the actual decorator on decorationan instance of timer is made that remembers the decorated function itselfbut also has access to the decorator arguments in the enclosing function scope timing with decorator arguments this timerather than embedding self-test code in this filewe'll run the decorator in different file here' client of our timer decoratorthe module file testseqs pyapplying it to sequence iteration alternatives againimport sys from timerdeco import timer force list if sys version_info[ = else (lambda xx@timer(label='[ccc]==>'def listcomp( )return [ for in range( )like listcomp timer)(listcomplistcomptriggers timer __call__ coding function decorators |
1,853 | def mapcall( )return force(map((lambda xx )range( ))for func in (listcompmapcall)result func( time for this callall callsreturn value func( func( func( print(resultprint('alltime % \nfunc alltimetotal time for all calls print('**map/comp %sround(mapcall alltime listcomp alltime )againto make this fairmap is wrapped in list call in only when run as is in or xthis file prints the following--each decorated function now has label of its own defined by decorator argumentswhich will be more useful when we need to find trace displays mixed in with larger program' outputc:\codepy - testseqs py [ccc]==listcomp [ccc]==listcomp [ccc]==listcomp [ccc]==listcomp [ alltime [mmm]==mapcall [mmm]==mapcall [mmm]==mapcall [mmm]==mapcall [ alltime **map/comp as usualwe can also test interactively to see how the decorator' configuration arguments come into playfrom timerdeco import timer @timer(trace=falseno tracingcollect total time def listcomp( )return [ for in range( ) listcomp( listcomp( listcomp( listcomp alltime listcomp timer object at @timer(trace=truelabel='\ =>'def listcomp( ) decorators turn on tracingcustom label |
1,854 | return [ for in range( ) listcomp( =listcomp listcomp( =listcomp listcomp( =listcomp listcomp alltime as isthis timing function decorator can be used for any functionboth in modules and interactively in other wordsit automatically qualifies as general-purpose tool for timing code in our scripts watch for another example of decorator arguments in the section "implementing private attributeson page and again in " basic rangetesting decorator for positional argumentssupporting methodsthis section' timer decorator works on any functionbut minor rewrite is required to be able to apply it to class-level methods too in shortas our earlier section "class blunders idecorating methodson page illustratedit must avoid using nested class because this mutation was deliberately reserved to be subject of one of our end-of-quiz questionsthoughi'll avoid giving away the answer completely here coding class decorators so far we've been coding function decorators to manage function callsbut as we've seendecorators have been extended to work on classes too as of python and as described earlierwhile similar in concept to function decoratorsclass decorators are applied to classes instead--they may be used either to manage classes themselvesor to intercept instance creation calls in order to manage instances also like function decoratorsclass decorators are really just optional syntactic sugarthough many believe that they make programmer' intent more obvious and minimize erroneous or missed calls singleton classes because class decorators may intercept instance creation callsthey can be used to either manage all the instances of classor augment the interfaces of those instances to demonstratehere' first class decorator example that does the former--managing all instances of class this code implements the classic singleton coding patternwhere at most one instance of class ever exists its singleton function defines and returns function for managing instancesand the syntax automatically wraps up subject class in this functioncoding class decorators |
1,855 | instances {def singleton(aclass)on decoration def oncall(*args**kwargs)on instance creation if aclass not in instancesone dict entry per class instances[aclassaclass(*args**kwargsreturn instances[aclassreturn oncall to use thisdecorate the classes for which you want to enforce single-instance model (for referenceall the code in this section is in the file singletons py)@singleton class persondef __init__(selfnamehoursrate)self name name self hours hours self rate rate def pay(self)return self hours self rate person singleton(personrebinds person to oncall oncall remembers person @singleton class spamdef __init__(selfval)self attr val spam singleton(spamrebinds spam to oncall oncall remembers spam bob person('bob' print(bob namebob pay()really calls oncall sue person('sue' print(sue namesue pay()samesingle object spam(val= spam( print( attry attrone personone spam nowwhen the person or spam class is later used to create an instancethe wrapping logic layer provided by the decorator routes instance construction calls to oncallwhich in turn ensures single instance per classregardless of how many construction calls are made here' this code' output ( prints extra tuple parentheses) :\codepython singletons py bob bob coding alternatives interestinglyyou can code more self-contained solution here if you're able to use the nonlocal statement (available in python onlyto change enclosing scope namesas described earlier--the following alternative achieves an identical effectby using one enclosing scope per classinstead of one global table entry per class it works the same decorators |
1,856 | the none check could use is instead of =herebut it' trivial test either way) onlynonlocal def singleton(aclass)instance none def oncall(*args**kwargs)nonlocal instance if instance =noneinstance aclass(*args**kwargsreturn instance return oncall on decoration on instance creation and later nonlocal one scope per class in either python or ( and later)you can also code self-contained solution with either function attributes or class instead the first of the following codes the formerleveraging the fact that there will be one oncall function per decoration--the object namespace serves the same role as an enclosing scope the second uses one instance per decorationrather than an enclosing scopefunction objector global table in factthe second relies on the same coding pattern that we will later see is common decorator class blunder--here we want just one instancebut that' not usually the case and xfunc attrsclasses (alternative codingsdef singleton(aclass)def oncall(*args**kwargs)if oncall instance =noneoncall instance aclass(*args**kwargsreturn oncall instance oncall instance none return oncall on decoration on instance creation one function per class class singletondef __init__(selfaclass)on decoration self aclass aclass self instance none def __call__(self*args**kwargs)on instance creation if self instance =noneself instance self aclass(*args**kwargsone instance per class return self instance to make this decorator fully general-purpose toolchoose onestore it in an importable module fileand indent the self-test code under __name__ check--steps we'll leave as suggested exercise the final class-based version offers portability and explicit optionwith extra structure that may better support later evolutionbut oop might not be warranted in all contexts tracing object interfaces the singleton example of the prior section illustrated using class decorators to manage all the instances of class another common use case for class decorators augments the interface of each generated instance class decorators can essentially install on incoding class decorators |
1,857 | way for examplein the __getattr__ operator overloading method is shown as way to wrap up entire object interfaces of embedded instancesin order to implement the delegation coding pattern we saw similar examples in the managed attribute coverage of the prior recall that __getattr__ is run when an undefined attribute name is fetchedwe can use this hook to intercept method calls in controller class and propagate them to an embedded object for referencehere' the original nondecorator delegation exampleworking on two built-in type objectsclass wrapperdef __init__(selfobject)self wrapped object def __getattr__(selfattrname)print('trace:'attrnamereturn getattr(self wrappedattrnamesave object trace fetch delegate fetch wrapper([ , , ] append( traceappend wrapped [ wrap list delegate to list method wrapper({" " " " }list( keys()tracekeys [' '' 'wrap dictionary delegate to dictionary method use list(in print my member in this codethe wrapper class intercepts access to any of the wrapped object' named attributesprints trace messageand uses the getattr built-in to pass off the request to the wrapped object specificallyit traces attribute accesses made outside the wrapped object' classaccesses inside the wrapped object' methods are not caught and run normally by design this whole-interface model differs from the behavior of function decoratorswhich wrap up just one specific method tracing interfaces with class decorators class decorators provide an alternative and convenient way to code this __getattr__ technique to wrap an entire interface as of both and for examplethe prior class example can be coded as class decorator that triggers wrapped instance creationinstead of passing premade instance into the wrapper' constructor (also augmented here to support keyword arguments with **kargs and to count the number of accesses made to illustrate changeable state)def tracer(aclass)class wrapperdef __init__(self*args**kargs)self fetches decorators on decorator on instance creation |
1,858 | def __getattr__(selfattrname)print('traceattrnameself fetches + return getattr(self wrappedattrnamereturn wrapper use enclosing scope name catches all but own attrs delegate to wrapped obj if __name__ ='__main__'@tracer class spamdef display(self)print('spam! @tracer class persondef __init__(selfnamehoursrate)self name name self hours hours self rate rate def pay(self)return self hours self rate spam tracer(spamspam is rebound to wrapper person tracer(personwrapper remembers person accesses outside class traced in-method accesses not traced food spam(food display(print([food fetches]triggers wrapper(triggers __getattr__ bob person('bob' print(bob nameprint(bob pay()bob is really wrapper wrapper embeds person print(''sue person('sue'rate= hours= print(sue nameprint(sue pay()print(bob nameprint(bob pay()print([bob fetchessue fetches]sue is different wrapper with different person bob has different state wrapper attrs not traced it' important to note that this is very different from the tracer decorator we met earlier (despite the name!in "coding function decorators"we looked at decorators that enabled us to trace and time calls to given function or method in contrastby intercepting instance creation callsthe class decorator here allows us to trace an entire object interface--that isaccesses to any of the instance' attributes the following is the output produced by this code under both and ( and later)attribute fetches on instances of both the spam and person classes invoke the __getattr__ logic in the wrapper classbecause food and bob are really instances of wrapperthanks to the decorator' redirection of instance creation callsc:\codepython interfacetracer py tracedisplay coding class decorators |
1,859 | [ tracename bob tracepay tracename sue tracepay tracename bob tracepay [ notice how there is one wrapper class with state retention per decorationgenerated by the nested class statement in the tracer functionand how each instance gets its own fetches counter by virtue of generating new wrapper instance as we'll see aheadorchestrating this is trickier than you may expect applying class decorators to built-in types also notice that the preceding decorates user-defined class just like in the original example in we can also use the decorator to wrap up built-in type such as listas long as we either subclass to allow decoration syntax or perform the decoration manually--decorator syntax requires class statement for the line in the followingx is really wrapper again due to the indirection of decorationfrom interfacetracer import tracer @tracer class mylist(list)pass mylist tracer(mylistx mylist([ ] append( traceappend wrapped [ triggers wrapper(triggers __getattr__append wraplist tracer(listx wraplist([ ] append( traceappend wrapped [ or perform decoration manually else subclass statement required the decorator approach allows us to move instance creation into the decorator itselfinstead of requiring premade object to be passed in although this seems like minor differenceit lets us retain normal instance creation syntax and realize all the benefits of decorators in general rather than requiring all instance creation calls to route objects decorators |
1,860 | syntax@tracer class personbob person('bob' sue person('sue'rate= hours= decorator approach class personnondecorator approach bob wrapper(person('bob' )sue wrapper(person('sue'rate= hours= )assuming you will make more than one instance of classand want to apply the augmentation to every instance of classdecorators will generally be net win in terms of both code size and code maintenance attribute version skew notethe preceding tracer decorator works for explicitly accessed attribute names on all pythons as we learned in and elsewherethough__getattr__ intercepts built-insimplicit accesses to operator overloading methods like __str__ and __repr__ in python ' default classic classesbut not in ' new-style classes in python ' classesinstances inherit defaults for somebut not all of these names from the class (reallyfrom the object superclassmoreoverin ximplicitly invoked attributes for built-in operations like printing and are not routed through __getattr__or its cousin__get attribute__ in new-style classesbuilt-ins start such searches at classes and skip the normal instance lookup entirely herethis means that the __getattr__ based tracing wrapper will automatically trace and propagate operator overloading calls for built-ins in as codedbut not in to see thisdisplay "xdirectly at the end of the preceding interactive session--in the attribute __repr__ is traced and the list prints as expectedbut in no trace occurs and the list prints using default display for the wrapper classx trace__repr__ [ wrapper object at to work the same in xoperator overloading methods generally must be redefined redundantly in the wrapper classeither by handby toolsor by definition in superclasses we'll see this at work again in pri vate decorator later in this -where we'll also study ways to add the methods required of such code in coding class decorators |
1,861 | curiouslythe decorator function in this example can almost be coded as class instead of functionwith the proper operator overloading protocol the following slightly simplified alternative works similarly because its __init__ is triggered when the decorator is applied to the classand its __call__ is triggered when subject class instance is created our objects are really instances of tracer this timeand we essentially just trade an enclosing scope reference for an instance attribute hereclass tracerdef __init__(selfaclass)on @decorator self aclass aclass use instance attribute def __call__(self*args)on instance creation self wrapped self aclass(*argsone (lastinstance per classreturn self def __getattr__(selfattrname)print('traceattrnamereturn getattr(self wrappedattrname@tracer class spamdef display(self)print('spam! food spam(food display(triggers __init__ likespam tracer(spamtriggers __call__ triggers __getattr__ as we saw in the abstract earlierthoughthis class-only alternative handles multiple classes as beforebut it won' quite work for multiple instances of given classeach instance construction call triggers __call__which overwrites the prior instance the net effect is that tracer saves just one instance--the last one created experiment with this yourself to see howbut here' an example of the problem@tracer class persondef __init__(selfname)self name name bob person('bob'print(bob namesue person('sue'print(sue nameprint(bob nameperson tracer(personwrapper bound to person bob is really wrapper wrapper embeds person sue overwrites bob oopsnow bob' name is 'sue'this code' output follows--because this tracer only has single shared instancethe second overwrites the firsttracename bob tracename sue tracename sue decorators |
1,862 | but not per class instancesuch that only the last instance is retained the solutionas in our prior class blunder for decorating methodslies in abandoning class-based decorators the earlier function-based tracer version does work for multiple instancesbecause each instance construction call makes new wrapper instanceinstead of overwriting the state of single shared tracer instancethe original nondecorator version handles multiple instances correctly for the same reason the moral heredecorators are not only arguably magicalthey can also be incredibly subtledecorators versus manager functions regardless of such subtletiesthe tracer class decorator example ultimately still relies on __getattr__ to intercept fetches on wrapped and embedded instance object as we saw earlierall we've really accomplished is moving the instance creation call inside classinstead of passing the instance into manager function with the original nondecorator tracing examplewe would simply code instance creation differentlyclass spamfood wrapper(spam()nondecorator version any class will do special creation syntax @tracer class spamfood spam(decorator version requires syntax at class normal creation syntax essentiallyclass decorators shift special syntax requirements from the instance creation call to the class statement itself this is also true for the singleton example earlier in this section--rather than decorating class and using normal instance creation callswe could simply pass the class and its construction arguments into manager functioninstances {def getinstance(aclass*args**kwargs)if aclass not in instancesinstances[aclassaclass(*args**kwargsreturn instances[aclassbob getinstance(person'bob' versusbob person('bob' alternativelywe could use python' introspection facilities to fetch the class from an already created instance (assuming creating an initial instance is acceptable)instances {def getinstance(object)aclass object __class__ if aclass not in instancesinstances[aclassobject return instances[aclassbob getinstance(person('bob' )versusbob person('bob' coding class decorators |
1,863 | decorating function with logic that intercepts later callswe could simply pass the function and its arguments into manager that dispatches the calldef func(xy)result tracer(func( )nondecorator version def tracer(funcargs)func(*argsspecial call syntax @tracer def func(xy)result func( decorator version rebinds namefunc tracer(funcnormal call syntax manager function approaches like this place the burden of using special syntax on callsinstead of expecting decoration syntax at function and class definitionsbut also allow you to selectively apply augmentation on call-by-call basis why decorators(revisitedso why did just show you ways to not use decorators to implement singletonsas mentioned at the start of this decorators present us with tradeoffs although syntax matterswe all too often forget to ask the "whyquestions when confronted with new tools now that we've seen how decorators actually worklet' step back for minute to glimpse the big picture here before moving on to more code like most language featuresdecorators have both pros and cons for examplein the negatives columndecorators may suffer from three potential drawbackswhich can vary per decorator typetype changes as we've seenwhen wrappers are inserteda decorated function or class does not retain its original type--it is rebound to wrapper (proxyobjectwhich might matter in programs that use object names or test object types in the singleton exampleboth the decorator and manager function approaches retain the original class type for instancesin the tracer codeneither approach doesbecause wrappers are required of courseyou should avoid type checks in polymorphic language like python anyhowbut there are exceptions to most rules extra calls wrapping layer added by decoration incurs the additional performance cost of an extra call each time the decorated object is invoked--calls are relatively timeexpensive operationsso decoration wrappers can make program slower in the tracer codeboth approaches require each attribute to be routed through wrapper layerthe singleton example avoids extra calls by retaining the original class type all or nothing because decorators augment function or classthey generally apply to every later call to the decorated object that ensures uniform deploymentbut can also be decorators |
1,864 | basis that saidnone of these is very serious issue for most programsdecorationsuniformity is an assetthe type difference is unlikely to matterand the speed hit of the extra calls will be insignificant furthermorethe latter of these occurs only when wrappers are usedcan often be negated if we simply remove the decorator when optimal performance is requiredand is also incurred by nondecorator solutions that add wrapping logic (including metaclassesas we'll see in converselyas we saw at the start of this decorators have three main advantages compared to the manager ( "helper"function solutions of the prior sectiondecorators offerexplicit syntax decorators make augmentation explicit and obvious their syntax is easier to recognize than special code in calls that may appear anywhere in source file--in our singleton and tracer examplesfor instancethe decorator lines seem more likely to be noticed than extra code at calls would be moreoverdecorators allow function and instance creation calls to use normal syntax familiar to all python programmers code maintenance decorators avoid repeated augmentation code at each function or class call because they appear just onceat the definition of the class or function itselfthey obviate redundancy and simplify future code maintenance for our singleton and tracer caseswe need to use special code at each call to use manager function approach--extra work is required both initially and for any modifications that must be made in the future consistency decorators make it less likely that programmer will forget to use required wrapping logic this derives mostly from the two prior advantages--because decoration is explicit and appears only onceat the decorated objects themselvesdecorators promote more consistent and uniform api usage than special code that must be included at each call in the singleton examplefor instanceit would be easy to forget to route all class creation calls through special codewhich would subvert the singleton management altogether decorators also promote code encapsulation to reduce redundancy and minimize future maintenance effortalthough other code structuring tools do toodecorators add explicit structure that makes this natural for augmentation tasks none of these benefits completely requires decorator syntax to be achievedthoughand decorator usage is ultimately stylistic choice that saidmost programmers find them to be net winespecially as tool for using libraries and apis correctly coding class decorators |
1,865 | and against constructor functions in classes--prior to the introduction of __init__ methodsprogrammers achieved the same effect by running an instance through method manually when creating it ( =class(init()over timethoughdespite being fundamentally stylistic choicethe __init__ syntax came to be universally preferred because it was more explicitconsistentand maintainable although you should be the judgedecorators seem to bring many of the same assets to the table managing functions and classes directly most of our examples in this have been designed to intercept function and instance creation calls although this is typical for decoratorsthey are not limited to this role because decorators work by running new functions and classes through decorator codethey can also be used to manage function and class objects themselvesnot just later calls made to them imaginefor examplethat you require methods or classes used by an application to be registered to an api for later processing (perhaps that api will call the objects laterin response to eventsalthough you could provide registration function to be called manually after the objects are defineddecorators make your intent more explicit the following simple implementation of this idea defines decorator that can be applied to both functions and classesto add the object to dictionary-based registry because it returns the object itself instead of wrapperit does not intercept later callsregistering decorated objects to an api from __future__ import print_function registry {def register(obj)registry[obj __name__obj return obj both class and func decorator add to registry return obj itselfnot wrapper @register def spam( )return( * spam register(spam@register def ham( )return( * @register class eggsdef __init__(selfx)self data * def __str__(self)return str(self data decorators eggs register(eggs |
1,866 | for name in registryprint(name'=>'registry[name]type(registry[name])print('\nmanual calls:'print(spam( )print(ham( ) eggs( print(xinvoke objects manually later calls not intercepted print('\nregistry calls:'for name in registryprint(name'=>'registry[name]( )invoke from registry when this code is run the decorated objects are added to the registry by namebut they still work as originally coded when they're called laterwithout being routed through wrapper layer in factour objects can be run both manually and from inside the registry tablec:\codepy - registry-deco py registryspam =ham =eggs =manual calls registry callsspam = ham = eggs = user interface might use this techniquefor exampleto register callback handlers for user actions handlers might be registered by function or class nameas done hereor decorator arguments could be used to specify the subject eventan extra def statement enclosing our decorator could be used to retain such arguments for use on decoration this example is artificialbut its technique is very general for examplefunction decorators might also be used to process function attributesand class decorators might insert new class attributesor even new methodsdynamically consider the following function decorators--they assign function attributes to record information for later use by an apibut they do not insert wrapper layer to intercept later callsaugmenting decorated objects directly def decorate(func)func marked true return func assign function attribute for later use @decorate def spam(ab)managing functions and classes directly |
1,867 | spam marked true def annotate(text)def decorate(func)func label text return func return decorate @annotate('spam data'def spam(ab)return samebut value is decorator argument spam annotate)(spamspam( )spam label ( 'spam data'such decorators augment functions and classes directlywithout catching later calls to them we'll see more examples of class decorations managing classes directly in the next because this turns out to encroach on the domain of metaclassesfor the remainder of this let' turn to two larger case studies of decorators at work example"privateand "publicattributes the final two sections of this present larger examples of decorator use both are presented with minimal descriptionpartly because this has hit its size limitsbut mostly because you should already understand decorator basics well enough to study these on your own being general-purpose toolsthese examples give us chance to see how decorator concepts come together in more useful code implementing private attributes the following class decorator implements private declaration for class instance attributes--that isattributes stored on an instanceor inherited from one of its classes it disallows fetch and change access to such attributes from outside the decorated classbut still allows the class itself to access those names freely within its own methods it' not exactly +or javabut it provides similar access control as an option in python we saw an incomplete first-cut implementation of instance attribute privacy for changes only in the version here extends this concept to validate attribute fetches tooand it uses delegation instead of inheritance to implement the model in factin sense this is just an extension to the attribute tracer class decorator we met earlier although this example utilizes the new syntactic sugar of class decorators to code attribute privacyits attribute interception is ultimately still based upon the __get attr__ and __setattr__ operator overloading methods we met in prior when decorators |
1,868 | exceptionalong with an error messagethe exception may be caught in try or allowed to terminate the script here is the codealong with self test at the bottom of the file it will work under both python and ( and laterbecause it employs version-neutral print and raise syntaxthough as coded it catches built-insdispatch to operator overloading method attributes in only (more on this in moment)""file access py ( xprivacy for attributes fetched from class instances see self-test code at end of file for usage example decorator same asdoubler private('data''size')(doublerprivate returns ondecoratorondecorator returns oninstanceand each oninstance instance embeds doubler instance ""traceme false def trace(*args)if tracemeprint('[join(map(strargs)']'def private(*privates)privates in enclosing scope def ondecorator(aclass)aclass in enclosing scope class oninstancewrapped in instance attribute def __init__(self*args**kargs)self wrapped aclass(*args**kargsdef __getattr__(selfattr)my attrs don' call getattr trace('get:'attrothers assumed in wrapped if attr in privatesraise typeerror('private attribute fetchattrelsereturn getattr(self wrappedattrdef __setattr__(selfattrvalue)outside accesses trace('set:'attrvalueothers run normally if attr ='wrapped'allow my attrs self __dict__[attrvalue avoid looping elif attr in privatesraise typeerror('private attribute changeattrelsesetattr(self wrappedattrvaluewrapped obj attrs return oninstance or use __dict__ return ondecorator if __name__ ='__main__'traceme true @private('data''size'class doublerdoubler private)(doublerexample"privateand "publicattributes |
1,869 | self label label accesses inside the subject class self data start not interceptedrun normally def size(self)return len(self datamethods run with no checking def double(self)because privacy not inherited for in range(self size())self data[iself data[ def display(self)print('% =% (self labelself data) doubler(' is'[ ] doubler(' is'[- - - ]the following all succeed print( labelx display() double() display(print( labely display() double( label 'spamy display(accesses outside subject class interceptedvalidateddelegated the following all fail properly ""print( size()prints "typeerrorprivate attribute fetchsizeprint( datax data [ size lambda print( dataprint( size()""when traceme is truethe module file' self-test code produces the following output notice how the decorator catches and validates both attribute fetches and assignments run outside of the wrapped classbut does not catch attribute accesses inside the class itselfc:\codepy - access py [setwrapped [setwrapped [getlabelx is [getdisplayx is =[ [getdouble[getdisplayx is =[ [getlabely is [getdisplayy is =[- - - [getdouble[setlabel spam[getdisplayspam =[- - - decorators |
1,870 | this code is bit complexand you're probably best off tracing through it on your own to see how it works to help you studythoughhere are few highlights worth mentioning inheritance versus delegation the first-cut privacy example shown in used inheritance to mix in __setattr__ to catch accesses inheritance makes this difficulthoweverbecause differentiating between accesses from inside or outside the class is not straightforward (inside access should be allowed to run normallyand outside access should be restrictedto work around thisthe example requires inheriting classes to use __dict__ assignments to set attributes--an incomplete solution at best the version here uses delegation (embedding one object inside anotherinstead of inheritancethis pattern is better suited to our taskas it makes it much easier to distinguish between accesses inside and outside of the subject class attribute accesses from outside the subject class are intercepted by the wrapper layer' overloading methods and delegated to the class if valid accesses inside the class itself ( through self within its methodscodeare not intercepted and are allowed to run normally without checksbecause privacy is not inherited in this version decorator arguments the class decorator used here accepts any number of argumentsto name private attributes what really happensthoughis that the arguments are passed to the pri vate functionand private returns the decorator function to be applied to the subject class that isthe arguments are used before decoration ever occursprivate returns the decoratorwhich in turn "remembersthe privates list as an enclosing scope reference state retention and enclosing scopes speaking of enclosing scopesthere are actually three levels of state retention at work in this codethe arguments to private are used before decoration occurs and are retained as an enclosing scope reference for use in both ondecorator and oninstance the class argument to ondecorator is used at decoration time and is retained as an enclosing scope reference for use at instance construction time the wrapped instance object is retained as an instance attribute in the onin stance proxy objectfor use when attributes are later accessed from outside the class this all works fairly naturallygiven python' scope and namespace rules example"privateand "publicattributes |
1,871 | the __setattr__ method in this code relies on an instance object' __dict__ attribute namespace dictionary in order to set oninstance' own wrapped attribute as we learned in the prior this method cannot assign an attribute directly without looping howeverit uses the setattr built-in instead of __dict__ to set attributes in the wrapped object itself moreovergetattr is used to fetch attributes in the wrapped objectsince they may be stored in the object itself or inherited by it because of thatthis code will work for most classes--including those with "virtualclass-level attributes based on slotspropertiesdescriptorsand even __getattr__ and its ilk by assuming namespace dictionary for itself only and using storage-neutral tools for the wrapped objectthe wrapper class avoids limitations inherent in other tools for exampleyou may recall from that new-style classes with __slots__ may not store attributes in __dict__ (and in fact may not even have one of these at allhoweverbecause we rely on __dict__ only at the oninstance level hereand not in the wrapped instancethis concern does not apply in additionbecause setattr and getattr apply to attributes based on both __dict__ and __slots__our decorator applies to classes using either storage scheme by the same reasoningthe decorator also applies to new-style properties and similar toolsdelegated names will be looked up anew in the wrapped instanceirrespective of attributes of the decorator proxy object itself generalizing for public declarationstoo now that we have private implementationit' straightforward to generalize the code to allow for public declarations too--they are essentially the inverse of private declarationsso we need only negate the inner test the example listed in this section allows class to use decorators to define set of either private or public instance attributes --attributes of any kind stored on an instance or inherited from its classes--with the following semanticsprivate declares attributes of class' instances that cannot be fetched or assignedexcept from within the code of the class' methods that isany name declared private cannot be accessed from outside the classwhile any name not declared private can be freely fetched or assigned from outside the class public declares attributes of class' instances that can be fetched or assigned from both outside the class and within the class' methods that isany name declared public can be freely accessed anywherewhile any name not declared public cannot be accessed from outside the class private and public declarations are intended to be mutually exclusivewhen using privateall undeclared names are considered publicand when using publicall undeclared names are considered private they are essentially inversesthough undeclared names not created by class' methods behave slightly differently--new names decorators |
1,872 | are accessible)but not under public (all undeclared names are inaccessibleagainstudy this code on your own to get feel for how this works notice that this scheme adds an additional fourth level of state retention at the topbeyond that described in the preceding sectionthe test functions used by the lambdas are saved in an extra enclosing scope this example is coded to run under either python or ( or later)though it comes with caveat when run under (explained briefly in the file' docstring and expanded on after the code)""file access py ( xclass decorator with private and public attribute declarations controls external access to attributes stored on an instanceor inherited by it from its classes private declares attribute names that cannot be fetched or assigned outside the decorated classand public declares all the names that can caveatthis works in for explicitly named attributes only__x__ operator overloading methods implicitly run for built-in operations do not trigger either __getattr__ or __getattribute__ in new-style classes add __x__ methods here to intercept and delegate built-ins ""traceme false def trace(*args)if tracemeprint('[join(map(strargs)']'def accesscontrol(failif)def ondecorator(aclass)class oninstancedef __init__(self*args**kargs)self __wrapped aclass(*args**kargsdef __getattr__(selfattr)trace('get:'attrif failif(attr)raise typeerror('private attribute fetchattrelsereturn getattr(self __wrappedattrdef __setattr__(selfattrvalue)trace('set:'attrvalueif attr ='_oninstance__wrapped'self __dict__[attrvalue elif failif(attr)raise typeerror('private attribute changeattrelsesetattr(self __wrappedattrvaluereturn oninstance return ondecorator def private(*attributes)example"privateand "publicattributes |
1,873 | def public(*attributes)return accesscontrol(failif=(lambda attrattr not in attributes)see the prior example' self-test code for usage example here' quick look at these class decorators in action at the interactive promptthey work the same in and for attributes referenced by explicit name like those tested here as advertisednonprivate or public names can be fetched and changed from outside the subject classbut private or non-public names cannotfrom access import privatepublic @private('age'class persondef __init__(selfnameage)self name name self age age person('bob' name 'bobx name 'suex name 'suex age typeerrorprivate attribute fetchage age 'tomtypeerrorprivate attribute changeage person private('age')(personperson oninstance with state inside accesses run normally outside accesses validated @public('name'class persondef __init__(selfnameage)self name name self age age person('bob' name 'bobx name 'suex name 'suex age typeerrorprivate attribute fetchage age 'tomtypeerrorprivate attribute changeage is an oninstance oninstance embeds person implementation details ii to help you analyze the codehere are few final notes on this version since this is just generalization of the preceding section' versionthe implementation notes there apply here as well decorators |
1,874 | besides generalizingthis version also makes use of python' __x pseudoprivate name mangling feature (which we met in to localize the wrapped attribute to the proxy control classby automatically prefixing it with this class' name this avoids the prior version' risk for collisions with wrapped attribute that may be used by the realwrapped classand it' useful in general tool like this it' not quite "privacy,thoughbecause the mangled version of the name can be used freely outside the class notice that we also have to use the fully expanded name string--'_oninstance__wrap ped'-as test value in __setattr__because that' what python changes it to breaking privacy although this example does implement access controls for attributes of an instance and its classesit is possible to subvert these controls in various ways--for instanceby going through the expanded version of the wrapped attribute explicitly (bob pay might not workbut the fully mangled bob _oninstance__wrapped pay could!if you have to explicitly try to do sothoughthese controls are probably sufficient for normal intended use of courseprivacy controls can generally be subverted in other languages if you try hard enough (#define private public may work in some +implementationstooalthough access controls can reduce accidental changesmuch of this is up to programmers in any languagewhenever source code may be changedairtight access control will always be bit of pipe dream decorator tradeoffs we could again achieve the same results without decoratorsby using manager functions or coding the name rebinding of decorators manuallythe decorator syntaxhowevermakes this consistent and bit more obvious in the code the chief potential downsides of this and any other wrapper-based approach are that attribute access incurs an extra calland instances of decorated classes are not really instances of the original decorated class--if you test their type with __class__ or isinstance(xc)for exampleyou'll find that they are instances of the wrapper class unless you plan to do introspection on objectstypesthoughthe type issue is probably irrelevantand the extra call may apply mostly to development timeas we'll see laterthere are ways to remove decorations automatically if desired open issues as isthis example works as planned under both python and for methods called explicitly by name as with most softwarethoughthere is always room for improvement most notablythis tool turns in mixed performance on operator overloading methods if they are used by client classes as codedthe proxy class is classic class when run under xbut new-style class when run by as suchthe code supports any client class in xbut in fails to example"privateand "publicattributes |
1,875 | operationsunless they are redefined in the proxy clients that do not use operator overloading are fully supportedbut others may require additional code in importantlythis is not new-style class issue hereit' python version issue--the same code runs differently and fails in only because the nature of the wrapped object' class is irrelevant to the proxywe are concerned only with the proxy' own codewhich works under but not we've met this issue few times already in this bookbut let' take quick look at its impact on the very realistic code we've written hereand explore workaround to it caveatimplicitly run operator overloading methods fail to delegate under like all delegation-based classes that use __getattr__this decorator works cross-version for normally named or explicitly called attributes only when run implicitly by built-in operationsoperator overloading methods like __str__ and __add__ work differently for new-style classes because this code is interpreted as new-style class in onlysuch operations fail to reach an embedded object that defines them when run under this python line as currently coded as we learned in the prior built-in operations look for operator overloading names in instances for classic classesbut not for new-style classes--for the latterthey skip the instance entirely and begin the search for such methods in classes (technicallyin the namespace dictionaries of all classes in the instance' treehencethe __x__ operator overloading methods implicitly run for built-in operations do not trigger either __getattr__ or __getattribute__ in new-style classesbecause such attribute fetches skip our oninstance class' __getattr__ altogetherthey cannot be validated or delegated our decorator' class is not coded as explicitly new-style (by deriving from object)so it will catch operator overloading methods if run under as default classic class in xthoughbecause all classes are new-style automatically (and by mandate)such methods will fail if they are implemented by the embedded object--because they are not caught by the proxythey won' be passed on the most direct workaround in is to redefine redundantly in oninstance all the operator overloading methods that can possibly be used in wrapped objects such extra methods can be added by handby tools that partly automate the task ( with class decorators or the metaclasses discussed in the next or by definition in reusable superclasses though tedious--and code-intensive enough to largely omit here--we'll explore approaches to satisfying this -only requirement in moment firstthoughto see the difference for yourselftry applying the decorator to class that uses operator overloading methods under xvalidations work as beforeand both the __str__ method used by printing and the __add__ method run for invoke the decorators |
1,876 | person object correctlyc:\codec:\python \python from access import private @private('age'class persondef __init__(self)self age def __str__(self)return 'personstr(self agedef __add__(selfyrs)self age +yrs person( age typeerrorprivate attribute fetchage print(xperson print(xperson name validations fail correctly __getattr__ =runs person __str__ __getattr__ =runs person __add__ __getattr__ =runs person __str__ when the same code is run under python xthoughthe implicitly invoked __str__ and __add__ skip the decorator' __getattr__ and look for definitions in or above the decorator class itselfprint winds up finding the default display inherited from the class type (technicallyfrom the implied object superclass in )and generates an error because no default is inheritedc:\codec:\python \python from access import private @private('age'class persondef __init__(self)self age def __str__(self)return 'personstr(self agedef __add__(selfyrs)self age +yrs person(name validations still work age but fails to delegate built-instypeerrorprivate attribute fetchage print(xondecorator oninstance object at etcx typeerrorunsupported operand type(sfor +'oninstanceand 'intprint(xondecorator oninstance object at etcstrangelythis occurs only for dispatch from built-in operationsexplicit direct calls to overload methods are routed to __getattr__though clients using operator overloading can' be expected to do the sameexample"privateand "publicattributes |
1,877 | _oninstance__wrapped age though calls by name work normally break privacy to view result in other wordsthis is matter of built-in operations versus explicit callsit has little to do with the actual names of the methods involved just for built-in operationspython skips step for ' new-style classes using the alternative __getattribute__ method won' help here--although it is defined to catch every attribute reference (not just undefined names)it is also not run by builtin operations python' property featurewhich we met in won' help directly here eitherrecall that properties are automatically run code associated with specific attributes defined when class is writtenand are not designed to handle arbitrary attributes in wrapped objects approaches to redefining operator overloading methods for as mentioned earlierthe most straightforward solution under is to redundantly redefine operator overloading names that may appear in embedded objects in delegation-based classes like our decorator this isn' ideal because it creates some code redundancyespecially compared to solutions howeverit isn' an impossibly major coding effortcan be automated to some extent with tools or superclassessuffices to make our decorator work in xand may allow operator overloading names to be declared private or public tooassuming overloading methods trigger the failif test internally inline definition for instancethe following is an inline redefinition approach--add method redefinitions to the proxy for every operator overloading method wrapped object may define itselfto catch and delegate we're adding just four operation interceptors to illustratebut others are similar (new code is in bold font here)def accesscontrol(failif)def ondecorator(aclass)class oninstancedef __init__(self*args**kargs)self __wrapped aclass(*args**kargsintercept and delegate built-in operations specifically def __str__(self)return str(self __wrappeddef __add__(selfother)return self __wrapped other or getattr( '__add__')(ydef __getitem__(selfindex)return self __wrapped[indexif needed def __call__(self*args**kargs)return self __wrapped(*args**kargsif needed plus any others needed intercept and delegate by-name attribute access generically def __getattr__(selfattr)def __setattr__(selfattrvalue) decorators |
1,878 | return ondecorator mix-in superclasses alternativelythese methods can be inserted by common superclass --given that there are dozens of such methodsan external class may be better suited to the taskespecially if it is general enough to be used in any such interface proxy class either of the following mix-in class schemes (among likely otherssuffice to catch and delegate built-ins operationsthe first catches built-ins and forcibly reroutes down to the subclass __get attr__ it requires that operator overloading names be public per the decorator' specificationsbut built-in operation calls will work the same as both explicit name calls and ' classic classes the second catches built-ins and reroutes to the wrapped object directly it requires access to and assumes proxy attribute named _wrapped giving access to the embedded object--which is less than ideal because it precludes wrapped objects from using the same name and creates subclass dependencybut better than using the mangled and class-specific _oninstance__wrappedand no worse than similarly named method like the inline approachboth of these mix-ins also require one method per built-in operation in general tools that proxy arbitrary objectsinterfaces notice how these classes catch operation calls rather than operation attribute fetchesand thus must perform the actual operation by delegating call or expressionclass builtinsmixindef __add__(selfother)return self __class__ __getattr__(self'__add__')(otherdef __str__(self)return self __class__ __getattr__(self'__str__')(def __getitem__(selfindex)return self __class__ __getattr__(self'__getitem__')(indexdef __call__(self*args**kargs)return self __class__ __getattr__(self'__call__')(*args**kargsplus any others needed def accesscontrol(failif)def ondecorator(aclass)class oninstance(builtinsmixin)rest unchanged def __getattr__(selfattr)def __setattr__(selfattrvalue)class builtinsmixindef __add__(selfother)return self _wrapped other def __str__(self)return str(self _wrappeddef __getitem__(selfindex)return self _wrapped[indexassume _wrapped bypass __getattr__ example"privateand "publicattributes |
1,879 | return self _wrapped(*args**kargsplus any others needed def accesscontrol(failif)def ondecorator(aclass)class oninstance(builtinsmixin)and use self _wrapped instead of self __wrapped def __getattr__(selfattr)def __setattr__(selfattrvalue)either one of these superclass mix-ins will be extraneous codebut must be implemented only onceand seem much more straightforward than the various metaclassor decorator-based tool approaches you'll find online that populate each proxy class with the requisite methods redundantly (see the class augmentation examples in for the principles behind such toolscoding variationsroutersdescriptorsautomation naturallyboth of the prior section' mixin superclasses might be improved with additional code changes we'll largely pass on hereexcept for two variations worth noting briefly firstcompare the following mutation of the first mix-in--which uses simpler coding structure but will incur an extra call per built-in operationmaking it slower (though perhaps not significantly so in proxy context)class builtinsmixindef reroute(selfattr*args**kargs)return self __class__ __getattr__(selfattr)(*args**kargsdef __add__(selfother)return self reroute('__add__'otherdef __str__(self)return self reroute('__str__'def __getitem__(selfindex)return self reroute('__getitem__'indexdef __call__(self*args**kargs)return self reroute('__call__'*args**kargsplus any others needed secondall the preceding built-in mix-in classes code each operator overloading method explicitlyand intercept the call issued for the operation with an alternative codingwe could instead generate methods from list of names mechanicallyand intercept only the attribute fetch preceding the call by creating class-level descriptors of the prior -as in the followingwhichlike the second mix-in alternativeassumes the proxied object is named _wrapped in the proxy instance itselfclass builtinsmixinclass proxydesc(object)def __init__(selfattrname)self attrname attrname def __get__(selfinstanceowner)return getattr(instance _wrappedself attrnamebuiltins ['add''str''getitem''call' decorators object for assume _wrapped plus any others |
1,880 | for attr in builtinsexec('__%s__ proxydesc("__%s__")(attrattr)this coding may be the most concisebut also the most implicit and complexand is fairly tightly coupled with its subclasses by the shared name the loop at the end of this class is equivalent to the followingrun in the mix-in class' local scope--it creates descriptors that respond to initial name lookups by fetching from the wrapped object in __get__rather than catching the later operation call itself__add__ proxydesc("__add__"__str__ proxydesc("__str__"etc with such operator overloading methods added--either inline or by mix-in inheritance --the prior private example client that overloaded and print with __str__ and __add__ works correctly under and xas do subclasses that overload indexing and calls if you care to experiment furthersee files access _builtinspy in the book examples package for complete codings of these optionswe'll also employ that third of the mix-in options in solution to an end-of-quiz should operator methods be validatedadding support for operator overloading methods is required of interface proxies in generalto delegate calls correctly in our specific privacy applicationthoughit also raises some additional design choices in particularprivacy of operator overloading methods differs per implementationbecause they invoke __getattr__the rerouter mix-ins require either that all __x__ names accessed be listed in public decorationsor that private be used instead when operator overloading is present in clients in classes that use overloading heavilypublic may be impractical because they bypass __getattr__ entirelyas coded here both the inline scheme and self _wrapped mix-ins do not have these constraintsbut they preclude builtin operations from being made privateand cause built-in operation dispatch to work asymmetrically from both explicit __x__ calls by-name and ' default classic classes python classic classes have the first bullet' constraintssimply because all __x__ names are routed through __getattr__ automatically operator overloading names and protocols differ between and xmaking truly cross-version decoration less than trivial ( public decorators may need to list names from both lineswe'll leave final policy here tbdbut some interface proxies might prefer to allow __x__ operator names to always pass unchecked when delegated in the general casethougha substantial amount of extra code is required to accommodate ' new-style classes as delegation proxies--in principleevery operator example"privateand "publicattributes |
1,881 | decorator this is why this extension is omitted in our codethere are potentially more than such methodsbecause all its classes are new-styledelegation-based code is more difficult--though not necessarily impossible--in python implementation alternatives__getattribute__ insertscall stack inspection although redundantly defining operator overloading methods in wrappers is probably the most straightforward workaround to python dilemma outlined in the prior sectionit' not necessarily the only one we don' have space to explore this issue much further hereso deeper investigation will have to be relegated to suggested exercise because one dead-end alternative illustrates class concepts wellthoughit merits brief mention one downside of the privacy example is that instance objects are not truly instances of the original class--they are instances of the wrapper instead in some programs that rely on type testingthis might matter to support such caseswe might try to achieve similar effects by inserting __getattribute__ and __setattr__ method into the original classto catch every attribute reference and assignment made on its instances these inserted methods would pass valid requests up to their superclass to avoid loopsusing the techniques we studied in the prior here is the potential change to our class decorator' codemethod insertionrest of access py code as before def accesscontrol(failif)def ondecorator(aclass)def getattributes(selfattr)trace('get:'attrif failif(attr)raise typeerror('private attribute fetchattrelsereturn object __getattribute__(selfattrdef setattributes(selfattrvalue)trace('set:'attrif failif(attr)raise typeerror('private attribute changeattrelsereturn object __setattr__(selfattrvalueaclass __getattribute__ getattributes aclass __setattr__ setattributes return aclass return ondecorator insert accessors return original class this alternative addresses the type-testing issue but suffers from others for one thingthis decorator can be used by new-style class clients onlybecause __getattribute__ is new-style-only tool (as is this __setattr__ coding)decorated classes in must use decorators |
1,882 | set of classes supported is even further limitedinserting methods will break clients that are already using __setattr__ or __getattribute__ of their own worsethis scheme does not address the built-in operation attributes issue described in the prior sectionbecause __getattribute__ is also not run in these contexts in our caseif person had __str__ it would be run by print operationsbut only because it was actually present in that class as beforethe __str__ attribute would not be routed to the inserted __getattribute__ method generically--printing would bypass this method altogether and call the class' __str__ directly although this is probably better than not supporting operator overloading methods in wrapped object at all (barring redefinitionat least)this scheme still cannot intercept and validate __x__ methodsmaking it impossible for any of them to be private whether operator overloading methods should be private is another matterbut this structure precludes the possibility much worsebecause this nonwrapper approach works by adding __getattribute__ and __setattr__ to the decorated classit also intercepts attribute accesses made by the class itself and validates them the same as accesses made from outside in other wordsthe class' own method won' be able to use its private names eitherthis is showstopper for the insertion approach in factinserting these methods this way is functionally equivalent to inheriting themand implies the same constraints as our original privacy code to know whether an attribute access originated inside or outside the classour methods might need to inspect frame objects on the python call stack this might ultimately yield solution--implementing private attributes as properties or descriptors that check the stack and validate for outside accesses onlyfor example--but it would slow access furtherand is far too dark magic for us to explore here (descriptors seem to make all things possibleeven when they shouldn' !while interestingand possibly relevant for some other use casesthis method insertion technique doesn' meet our goals we won' explore this option' coding pattern further here because we will study class augmentation techniques in the next in conjunction with metaclasses as we'll see theremetaclasses are not strictly required for changing classes this waybecause class decorators can often serve the same role python isn' about control now that 've gone to such great lengths to implement private and public attribute declarations for python codei must again remind you that it is not entirely pythonic to add access controls to your classes like this in factmost python programmers will probably find this example to be largely or totally irrelevantapart from serving as demonstration of decorators in action most large python programs get by successfully without any such controls at all example"privateand "publicattributes |
1,883 | do wish to regulate attribute access in order to eliminate coding mistakesor happen to be soon-to-be-ex- ++-or-java programmermost things are possible with python' operator overloading and introspection tools examplevalidating function arguments as final example of the utility of decoratorsthis section develops function decorator that automatically tests whether arguments passed to function or method are within valid numeric range it' designed to be used during either development or productionand it can be used as template for similar tasks ( argument type testingif you mustbecause this size limits have been broachedthis example' code is largely self-study materialwith limited narrativeas usualbrowse the code for more details the goal in the object-oriented tutorial of we wrote class that gave pay raise to objects representing people based upon passed-in percentageclass persondef giveraise(selfpercent)self pay int(self pay ( percent)therewe noted that if we wanted the code to be robust it would be good idea to check the percentage to make sure it' not too large or too small we could implement such check with either if or assert statements in the method itselfusing inline testsclass persondef giveraise(selfpercent)validate with inline code if percent raise typeerror'percent invalidself pay int(self pay ( percent)class personvalidate with asserts def giveraise(selfpercent)assert percent > and percent < 'percent invalidself pay int(self pay ( percent)howeverthis approach clutters up the method with inline tests that will probably be useful only during development for more complex casesthis can become tedious (imagine trying to inline the code needed to implement the attribute privacy provided by the last section' decoratorperhaps worseif the validation logic ever needs to changethere may be arbitrarily many inline copies to find and update more useful and interesting alternative would be to develop general tool that can perform range tests for us automaticallyfor the arguments of any function or method decorators |
1,884 | convenientclass person@rangetest(percent=( )use decorator to validate def giveraise(selfpercent)self pay int(self pay ( percent)isolating validation logic in decorator simplifies both clients and future maintenance notice that our goal here is different than the attribute validations coded in the prior final example herewe mean to validate the values of function arguments when passedrather than attribute values when set python' decorator and introspection tools allow us to code this new task just as easily basic range-testing decorator for positional arguments let' start with basic range test implementation to keep things simplewe'll begin by coding decorator that works only for positional arguments and assumes they always appear at the same position in every callthey cannot be passed by keyword nameand we don' support additional **args keywords in calls because this can invalidate the positions declared in the decorator code the following in file called rangetest pydef rangetest(*argchecks)validate positional arg ranges def ondecorator(func)if not __debug__true if "python - main py args return func no-opcall original directly elseelse wrapper while debugging def oncall(*args)for (ixlowhighin argchecksif args[ixhigherrmsg 'argument % not in % % (ixlowhighraise typeerror(errmsgreturn func(*argsreturn oncall return ondecorator as isthis code is mostly rehash of the coding patterns we explored earlierwe use decorator argumentsnested scopes for state retentionand so on we also use nested def statements to ensure that this works for both simple functions and methodsas we learned earlier when used for class' methodoncall receives the subject class' instance in the first item in *args and passes this along to self in the original method functionargument numbers in range tests start at in this casenot new herenotice this code' use of the __debug__ built-in variable--python sets this to trueunless it' being run with the - optimize command-line flag ( python - main pywhen __debug__ is falsethe decorator returns the origin function unchangedto avoid extra later calls and their associated performance penalty in other wordsthe decorator automatically removes its augmentation logic when - is usedwithout requiring you to physically remove the decoration lines in your code examplevalidating function arguments |
1,885 | file rangetest _test py from __future__ import print_function from rangetest import rangetest print(__debug__false if "python - main py@rangetest(( )persinfo rangetest)(persinfodef persinfo(nameage)age must be in print('% is % years old(nameage)@rangetest([ ][ ][ ]def birthday(mdy)print('birthday { }/{ }/{ }format(mdy)class persondef __init__(selfnamejobpay)self job job self pay pay @rangetest([ ]giveraise rangetest)(giveraisedef giveraise(selfpercent)arg is the self instance here self pay int(self pay ( percent)comment lines raise typeerror unless "python -oused on shell command line persinfo('bob smith' #persinfo('bob smith' really runs oncallwith state or person if - cmd line argument birthday( #birthday( sue person('sue jones''dev' sue giveraise print(sue pay#sue giveraise( #print(sue payreally runs oncall(self or giveraise(self if - when runvalid calls in this code produce the following output (all the code in this section works the same under python and xbecause function decorators are supported in bothwe're not using attribute delegationand we use version-neutral exception construction and printing techniques) :\codepython rangetest _test py true bob smith is years old birthday uncommenting any of the invalid calls causes typeerror to be raised by the decorator here' the result when the last two lines are allowed to run (as usuali've omitted some of the error message text here to save space) :\codepython rangetest _test py true decorators |
1,886 | birthday typeerrorargument not in running python with its - flag at system command line will disable range testingbut also avoid the performance overhead of the wrapping layer--we wind up calling the original undecorated function directly assuming this is debugging tool onlyyou can use this flag to optimize your program for production usec:\codepython - rangetest _test py false bob smith is years old birthday generalizing for keywords and defaultstoo the prior version illustrates the basics we need to employbut it' fairly limited--it supports validating arguments passed by position onlyand it does not validate keyword arguments (in factit assumes that no keywords are passed in way that makes argument position numbers incorrectadditionallyit does nothing about arguments with defaults that may be omitted in given call that' fine if all your arguments are passed by position and never defaultedbut less than ideal in general tool python supports much more flexible argument-passing modeswhich we're not yet addressing the mutation of our example shown next does better by matching the wrapped function' expected arguments against the actual arguments passed in callit supports range validations for arguments passed by either position or keyword nameand it skips testing for default arguments omitted in the call in shortarguments to be validated are specified by keyword arguments to the decoratorwhich later steps through both the *pargs positionals tuple and the **kargs keywords dictionary to validate ""file rangetest pyfunction decorator that performs range-test validation for arguments passed to any function or method arguments are specified by keyword to the decorator in the actual callarguments may be passed by position or keywordand defaults may be omitted see rangetest_test py for example use cases ""trace true def rangetest(**argchecks)validate ranges for both+defaults def ondecorator(func)oncall remembers func and argchecks if not __debug__true if "python - main py args return func wrap if debuggingelse use original elsecode func __code__ allargs code co_varnames[:code co_argcountfuncname func __name__ examplevalidating function arguments |
1,887 | all pargs match first expected args by position the rest must be in kargs or be omitted defaults expected list(allargspositionals expected[:len(pargs)for (argname(lowhigh)in argchecks items()for all args to be checked if argname in kargswas passed by name if kargs[argnamehigherrmsg '{ argument "{ }not in { { }errmsg errmsg format(funcnameargnamelowhighraise typeerror(errmsgelif argname in positionalswas passed by position position positionals index(argnameif pargs[positionhigherrmsg '{ argument "{ }not in { { }errmsg errmsg format(funcnameargnamelowhighraise typeerror(errmsgelseassume not passeddefault if traceprint('argument "{ }defaultedformat(argname)return func(*pargs**kargsreturn oncall return ondecorator okrun original call the following test script shows how the decorator is used--arguments to be validated are given by keyword decorator argumentsand at actual calls we can pass by name or position and omit arguments with defaults even if they are to be validated otherwise""file rangetest_test py ( xcomment lines raise typeerror unless "python -oused on shell command line ""from __future__ import print_function from rangetest import rangetest test functionspositional and keyword @rangetest(age=( )persinfo rangetest)(persinfodef persinfo(nameage)print('% is % years old(nameage)@rangetest( =( ) =( ) =( )def birthday(mdy)print('birthday { }/{ }/{ }format(mdy)persinfo('bob' persinfo(age= name='bob' decorators |
1,888 | #persinfo('bob' #persinfo(age= name='bob'#birthday( = = test methodspositional and keyword class persondef __init__(selfnamejobpay)self job job self pay pay giveraise rangetest)(giveraise@rangetest(percent=( )percent passed by name or position def giveraise(selfpercent)self pay int(self pay ( percent)bob person('bob smith''dev' sue person('sue jones''dev' bob giveraise sue giveraise(percent print(bob paysue pay#bob giveraise( #bob giveraise(percent= test omitted defaultsskipped @rangetest( =( ) =( ) =( ) =( )def omitargs(ab= = = )print(abcdomitargs( omitargs( omitargs( = omitargs( = omitargs( = = omitargs( = = omitargs( = = = #omitargs( #omitargs( #omitargs( = #omitargs( = #omitargs( = = #omitargs( = = #omitargs( = = = bad bad bad bad bad bad bad when this script is runout-of-range arguments raise an exception as beforebut arguments may be passed by either name or positionand omitted defaults are not validated this code runs on both and trace its output and test this further on your own to experimentit works as beforebut its scope has been broadenedc:\codepython rangetest_test py bob is years old bob is years old birthday examplevalidating function arguments |
1,889 | argument "ddefaulted argument "cdefaulted argument "bdefaulted argument "cdefaulted argument "bdefaulted argument "cdefaulted argument "bdefaulted on validation errorswe get an exception as before when one of the method test lines is uncommentedunless the - command-line argument is passed to python to disable the decorator' logictypeerrorgiveraise argument "percentnot in implementation details this decorator' code relies on both introspection apis and subtle constraints of argument passing to be fully general we could in principle try to mimic python' argument matching logic in its entirety to see which names have been passed in which modesbut that' far too much complexity for our tool it would be better if we could somehow match arguments passed by name against the set of all expected argumentsnamesin order to determine which position arguments actually appear in during given call function introspection it turns out that the introspection api available on function objects and their associated code objects has exactly the tool we need this api was briefly introduced in but we'll actually put it to use here the set of expected argument names is simply the first variable names attached to function' code objectin python (and for compatibilitydef func(abce=truef=none) code func __code__ code co_nlocals code co_varnames (' '' '' '' '' '' '' 'code co_varnames[:code co_argcount(' '' '' '' '' ' decorators argsthree requiredtwo defaults plus two more local variables code object of function object all local variable names <=first locals are expected args |
1,890 | many arguments to be matched against the expected arguments so obtained from the function' introspection apidef catcher(*pargs**kargs)print('% % (pargskargs)catcher( ( ){catcher( = = = ( ){' ' ' ' ' ' arguments at calls the function object' api is available in older pythonsbut the func __code__ attribute is named func func_code in and earlierthe newer __code__ attribute is also redundantly available in and later for portability run dir call on function and code objects for more details code like the following would support and earlierthough the sys version_info result itself is similarly nonportable--it' named tuple in recent pythonsbut we can use offsets on newer and older pythons alikeimport sys for backward compatibility tuple(sys version_info[ is major release number ( 'final' code func __code__ if sys version_info[ = else func func_code argument assumptions given the decorated function' set of expected argument namesthe solution relies upon two constraints on argument passing order imposed by python (these still hold true in both and current releases)at the callall positional arguments appear before all keyword arguments in the defall nondefault arguments appear before all default arguments that isa nonkeyword argument cannot generally follow keyword argument at calland nondefault argument cannot follow default argument at definition all "name=valuesyntax must appear after any simple "namein both places as we've also learnedpython matches argument values passed by position to argument names in function headers from left to rightsuch that these values always match the leftmost names in headers keywords match by name insteadand given argument can receive only one value to simplify our workwe can also make the assumption that call is valid in general --that isthat all arguments either will receive values (by name or position)or will be omitted intentionally to pick up defaults this assumption won' necessarily holdbecause the function has not yet actually been called when the wrapper logic tests validity --the call may still fail later when invoked by the wrapper layerdue to incorrect argument passing as long as that doesn' cause the wrapper to fail any more badlythoughwe can finesse the validity of the call this helpsbecause validating calls before they are actually made would require us to emulate python' argument-matching algorithm in full--againtoo complex procedure for our tool examplevalidating function arguments |
1,891 | nowgiven these constraints and assumptionswe can allow for both keywords and omitted default arguments in the call with this algorithm when call is interceptedwe can make the following assumptions and deductions let be the number of passed positional argumentsobtained from the length of the *pargs tuple all positional arguments in *pargs must match the first expected arguments obtained from the function' code object this is true per python' call ordering rulesoutlined earliersince all positionals precede all keywords in call to obtain the names of arguments actually passed by positionwe can slice the list of all expected arguments up to the length of the *pargs passed positionals tuple any arguments after the first expected arguments either were passed by keyword or were defaulted by omission at the call for each argument name to be validated by the decoratora if the name is in **kargsit was passed by name--indexing **kargs gives its passed value if the name is in the first expected argumentsit was passed by position-its relative position in the expected list gives its relative position in *pargs otherwisewe can assume it was omitted in the call and defaultedand need not be checked in other wordswe can skip tests for arguments that were omitted in call by assuming that the first actually passed positional arguments in *pargs must match the first argument names in the list of all expected argumentsand that any others must either have been passed by keyword and thus be in **kargsor have been defaulted under this schemethe decorator will simply skip any argument to be checked that was omitted between the rightmost positional argument and the leftmost keyword argumentbetween keyword argumentsor after the rightmost positional in general trace through the decorator and its test script to see how this is realized in code open issues although our range-testing tool works as plannedthree caveats remain--it doesn' detect invalid callsdoesn' handle some arbitrary-argument signaturesand doesn' fully support nesting improvements may require extension or altogether different approaches here' quick rundown of the issues invalid calls firstas mentioned earliercalls to the original function that are not valid still fail in our final decorator the following both trigger exceptionsfor example decorators |
1,892 | omitargs( = = = these only failthoughwhere we try to invoke the original functionat the end of the wrapper while we could try to imitate python' argument matching to avoid thisthere' not much reason to do so--since the call would fail at this point anyhowwe might as well let python' own argument-matching logic detect the problem for us arbitrary arguments secondalthough our final version handles positional argumentskeyword argumentsand omitted defaultsit still doesn' do anything explicit about *pargs and **kargs starred-argument names that may be used in decorated function that accepts arbitrarily many arguments itself we probably don' need to care for our purposesthoughif an extra keyword argument is passedits name will show up in **kargs and can be tested normally if mentioned to the decorator if an extra keyword argument is not passedits name won' be in either **kargs or the sliced expected positionals listand it will thus not be checked--it is treated as though it were defaultedeven though it is really an optional extra argument if an extra positional argument is passedthere' no way to reference it in the decorator anyhow--its name won' be in either **kargs or the sliced expected arguments listso it will simply be skipped because such arguments are not listed in the function' definitionthere' no way to map name given to the decorator back to an expected relative position in other wordsas it is the code supports testing arbitrary keyword arguments by namebut not arbitrary positionals that are unnamed and hence have no set position in the function' argument signature in terms of the function object' apihere' the effect of these tools in decorated functionsdef func(*kargs**pargs)pass code func __code__ code co_nlocalscode co_varnames ( ('kargs''pargs')code co_argcountcode co_varnames[:code co_argcount( ()def func(ab*kargs**pargs)pass code func __code__ code co_argcountcode co_varnames[:code co_argcount( (' '' ')because starred-argument names show up as locals but not as expected argumentsthey won' be factor in our matching algorithm--names preceding them in function headers can be validated as usualbut not any extra positional arguments passed in principlewe could extend the decorator' interface to support *pargs in the decorated functiontoofor the rare cases where this might be useful ( special argument examplevalidating function arguments |
1,893 | of the expected arguments list)but we'll pass on such an extension here decorator nesting finallyand perhaps most subtlythis code' approach does not fully support use of decorator nesting to combine steps because it analyzes arguments using names in function definitionsand the names of the call proxy function returned by nested decoration won' correspond to argument names in either the original function or decorator argumentsit does not fully support use in nested mode technicallywhen nestedonly the most deeply nested appearance' validations are run in fullall other nesting levels run tests on arguments passed by keyword only trace the code to see whybecause the oncall proxy' call signature expects no named positional argumentsany to-be-validated arguments passed to it by position are treated as if they were omitted and hence defaultedand are thus skipped this may be inherent in this tool' approach--proxies change the argument name signatures at their levelsmaking it impossible to directly map names in decorator arguments to positions in passed argument sequences when proxies are presentargument names ultimately apply to keywords onlyby contrastthe first-cut solution' argument positions may support proxies betterbut do not fully support keywords in lieu of this nesting capabilitywe'll generalize this decorator to support multiple types of validations in single decoration in an end-of-quiz solutionwhich also gives examples of the nesting limitation in action since we've already neared the space allocation for this examplethoughif you care about these or any other further improvementsyou've officially crossed over into the realm of suggested exercises decorator arguments versus function annotations interestinglythe function annotation feature introduced in python ( and latercould provide an alternative to the decorator arguments used by our example to specify range tests as we learned in annotations allow us to associate expressions with arguments and return valuesby coding them in the def header line itselfpython collects annotations in dictionary and attaches it to the annotated function we could use this in our example to code range limits in the header lineinstead of in decorator arguments we would still need function decorator to wrap the function in order to intercept later callsbut we would essentially trade decorator argument syntax@rangetest( =( ) =( )def func(abc)print( cfor annotation syntax like this decorators func rangetest)(func |
1,894 | def func( :( )bc:( ))print( cthat isthe range constraints would be moved into the function itselfinstead of being coded externally the following script illustrates the structure of the resulting decorators under both schemesin incomplete skeleton code for brevity the decorator arguments code pattern is that of our complete solution shown earlierthe annotation alternative requires one less level of nestingbecause it doesn' need to retain decorator arguments as stateusing decorator arguments ( xdef rangetest(**argchecks)def ondecorator(func)def oncall(*pargs**kargs)print(argchecksfor check in argcheckspass return func(*pargs**kargsreturn oncall return ondecorator add validation code here @rangetest( =( ) =( )def func(abc)print( cfunc rangetest)(funcfunc( = runs oncallargchecks in scope using function annotations ( onlydef rangetest(func)def oncall(*pargs**kargs)argchecks func __annotations__ print(argchecksfor check in argcheckspass return func(*pargs**kargsreturn oncall add validation code here @rangetest def func( :( )bc:( ))print( cfunc rangetest(funcfunc( = runs oncallannotations on func when runboth schemes have access to the same validation test informationbut in different forms--the decorator argument version' information is retained in an argument in an enclosing scopeand the annotation version' information is retained in an attribute of the function itself in onlydue to the use of function annotationsc:\codepy - decoargs-vs-annotation py {' '( )' '( ) examplevalidating function arguments |
1,895 | 'll leave fleshing out the rest of the annotation-based version as suggested exerciseits code would be identical to that of our complete solution shown earlierbecause range-test information is simply on the function instead of in an enclosing scope reallyall this buys us is different user interface for our tool--it will still need to match argument names against expected argument names to obtain relative positions as before in factusing annotation instead of decorator arguments in this example actually limits its utility for one thingannotation only works under python xso is no longer supportedfunction decorators with argumentson the other handwork in both versions more importantlyby moving the validation specifications into the def headerwe essentially commit the function to single role--since annotation allows us to code only one expression per argumentit can have only one purpose for instancewe cannot use range-test annotations for any other role by contrastbecause decorator arguments are coded outside the function itselfthey are both easier to remove and more general--the code of the function itself does not imply single decoration purpose cruciallyby nesting decorators with argumentswe can apply multiple augmentation steps to the same functionannotation directly supports only one with decorator argumentsthe function itself also retains simplernormal appearance stillif you have single purpose in mindand you can commit to supporting onlythe choice between annotation and decorator arguments is largely stylistic and subjective as is so often true in lifeone person' decoration or annotation may well be another' syntactic clutterother applicationstype testing (if you insist!the coding pattern we've arrived at for processing arguments in decorators could be applied in other contexts checking argument data types at development timefor exampleis straightforward extensiondef typetest(**argchecks)def ondecorator(func)def oncall(*pargs**kargs)positionals list(allargs)[:len(pargs)for (argnametypein argchecks items()if argname in kargsif not isinstance(kargs[argname]type)raise typeerror(errmsgelif argname in positionalsposition positionals index(argname decorators |
1,896 | raise typeerror(errmsgelseassume not passeddefault return func(*pargs**kargsreturn oncall return ondecorator @typetest( =intc=floatdef func(abcd)func typetest)(funcfunc( func('spam' ok triggers exception correctly using function annotations instead of decorator arguments for such decoratoras described in the prior sectionwould make this look even more like type declarations in other languages@typetest def func(aintbcfloatd)func typetest(funcgaspbut we're getting dangerously close to triggering "flag on the playhere as you should have learned in this bookthis particular role is generally bad idea in working codeandmuch like private declarationsis not at all pythonic (and is often symptom of an ex- +programmer' first attempts to use pythontype testing restricts your function to work on specific types onlyinstead of allowing it to operate on any types with compatible interfaces in effectit limits your code and breaks its flexibility on the other handevery rule has exceptionstype checking may come in handy in isolated cases while debugging and when interfacing with code written in more restrictive languagessuch as +stillthis general pattern of argument processing might also be applicable in variety of less controversial roles we might even generalize further by passing in test functionmuch as we did to add public decorations earliera single copy of this sort of code would then suffice for both range and type testingand perhaps other similar goals in factwe will generalize this way in the end-of-quiz coming upso we'll leave this extension as cliffhanger here summary in this we explored decorators--both the function and class varieties as we learneddecorators are way to insert code to be run automatically when function or class is defined when decorator is usedpython rebinds function or class name to the callable object it returns this hook allows us to manage functions and classes themselvesor later calls to them--by adding layer of wrapper logic to catch later callswe can augment both function calls and instance interfaces as we also sawsummary |
1,897 | as we also learnedclass decorators can be used to manage classes themselvesrather than just their instances because this functionality overlaps with metaclasses--the topic of the next and final technical you'll have to read ahead for the conclusion to this storyand that of this book at large firstthoughlet' work through the following quiz because this was mostly focused on its examplesits quiz will ask you to modify some of its code in order to review you can find the original versionscode in the book' examples package (see the preface for access pointersif you're pressed for timestudy the modifications listed in the answers instead--programming is as much about reading code as writing it test your knowledgequiz method decoratorsas mentioned in one of this notesthe timerdeco py module' timer function decorator with decorator arguments that we wrote in the section "adding decorator argumentson page can be applied only to simple functionsbecause it uses nested class with __call__ operator overloading method to catch calls this structure does not work for class' methods because the decorator instance is passed to selfnot the subject class instance rewrite this decorator so that it can be applied to both simple functions and methods in classesand test it on both functions and methods (hintsee the section "class blunders idecorating methodson page for pointers note that you will probably need to use function object attributes to keep track of total timesince you won' have nested class for state retention and can' access nonlocals from outside the decorator code as an added bonusthis makes your decorator usable on both python and class decoratorsthe public/private class decorators we wrote in module access py in this first case study example will add performance costs to every attribute fetch in decorated class although we could simply delete the decoration line to gain speedwe could also augment the decorator itself to check the __debug__ switch and perform no wrapping at all when the - python flag is passed on the command line--just as we did for the argument range-test decorators that waywe can speed our program without changing its sourcevia command-line arguments (python - main py while we're at itwe could also use one of the mix-in superclass techniques we studied to catch few built-in operations in python too code and test these two extensions generalized argument validationsthe function and method decorator we wrote in rangetest py checks that passed arguments are in valid rangebut we also saw that the same pattern could apply to similar goals such as argument type testingand possibly more generalize the range tester so that its single code base can be used for multiple argument validations passed-in functions may be the simplest decorators |
1,898 | subclasses that provide expected methods can often provide similar generalization routes as well test your knowledgeanswers here' one way to code the first question' solutionand its output (though some methods may run too fast to register reported timethe trick lies in replacing nested classes with nested functionsso the self argument is not the decorator' instanceand assigning the total time to the decorator function itself so it can be fetched later through the original rebound name (see the section "state information retention optionsof this for details--functions support arbitrary attribute attachmentand the function name is an enclosing scope reference in this contextif you wish to expand this furtherit might be useful to also record the best (minimumcall time in addition to the total timeas we did in ' timer examples ""file timerdeco py ( xcall timer decorator for both functions and methods ""import time def timer(label=''trace=true)on decorator argsretain args def ondecorator(func)on @retain decorated func def oncall(*args**kargs)on callscall original start time clock(state is scopes func attr result func(*args**kargselapsed time clock(start oncall alltime +elapsed if traceformat '% % fvalues (labelfunc __name__elapsedoncall alltimeprint(format valuesreturn result oncall alltime return oncall return ondecorator 've coded tests in separate file here to allow the decorator to be easily reused""file timerdeco-test py ""from __future__ import print_function from timerdeco import timer import sys force list if sys version_info[ = else (lambda xxprint(''test on functions test your knowledgeanswers |
1,899 | def listcomp( )return [ for in range( )like listcomp timer)(listcomplistcomptriggers oncall @timer('[mmm]==>'def mapcall( )return force(map((lambda xx )range( ))list(for views for func in (listcompmapcall)result func( time for this callall callsreturn value func( print(resultprint('alltime % \nfunc alltimetotal time for all calls print(''test on methods class persondef __init__(selfnamepay)self name name self pay pay @timer(def giveraise(selfpercent)self pay *( percentgiveraise timer()(giveraisetracer remembers giveraise @timer(label='**'def lastname(self)return self name split()[- lastname timer)(lastnamealltime per classnot instance bob person('bob smith' sue person('sue jones' bob giveraise sue giveraise runs oncall(sue print(int(bob pay)int(sue pay)print(bob lastname()sue lastname()runs oncall(bob)remembers lastname print(' (person giveraise alltimeperson lastname alltime)if all goes according to planyou'll see the following output in both python and xalbeit with timing results that will vary per python and machinec:\codepy - timerdeco-test py [ccc]==>listcomp [ccc]==>listcomp [ alltime [mmm]==>mapcall [mmm]==>mapcall [ alltime giveraise decorators |
Subsets and Splits