id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
1,900 | **lastname **lastname smith jones the following three files satisfy the second question the first gives the decorator --it' been augmented to return the original class in optimized mode (- )so attribute accesses don' incur speed hit mostlyit just adds the debug mode test statements and indents the class further to the right""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 in any fashion private declares attribute names that cannot be fetched or assigned outside the decorated classand public declares all the names that can caveatsin catches built-ins coded in builtinmixins only (expand me)as codedpublic may be less useful than private for operator overloading ""from access_builtins import builtinsmixin partial settraceme false def trace(*args)if tracemeprint('[join(map(strargs)']'def accesscontrol(failif)def ondecorator(aclass)if not __debug__return aclass elseclass oninstance(builtinsmixin)def __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 test your knowledgeanswers |
1,901 | def private(*attributes)return accesscontrol(failif=(lambda attrattr in attributes)def public(*attributes)return accesscontrol(failif=(lambda attrattr not in attributes) 've also used one of our mix-in techniques to add some operator overloading method redefinitions to the wrapper classso that in it correctly delegates builtin operations to subject classes that use these methods as codedthe proxy is default classic class in that routes these through __getattr__ alreadybut in is new-style class that does not the mix-in used here requires listing such methods in public decoratorssee earlier for alternatives that do not (but that also do not allow built-ins to be made private)and expand this class as needed""file access_builtins py (from access _builtins pyroute some built-in operations back to proxy class __getattr__so they work the same in as direct by-name calls and ' default classic classes expand me as needed to include other __x__ names used by proxied objects ""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 used by wrapped objects in only here too split the self-test code off to separate fileso the decorator could be imported elsewhere without triggering the testsand without requiring __name__ test and indenting""fileaccess-test py test codeseparate file to allow decorator reuse ""import sys from access import privatepublic print(''test names are public if not private @private('age'class person decorators person private('age')(personperson oninstance with state |
1,902 | self name name self age age inside accesses run normally def __add__(selfn)self age + built-ins caught by mix-in in def __str__(self)return '% % (self nameself agex person('bob' print( namex name 'sueprint( namex print(xtryt age exceptprint(sys exc_info()[ ]tryx age exceptprint(sys exc_info()[ ]outside accesses validated fails unless "python -oditto print(''test names are private if not public operators must be non-private or public in builtinmixin used @public('name''__add__''__str__''__coerce__'class persondef __init__(selfnameage)self name name self age age def __add__(selfn)self age + built-ins caught by mix-in in def __str__(self)return '% % (self nameself agex person('bob' print( namex name 'sueprint( namex print(xx is an oninstance oninstance embeds person tryt age exceptprint(sys exc_info()[ ]tryx age exceptprint(sys exc_info()[ ]fails unless "python -oditto finallyif all works as expectedthis test' output is as follows in both python and --the same code applied to the same class decorated with private and then with publicc:\codepy - access-test py bob sue sue test your knowledgeanswers |
1,903 | private attribute changeage bob sue sue private attribute fetchage private attribute changeage :\codepy - - access-test py suppresses the four access error messages here' generalized argument validator for you to study on your own it uses passed-in validation functionto which it passes the test' criteria value coded for the argument in the decorator this handles rangestype testsvalue testersand almost anything else you can dream up in an expressive language like python 've also refactored the code bit to remove some redundancyand automated test failure processing see this module' self-test for usage examples and expected output per this example' caveats described earlierthis decorator doesn' fully work in nested mode as is--only the most deeply nested validation is run for positional arguments--but its arbitrary valuetest can be used to combine differing types of tests in single decoration (though the amount of code needed in this mode may negate much of its benefits over simple assert!""file argtest py( xfunction decorator that performs arbitrary passed-in validations for arguments passed to any function method range and type tests are two example usesvaluetest handles more arbitrary tests on an argument' value arguments are specified by keyword to the decorator in the actual callarguments may be passed by position or keywordand defaults may be omitted see self-test code below for example use cases caveatsdoesn' fully support nesting because call proxy args differdoesn' validate extra args passed to decoratee' *argsand may be no easier than an assert except for canned use cases ""trace false def rangetest(**argchecks)return argtest(argcheckslambda argvalsarg vals[ ]def typetest(**argchecks)return argtest(argcheckslambda argtypenot isinstance(argtype)def valuetest(**argchecks)return argtest(argcheckslambda argtesternot tester(arg)def argtest(argchecksfailif)def ondecorator(func)if not __debug__ decorators validate args per failif criteria oncall retains funcargchecksfailif no-op if "python - main py args |
1,904 | return func elsecode func __code__ expected list(code co_varnames[:code co_argcount]def onerror(argnamecriteria)errfmt '% argument "%snot %sraise typeerror(errfmt (func __name__argnamecriteria)def oncall(*pargs**kargs)positionals expected[:len(pargs)for (argnamecriteriain argchecks items()if argname in kargsif failif(kargs[argname]criteria)onerror(argnamecriteriafor all to test passed by name elif argname in positionalspassed by posit position positionals index(argnameif failif(pargs[position]criteria)onerror(argnamecriteriaelsenot passed-dflt if traceprint('argument "%sdefaultedargnamereturn func(*pargs**kargsokrun original call return oncall return ondecorator if __name__ ='__main__'import sys def fails(test)tryresult test(exceptprint('[% ]sys exc_info()[ ]elseprint('?% ?resultprint(''canned use casesrangestypes @rangetest( =( ) =( ) =( )def date(mdy)print('date % /% /% (mdy)date( fails(lambdadate( )@typetest( =intc=floatdef sum(abcd)print( dsum( sum( = = = fails(lambdasum('spam' )fails(lambdasum( = = = )print(''arbitrary/mixed tests test your knowledgeanswers |
1,905 | def msg(word ='mighty'word ='larch'label='the')print('% % % (labelword word )msg(word and word defaulted msg('majestic''moose'fails(lambdamsg('giant''redwood')fails(lambdamsg('great'word ='elm')print(''manual type and range tests @valuetest( =lambda xisinstance(xint) =lambda xx and def manual(ab)print( bmanual( fails(lambdamanual( )fails(lambdamanual( )print(''nestingruns bothby nesting proxies on original open issueouter levels do not validate positionals due to call proxy function' differing argument signaturewhen trace=truein all but the last of these "xis classified as defaulted due to the proxy' signature @rangetest( =( )@typetest( =strdef nester(xyz)return('% -% -% (xyz)only innermost validates positional args print(nester( 'spam')fails(lambdanester( )fails(lambdanester( = )fails(lambdanester( 'spam')fails(lambdanester( = = ='spam')original function runs properly nested typetest is runpositional nested typetest is runkeyword <==outer rangetest not runposit outer rangetest is runkeyword this module' self-test output in both and follows (some object displays vary slightly)as usualcorrelate with the source for more insights :\codepy - argtest py date [date argument "ynot ( ) [sum argument "anot [sum argument "cnot the mighty larch the majestic moose [msg argument "word not [msg argument "word not at > decorators |
1,906 | [manual argument "anot at >[manual argument "bnot at > - -spam [nester argument "znot [nester argument "znot ? - -spam[oncall argument "xnot ( )finallyas we've learnedthis decorator' coding structure works for both functions and methodsfile argtest_testmeth py from argtest import rangetesttypetest class @rangetest( =( )def meth (selfa)return @typetest( =intdef meth (selfa)return from argtest_testmeth import ( meth ( meth ( typeerrormeth argument "anot ( meth ( meth ( typeerrormeth argument "anot test your knowledgeanswers |
1,907 | metaclasses in the prior we explored decorators and studied various examples of their use in this final technical of the bookwe're going to continue our tool-builders focus and investigate another advanced topicmetaclasses in sensemetaclasses simply extend the code-insertion model of decorators as we learned in the prior function and class decorators allow us to intercept and augment function calls and class instance creation calls in similar spiritmetaclasses allow us to intercept and augment class creation--they provide an api for inserting extra logic to be run at the conclusion of class statementalbeit in different ways than decorators accordinglythey provide general protocol for managing class objects in program like all the subjects dealt with in this part of the bookthis is an advanced topic that can be investigated on an as-needed basis in practicemetaclasses allow us to gain high level of control over how set of classes works this is powerful conceptand metaclasses are not intended for most application programmers norfranklyis this topic for the faint of heart--some parts of this may warrant extra focus (and others might even owe attribution to dr seuss!on the other handmetaclasses open the door to variety of coding patterns that may be difficult or impossible to achieve otherwiseand they are especially of interest to programmers seeking to write flexible apis or programming tools for others to use even if you don' fall into that categorythoughmetaclasses can teach you much about python' class model in general (as we'll seethey even impact inheritance)and are prerequisite to understanding code that employs them like other advanced toolsmetaclasses have begun appearing in python programs more often than their creators may have intended as in the prior part of our goal here is also to show more realistic code examples than we did earlier in this book although metaclasses are core language topic and not themselves an application domainpart of this agenda is to spark your interest in exploring larger application-programming examples after you finish this book |
1,908 | threads concerning python itself that we've met often along the way and will finalize in the conclusion that follows where you go after this book is up to youof coursebut in an open source project it' important to keep the big picture in mind while hacking the small details to metaclass or not to metaclass metaclasses are perhaps the most advanced topic in this bookif not the python language as whole to borrow quote from the comp lang python newsgroup by veteran python core developer tim peters (who is also the author of the famous "import thispython motto)[metaclassesare deeper magic than of users should ever worry about if you wonder whether you need themyou don' (the people who actually need them know with certainty that they need themand don' need an explanation about whyin other wordsmetaclasses are primarily intended for subset of programmers building apis and tools for others to use in many (if not mostcasesthey are probably not the best choice in applications work this is especially true if you're developing code that other people will use in the future coding something "because it seems coolis not generally reasonable justificationunless you are experimenting or learning stillmetaclasses have wide variety of potential rolesand it' important to know when they can be useful for examplethey can be used to enhance classes with features like tracingobject persistenceexception loggingand more they can also be used to construct portions of class at runtime based upon configuration filesapply function decorators to every method of class genericallyverify conformance to expected interfacesand so on in their more grandiose incarnationsmetaclasses can even be used to implement alternative coding patterns such as aspect-oriented programmingobject/relational mappers (ormsfor databasesand more although there are often alternative ways to achieve such results--as we'll seethe roles of class decorators and metaclasses often intersect--metaclasses provide formal model tailored to those tasks we don' have space to explore all such applications first-hand in this of coursebut you should feel free to search the web for additional use cases after studying the basics here probably the reason for studying metaclasses most relevant to this book is that this topic can help demystify python' class mechanics in general for instancewe'll see that they are an intrinsic part of the language' new-style inheritance model finally formalized in full here although you may or may not code or reuse them in your worka cursory understanding of metaclasses can impart deeper understanding of python at large metaclasses |
1,909 | most of this book has focused on straightforward application-coding techniques--the modulesfunctionsand classes that most programmers spend their time writing to achieve real-world goals the majority of python' users may use classes and make instancesand might even do bit of operator overloadingbut they probably won' get too deep into the details of how their classes actually work howeverin this book we've also seen variety of tools that allow us to control python' behavior in generic waysand that often have more to do with python internals or tool building than with application-programming domains as reviewand to help us place metaclasses in the tools spectrumintrospection attributes and tools special attributes like __class__ and __dict__ allow us to inspect internal implementation aspects of python objectsin order to process them generically--to list all attributes of an objectdisplay class' nameand so on as we've also seentools such as dir and getattr can serve similar roles when "virtualattributes such as slots must be supported operator overloading methods specially named methods such as __str__ and __add__ coded in classes intercept and provide behavior for built-in operations applied to class instancessuch as printingexpression operatorsand so on they are run automatically in response to built-in operations and allow classes to conform to expected interfaces attribute interception methods special category of operator overloading methods provides way to intercept attribute accesses on instances generically__getattr____setattr____delattr__and __getattribute__ allow wrapper ( proxyclasses to insert automatically run code that may validate attribute requests and delegate them to embedded objects they allow any number of attributes of an object to be computed when accessed--either selected attributesor all of them class properties the property built-in allows us to associate code with specific class attribute that is automatically run when the attribute is fetchedassignedor deleted though not as generic as the prior paragraph' toolsproperties allow for automatic code invocation on access to specific attributes class attribute descriptors reallyproperty is succinct way to define an attribute descriptor that runs functions on access automatically descriptors allow us to code in separate class and to quote python error message just came across"typeerrormetaclass conflictthe metaclass of derived class must be (non-strictsubclass of the metaclasses of all its bases(!this reflects an erroneous use of module as superclassbut metaclasses may not be as optional as developers imply -- theme we'll revisit in the next conclusion to this book to metaclass or not to metaclass |
1,910 | an attribute assigned to an instance of that class is accessed they provide general way to insert arbitrary code that is run implicitly when specific attribute is accessed as part of the normal attribute lookup procedure function and class decorators as we saw in the special @callable syntax for decorators allows us to add logic to be automatically run when function is called or class instance is created this wrapper logic can trace or time callsvalidate argumentsmanage all instances of classaugment instances with extra behavior such as attribute fetch validationand more decorator syntax inserts name-rebinding logic to be run at the end of function and class definition statements--decorated function and class names may be rebound to either augmented original objectsor to object proxies that intercept later calls metaclasses the last topic of magic introduced in which we take up here as mentioned in this introductionmetaclasses are continuation of this story --they allow us to insert logic to be run automatically at the end of class statementwhen class object is being created though strongly reminiscent of class decoratorsthe metaclass mechanism doesn' rebind the class name to decorator callable' resultbut rather routes creation of the class itself to specialized logic language of hooks in other wordsmetaclasses are ultimately just another way to define automatically run code with the tools listed in the prior sectionpython provides ways for us to interject logic in variety of contexts--at operator evaluationattribute accessfunction callsclass instance creationand now class object creation it' language with hooks galore -- feature open to abuse like any otherbut one that also offers the flexibility that some programmers desireand that some programs may require as we've also seenmany of these advanced python tools have intersecting roles for exampleattributes can often be managed with propertiesdescriptorsor attribute interception methods as we'll see in this class decorators and metaclasses can often be used interchangeably as well by way of previewalthough class decorators are often used to manage instancesthey can also be used to manage classes insteadmuch like metaclasses similarlywhile metaclasses are designed to augment class constructionthey can also insert proxies to manage instances insteadmuch like class decorators in factthe main functional difference between these two tools is simply their place in the timing of class creation as we saw in the prior class decorators run after the decorated class has already been created thusthey are often used to add logic to metaclasses |
1,911 | through changes or proxiesinstead of more direct relationship as we'll see heremetaclassesby contrastrun during class creation to make and return the new client class thereforethey are often used for managing or augmenting classes themselvesand can even provide methods to process the classes that are created from themvia direct instance relationship for examplemetaclasses can be used to add decoration to all methods of classes automaticallyregister all classes in use to an apiadd user-interface logic to classes automaticallycreate or extend classes from simplified specifications in text filesand so on because they can control how classes are made--and by proxy the behavior their instances acquire--metaclass applicability is potentially very wide as we'll also see herethoughthese two tools are more similar than different in many common roles since tool choices are sometimes partly subjectiveknowledge of the alternatives can help you pick the right tool for given task to understand the options betterlet' see how metaclasses stack up the downside of "helperfunctions also like the decorators of the prior metaclasses are often optional from theoretical perspective we can usually achieve the same effect by passing class objects through manager functions--sometimes known as helper functions--much as we can achieve the goals of decorators by passing functions and instances through manager code just like decoratorsthoughmetaclassesprovide more formal and explicit structure help ensure that application programmers won' forget to augment their classes according to an api' requirements avoid code redundancy and its associated maintenance costs by factoring class customization logic into single locationthe metaclass to illustratesuppose we want to automatically insert method into set of classes of coursewe could do this with simple inheritanceif the subject method is known when we code the classes in that casewe can simply code the method in superclass and have all the classes in question inherit from itclass extrasdef extra(selfargs)normal inheritancetoo static class client (extras)class client (extras)class client (extras)clients inherit extra methods client ( extra(make an instance run the extra methods to metaclass or not to metaclass |
1,912 | user interface at runtimeor to specifications typed in configuration file although we could code every class in our imaginary set to manually check thesetooit' lot to ask of clients (required is abstract here--it' something to be filled in)def extra(selfarg)class client if required()client extra extra client augmentstoo distributed class client if required()client extra extra class client if required()client extra extra client ( extra(we can add methods to class after the class statement like this because class-level method is just function that is associated with class and has first argument to receive the self instance although this worksit might become untenable for larger method setsand puts all the burden of augmentation on client classes (and assumes they'll remember to do this at all!it would be better from maintenance perspective to isolate the choice logic in single place we might encapsulate some of this extra work by routing classes through manager function--such manager function would extend the class as required and handle all the work of runtime testing and configurationdef extra(selfarg)def extras(class)if required()class extra extra class client extras(client class client extras(client class client extras(client client ( extra( metaclasses manager functiontoo manual |
1,913 | although manager functions like this one can achieve our goal herethey still put fairly heavy burden on class coderswho must understand the requirements and adhere to them in their code it would be better if there was simple way to enforce the augmentation in the subject classesso that they don' need to deal with the augmentation so explicitlyand would be less likely to forget to use it altogether in other wordswe' like to be able to insert some code to run automatically at the end of class statementto augment the class this is exactly what metaclasses do--by declaring metaclasswe tell python to route the creation of the class object to another class we providedef extra(selfarg)class extras(type)def __init__(classclassnamesuperclassesattributedict)if required()class extra extra class client (metaclass=extras)class client (metaclass=extras)class client (metaclass=extras)metaclass declaration only ( formclient class is instance of meta client ( extra( is instance of client because python invokes the metaclass automatically at the end of the class statement when the new class is createdit can augmentregisteror otherwise manage the class as needed moreoverthe only requirement for the client classes is that they declare the metaclassevery class that does so will automatically acquire whatever augmentation the metaclass providesboth now and in the future if the metaclass changes of coursethis is the standard rationalewhich you'll need to judge for yourself--in truthclients might forget to list metaclass just as easily as they could forget to call manager functionstillthe explicit nature of metaclasses may make this less likely moreovermetaclasses have additional potentials we haven' yet seen although it may be difficult to glean from this small examplemetaclasses generally handle such tasks better than more manual approaches metaclasses versus class decoratorsround having said thatit' also important to note that the class decorators described in the preceding sometimes overlap with metaclasses--in terms of both utility and benefit although they are often used for managing instancesclass decorators can also augment classesindependent of any created instances their syntax makes their usage similarly explicitand arguably more obvious than manager function calls for examplesuppose we coded our manager function to return the augmented classinstead of simply modifying it in place this would allow greater degree of flexibilityto metaclass or not to metaclass |
1,914 | class' expected interfacedef extra(selfarg)def extras(class)if required()class extra extra return class class client client extras(client class client client extras(client class client client extras(client client ( extra(if you think this is starting to look reminiscent of class decoratorsyou're right in the prior we emphasized class decoratorsrole in augmenting instance creation calls because they work by automatically rebinding class name to the result of functionthoughthere' no reason that we can' use them to augment the class by changing it before any instances are ever created that isclass decorators can apply extra logic to classesnot just instancesat class creation timedef extra(selfarg)def extras(class)if required()class extra extra return class @extras class client client extras(client @extras class client rebinds class independent of instances @extras class client client ( extra(makes instance of augmented class is instance of original client decorators essentially automate the prior example' manual name rebinding here just as for metaclassesbecause this decorator returns the original classinstances are made from itnot from wrapper object in factinstance creation is not intercepted at all in this example metaclasses |
1,915 | metaclasses and decorators is somewhat arbitrary decorators can be used to manage both instances and classesand intersect most strongly with metaclasses in the second of these rolesbut this discrimination is not absolute in factthe roles of each are determined in part by their mechanics as we'll see aheaddecorators technically correspond to metaclass __init__ methodsused to initialize newly created classes metaclasses have additional customization hooks beyond class initializationthoughand may perform arbitrary class construction tasks that might be more difficult with decorators this can make them more complexbut also better suited for augmenting classes as they are being formed for examplemetaclasses also have __new__ method used to create classwhich has no analogy in decoratorsmaking new class in decorator would incur an extra step moreovermetaclasses may also provide behavior acquired by classes in the form of methodswhich have no direct counterpart in decorators eitherdecorators must provide class behavior is less direct ways converselybecause metaclasses are designed to manage classesapplying them to managing instances alone is less optimal because they are also responsible for making the class itselfmetaclasses incur this as an extra step in instance management roles we'll explore these differences in code later in this and will flesh out this section' partial code into real working example later in this to understand how metaclasses do their workthoughwe first need to get clearer picture of their underlying model there' magicand then there' magic this "increasing levels of magiclist deals with types of magic beyond those widely seen as beneficial by programmers some might add python' functional tools like closures and generatorsand even its basic oop supportto this list--the former relying on scope retention and automatic generator object creationand the latter on inheritance attribute search and special first function argument though based on magic toothese represent paradigms that ease the task of programming by providing abstractions above and beyond the underlying hardware architecture for exampleoop--python' earlier paradigm--is broadly accepted in the software world it provides model for writing programs that is more completeexplicitand richly structured than functional tools that issome levels of magic are considered more warranted than othersafter allif it were not for some magicprograms would still consist of machine code (or physical switchesit' usually the accumulation of new magic that puts systems at risk of breaching complexity threshold--such as adding functional paradigm to what was always an oo languageor adding redundant or advanced ways to achieve goals that are rarely pursued in the common practice of most users such magic can set the entry bar far too high for large part of your tool' audience to metaclass or not to metaclass |
1,916 | of compilerfor instancedoes not generally require its users to be compiler developers by contrastpython' super assumes full mastery and deployment of the arguably obscure and artificial mro algorithm the new-style inheritance algorithm presented in this similarly assumes descriptorsmetaclassesand the mro as its prerequisites--all advanced tools in their own right even implicit "hookslike descriptors remain implicit only until their first failure or maintenance cycle such magic exposed escalates tool' prerequisites and downgrades its usability in open source systemsonly time and downloads can determine where such thresholds may lie finding the proper balance of power and complexity depends as much on shifting opinion as on technology subjective factors asidethoughnew magic that imposes itself on users inevitably skews system' learning curve higher-- topic we'll return to in the next final words the metaclass model to understand metaclassesyou first need to understand bit more about python' type model and what happens at the end of class statement as we'll see herethe two are intimately related classes are instances of type so far in this bookwe've done most of our work by making instances of built-in types like lists and stringsas well as instances of classes we code ourselves as we've seeninstances of classes have some state information attributes of their ownbut they also inherit behavioral attributes from the classes from which they are made the same holds true for built-in typeslist instancesfor examplehave values of their ownbut they inherit methods from the list type while we can get lot done with such instance objectspython' type model turns out to be bit richer than 've formally described reallythere' hole in the model we've seen thus farif instances are created from classeswhat is it that creates our classesit turns out that classes are instances of somethingtooin python xuser-defined class objects are instances of the object named typewhich is itself class in python xnew-style classes inherit from objectwhich is subclass of typeclassic classes are instances of type and are not created from class we explored the notion of types in and the relationship of classes to types in but let' review the basics here so we can see how they apply to metaclasses recall that the type built-in returns the type of any object (which is itself an objectwhen called with single argument for built-in types like liststhe type of the instance metaclasses |
1,917 | at the top of the hierarchy creates specific typesand specific types create instances you can see this for yourself at the interactive prompt in python xfor examplethe type of list instance is the list classand the type of the list class is the type classc:\codepy - type([])type(type([])(type(list)type(type(in xlist instance is created from list class list class is created from type class samebut with type names type of type is typetop of hierarchy as we learned when studying new-style class changes in the same is generally true in python xbut types are not quite the same as classes--type is unique kind of built-in object that caps the type hierarchy and is used to construct typesc:\codepy - type([])type(type([])(type(list)type(type(in xtype is bit different as it happensthe type/instance relationship holds true for user-defined classes as wellinstances are created from classesand classes are created from type in python xthoughthe notion of "typeis merged with the notion of "class in factthe two are essentially synonyms--classes are typesand types are classes that istypes are defined by classes that derive from type user-defined classes are instances of type classes user-defined classes are types that generate instances of their own as we saw earlierthis equivalence affects code that tests the type of instancesthe type of an instance is the class from which it was generated it also has implications for the way that classes are created that turn out to be the key to this subject because classes are normally created from root type class by defaultmost programmers don' need to think about this type/class equivalence howeverit opens up new possibilities for customizing both classes and their instances for exampleall user-defined classes in (and new-style classes in xare instances of the type classand instance objects are instances of their classesin factclasses now have __class__ that links to typejust as an instance has __class__ that links to the class from which it was madec:\codepy - class cpass ( class object (new-styleclass instance object type(xx __class__ instance is instance of class type(cclass is instance of type instance' class the metaclass model |
1,918 | __class__ class' class is type notice especially the last two lines here--classes are instances of the type classjust as normal instances are instances of user-defined class this works the same for both built-ins and user-defined class types in in factclasses are not really separate concept at allthey are simply user-defined typesand type itself is defined by class in python xthings work similarly for new-style classes derived from objectbecause this enables class behavior (as we've seen adds object to the __bases__ superclass tuple of top-level root classes automatically to qualify them as new-style) :\codepy - class (object)pass (in new-style classesclasses have class too type(xx __class__ type(cc __class__ classic classes in are bit differentthough--because they reflect the original class model in older pythonsthey do not have __class__ linkand like built-in types in they are instances of typenot type class ( 've shortened some of the hex addresses in object displays in this for clarity) :\codepy - class cpass (in classic classesclasses have no class themselves type(xx __class__ type(cc __class__ attributeerrorclass has no attribute '__class__metaclasses are subclasses of type why would we care that classes are instances of type class in xit turns out that this is the hook that allows us to code metaclasses because the notion of type is the same as class todaywe can subclass type with normal object-oriented techniques and class syntax to customize it and because classes are really instances of the type class metaclasses |
1,919 | kinds of classes in full detailthis all works out quite naturally--in xand in new-style classestype is class that generates user-defined classes metaclasses are subclasses of the type class class objects are instances of the type classor subclass thereof instance objects are generated from class in other wordsto control the way classes are created and augment their behaviorall we need to do is specify that user-defined class be created from user-defined metaclass instead of the normal type class notice that this type instance relationship is not quite the same as normal inheritance user-defined classes may also have superclasses from which they and their instances inherit attributes as usual as we've seeninheritance superclasses are listed in parentheses in the class statement and show up in class' __bases__ tuple the type from which class is createdthoughand of which it is an instanceis different relationship inheritance searches instance and class namespace dictionariesbut classes may also acquire behavior from their type that is not exposed to the normal inheritance search to lay the groundwork for understanding this distinctionthe next section describes the procedure python follows to implement this instance-of type relationship class statement protocol subclassing the type class to customize it is really only half of the magic behind metaclasses we still need to somehow route class' creation to the metaclassinstead of the default type to fully understand how this is arrangedwe also need to know how class statements do their business we've already learned that when python reaches class statementit runs its nested block of code to create its attributes--all the names assigned at the top level of the nested code block generate attributes in the resulting class object these names are usually method functions created by nested defsbut they can also be arbitrary attributes assigned to create class data shared by all instances technically speakingpython follows standard protocol to make this happenat the end of class statementand after running all its nested code in namespace dictionary corresponding to the class' local scopepython calls the type object to create the class object like thisclass type(classnamesuperclassesattributedictthe type object in turn defines __call__ operator overloading method that runs two other methods when the type object is calledthe metaclass model |
1,920 | type __init__(classclassnamesuperclassesattributedictthe __new__ method creates and returns the new class objectand then the __init__ method initializes the newly created object as we'll see in momentthese are the hooks that metaclass subclasses of type generally use to customize classes for examplegiven class definition like the following for spamclass eggsinherited names here class spam(eggs)data def meth(selfarg)return self data arg inherits from eggs class data attribute class method attribute python will internally run the nested code block to create two attributes of the class (data and meth)and then call the type object to generate the class object at the end of the class statementspam type('spam'(eggs,){'data' 'meth'meth'__module__''__main__'}in factyou can call type this way yourself to create class dynamically--albeit here with fabricated method function and empty superclasses tuple (python adds object automatically in both and ) type('spam'(){'data' 'meth'(lambda xyx data )} (xi ( datai meth( ( the class produced is exactly like that you' get from running class statementx __bases__ (,[(avfor (avin __dict__ items(if not startswith('__')[('data' )('meth'at >)because this type call is made automatically at the end of the class statementthoughit' an ideal hook for augmenting or otherwise processing class the trick lies in replacing the default type with custom subclass that will intercept this call the next section shows how declaring metaclasses as we've just seenclasses are created by the type class by default to tell python to create class with custom metaclass insteadyou simply need to declare metaclass to intercept the normal instance creation call in user-defined class how you do so depends on which python version you are using metaclasses |
1,921 | in python xlist the desired metaclass as keyword argument in the class headerclass spam(metaclass=meta) version (onlyinheritance superclasses can be listed in the header as well in the followingfor examplethe new class spam inherits from superclass eggsbut is also an instance of and is created by metaclass metaclass spam(eggsmetaclass=meta)normal supers okmust list first in this formsuperclasses must be listed before the metaclassin effectthe ordering rules used for keyword arguments in function calls apply here declaration in we can get the same effect in python xbut we must specify the metaclass differently --using class attribute instead of keyword argumentclass spam(object)__metaclass__ meta version (only)object optionalclass spam(eggsobject)__metaclass__ meta normal supers okobject suggested technicallysome classes in do not have to derive from object explicitly to make use of metaclasses the generalized metaclass dispatch mechanism was added at the same time as new-style classesbut is not itself bound to them it doeshoweverproduce them--in the presence of __metaclass__ declaration makes the resulting class new-style automaticallyadding object to its __bases__ sequence in the absence of this declaration simply uses the classic class creator as the metaclass default because of thissome classes in require only the __metaclass__ attribute on the other handnotice that metaclasses imply that your class will be new-style in even without an explicit object they'll behave somewhat differently as outlined in and as we'll see ahead may require that they or their superclasses derive from object explicitlybecause new-style class cannot have only classic superclasses in this context given thisderiving from object doesn' hurt as sort of warning about the class' natureand may be required to avoid potential problems also in xa module level __metaclass__ global variable is available to link all classes in the module to metaclass this is no longer supported in xas it was intended as temporary measure to make it easier to default to new-style classes without deriving every class from object python also ignores the class attributeand the keyword form is syntax error in xso there is no simple portability route apart from differing syntaxthoughmetaclass declaration in and has the same effectwhich we turn to next declaring metaclasses |
1,922 | when specific metaclass is declared per the prior sectionssyntaxthe call to create the class object run at the end of the class statement is modified to invoke the metaclass instead of the type defaultclass meta(classnamesuperclassesattributedictand because the metaclass is subclass of typethe type class' __call__ delegates the calls to create and initialize the new class object to the metaclassif it defines custom versions of these methodsmeta __new__(metaclassnamesuperclassesattributedictmeta __init__(classclassnamesuperclassesattributedictto demonstratehere' the prior section' example againaugmented with metaclass specificationclass spam(eggsmetaclass=meta)data def meth(selfarg)return self data arg inherits from eggsinstance of meta class data attribute class method attribute at the end of this class statementpython internally runs the following to create the class object--againa call you could make manually toobut automatically run by python' class machineryspam meta('spam'(eggs,){'data' 'meth'meth'__module__''__main__'}if the metaclass defines its own versions of __new__ or __init__they will be invoked in turn during this call by the inherited type class' __call__ methodto create and initialize the new class the net effect is to automatically run methods the metaclass providesas part of the class construction process the next section shows how we might go about coding this final piece of the metaclass puzzle this uses python metaclass keyword argument syntaxnot the class attribute readers will need to translatebut version neutrality is not straightforward here-- doesn' recognize the attribute and doesn' allow keyword syntax--and listing examples twice doesn' address portability (or size!coding metaclasses so farwe've seen how python routes class creation calls to metaclassif one is specified and provided howthoughdo we actually code metaclass that customizes typeit turns out that you already know most of the story--metaclasses are coded with normal python class statements and semantics by definitionthey are simply classes that inherit from type their only substantial distinctions are that python calls them metaclasses |
1,923 | basic metaclass perhaps the simplest metaclass you can code is simply subclass of type with __new__ method that creates the class object by running the default version in type metaclass __new__ like this is run by the __call__ method inherited from typeit typically performs whatever customization is required and calls the type superclass' __new__ method to create and return the new class objectclass meta(type)def __new__(metaclassnamesupersclassdict)run by inherited type __call__ return type __new__(metaclassnamesupersclassdictthis metaclass doesn' really do anything (we might as well let the default type class create the class)but it demonstrates the way metaclass taps into the metaclass hook to customize--because the metaclass is called at the end of class statementand because the type object' __call__ dispatches to the __new__ and __init__ methodscode we provide in these methods can manage all the classes created from the metaclass here' our example in action againwith prints added to the metaclass and the file at large to trace (againsome filenames are implied by later command-lines in this class metaone(type)def __new__(metaclassnamesupersclassdict)print('in metaone new:'metaclassnamesupersclassdictsep='\ 'return type __new__(metaclassnamesupersclassdictclass eggspass print('making class'class spam(eggsmetaclass=metaone)data def meth(selfarg)return self data arg inherits from eggsinstance of metaone class data attribute class method attribute print('making instance' spam(print('data:' datax meth( )herespam inherits from eggs and is an instance of metaonebut is an instance of and inherits from spam when this code is run with python xnotice how the metaclass is invoked at the end of the class statementbefore we ever make an instance--metaclasses are for processing classesand classes are for processing normal instancesc:\codepy - metaclass py making class in metaone newcoding metaclasses |
1,924 | spam (,{'data' 'meth''__module__''__main__'making instance data presentation notei' truncating addresses and omitting some irrelevant built-in __x__ names in namespace dictionaries in this for brevityand as noted earlier am forgoing portability due to differing declaration syntax to run in xuse the class attribute formand change print operations as desired this example works in with the following modificationsin the file metaclass - pynotice that either eggs or spam must be derived from object explicitlyor else issues warning because new-style class can' have only classic bases here--when in doubtuse object in metaclasses clientsto run the same in (onlyone of the "objectoptional from __future__ import print_function class eggs(object)class spam(eggsobject)__metaclass__ metaone customizing construction and initialization metaclasses can also tap into the __init__ protocol invoked by the type object' __call__ in general__new__ creates and returns the class objectand __init__ initializes the already created class passed in as an argument metaclasses can use either or both hooks to manage the class at creation timeclass metatwo(type)def __new__(metaclassnamesupersclassdict)print('in metatwo new'classnamesupersclassdictsep='\ 'return type __new__(metaclassnamesupersclassdictdef __init__(classclassnamesupersclassdict)print('in metatwo init:'classnamesupersclassdictsep='\ 'print(init class object:'list(class __dict__ keys())class eggspass print('making class'class spam(eggsmetaclass=metatwo)data def meth(selfarg)return self data arg inherits from eggsinstance of metatwo class data attribute class method attribute print('making instance' spam(print('data:' datax meth( )in this casethe class initialization method is run after the class construction methodbut both run at the end of the class statement before any instances are made con metaclasses |
1,925 | run by the metaclass' __init__c:\codepy - metaclass py making class in metatwo newspam (,{'data' 'meth''__module__''__main__'in metatwo initspam (,{'data' 'meth''__module__''__main__'init class object['__qualname__''data''__module__''meth''__doc__'making instance data other metaclass coding techniques although redefining the type superclass' __new__ and __init__ methods is the most common way to insert logic into the class object creation process with the metaclass hookother schemes are possible using simple factory functions for examplemetaclasses need not really be classes at all as we've learnedthe class statement issues simple call to create class at the conclusion of its processing because of thisany callable object can in principle be used as metaclassprovided it accepts the arguments passed and returns an object compatible with the intended class in facta simple object factory function may serve just as well as type subclassa simple function can serve as metaclass too def metafunc(classnamesupersclassdict)print('in metafunc'classnamesupersclassdictsep='\ 'return type(classnamesupersclassdictclass eggspass print('making class'class spam(eggsmetaclass=metafunc)data def meth(selfarg)return self data arg run simple function at end function returns class print('making instance' spam(print('data:' datax meth( )coding metaclasses |
1,926 | returns the expected new class object the function is simply catching the call that the type object' __call__ normally intercepts by defaultc:\codepy - metaclass py making class in metafuncspam (,{'data' 'meth''__module__''__main__'making instance data overloading class creation calls with normal classes because normal class instances can respond to call operations with operator overloadingthey can serve in some metaclass roles toomuch like the preceding function the output of the following is similar to the prior class-based versionsbut it' based on simple class--one that doesn' inherit from type at alland provides __call__ for its instances that catches the metaclass call using normal operator overloading note that __new__ and __init__ must have different names hereor else they will run when the meta instance is creatednot when it is later called in the role of metaclassa normal class instance can serve as metaclass too class metaobjdef __call__(selfclassnamesupersclassdict)print('in metaobj call'classnamesupersclassdictsep='\ 'class self __new__(classnamesupersclassdictself __init__(classclassnamesupersclassdictreturn class def __new__(selfclassnamesupersclassdict)print('in metaobj new'classnamesupersclassdictsep='\ 'return type(classnamesupersclassdictdef __init__(selfclassclassnamesupersclassdict)print('in metaobj init:'classnamesupersclassdictsep='\ 'print(init class object:'list(class __dict__ keys())class eggspass print('making class'class spam(eggsmetaclass=metaobj())data def meth(selfarg)return self data arg print('making instance' spam(print('data:' datax meth( ) metaclasses metaobj is normal class instance called at end of statement |
1,927 | semanticsc:\codepy - metaclass py making class in metaobj callspam (,{'data' 'meth''__module__''__main__'in metaobj newspam (,{'data' 'meth''__module__''__main__'in metaobj initspam (,{'data' 'meth''__module__''__main__'init class object['__module__''__doc__''data''__qualname__''meth'making instance data in factwe can use normal superclass inheritance to acquire the call interceptor in this coding model--the superclass here is serving essentially the same role as typeat least in terms of metaclass dispatchinstances inherit from classes and their supers normally class supermetaobjdef __call__(selfclassnamesupersclassdict)print('in supermetaobj call'classnamesupersclassdictsep='\ 'class self __new__(classnamesupersclassdictself __init__(classclassnamesupersclassdictreturn class class submetaobj(supermetaobj)def __new__(selfclassnamesupersclassdict)print('in submetaobj new'classnamesupersclassdictsep='\ 'return type(classnamesupersclassdictdef __init__(selfclassclassnamesupersclassdict)print('in submetaobj init:'classnamesupersclassdictsep='\ 'print(init class object:'list(class __dict__ keys())class spam(eggsmetaclass=submetaobj())rest of file unchanged invoke sub instance via super __call__ :\codepy - metaclass -super py making class in supermetaobj callas before in submetaobj newas before in submetaobj initas before coding metaclasses |
1,928 | making instance data although such alternative forms workmost metaclasses get their work done by redefining the type superclass' __new__ and __init__in practicethis is usually as much control as is requiredand it' often simpler than other schemes moreovermetaclasses have access to additional toolssuch as class methods we'll explore aheadwhich can influence class behavior more directly than some other schemes stillwe'll see later that simple callable-based metaclass can often work much like class decoratorwhich allows the metaclasses to manage instances as well as classes firstthoughthe next section presents an example drawn from the python "twilight zoneto introduce metaclass name resolution concepts overloading class creation calls with metaclasses since they participate in normal oop mechanicsit' also possible for metaclasses to catch the creation call at the end of class statement directlyby redefining the type object' __call__ the redefinitions of both __new__ and __call__ must be careful to call back to their defaults in type if they mean to make class in the endand __call__ must invoke type to kick off the other two hereclasses can catch calls too (but built-ins look in metasnot supers!class supermeta(type)def __call__(metaclassnamesupersclassdict)print('in supermeta call'classnamesupersclassdictsep='\ 'return type __call__(metaclassnamesupersclassdictdef __init__(classclassnamesupersclassdict)print('in supermeta init:'classnamesupersclassdictsep='\ 'print(init class object:'list(class __dict__ keys())print('making metaclass'class submeta(typemetaclass=supermeta)def __new__(metaclassnamesupersclassdict)print('in submeta new'classnamesupersclassdictsep='\ 'return type __new__(metaclassnamesupersclassdictdef __init__(classclassnamesupersclassdict)print('in submeta init:'classnamesupersclassdictsep='\ 'print(init class object:'list(class __dict__ keys())class eggspass print('making class'class spam(eggsmetaclass=submeta)data def meth(selfarg)return self data arg print('making instance' metaclasses invoke submetavia supermeta __call__ |
1,929 | print('data:' datax meth( )this code has some oddities 'll explain in moment when runthoughall three redefined methods run in turn for spam as in the prior section this is again essentially what the type object does by defaultbut there' an additional metaclass call for the metaclass subclass (metasubclass?) :\codepy - metaclass py making metaclass in supermeta initsubmeta (,{'__init__'init class object['__doc__''__module__''__new__''__init__making class in supermeta callspam (,{'data' 'meth''__module__''__main__'in submeta newspam (,{'data' 'meth''__module__''__main__'in submeta initspam (,{'data' 'meth''__module__''__main__'init class object['__qualname__''__module__''__doc__''data''meth'making instance data this example is complicated by the fact that it overrides method invoked by builtin operation--in this casethe call run automatically to create class metaclasses are used to create class objectsbut only generate instances of themselves when called in metaclass role because of thisname lookup with metaclasses may be somewhat different than what we are accustomed to the __call__ methodfor exampleis looked up by built-ins in the class ( typeof an objectfor metaclassesthis means the metaclass of metaclassas we'll see aheadmetaclasses also inherit names from other metaclasses normallybut as for normal classesthis seems to apply to explicit name fetches onlynot to the implicit lookup of names for built-in operations such as calls the latter appears to look in the metaclass' classavailable in its __class__ link--which is either the default type or metaclass this is the same built-ins routing issue we've seen so often in this book for normal class instances the metaclass in submeta is required to set this linkthough this also kicks off metaclass construction step for the metaclass itself trace the invocations in the output supermeta' __call__ method is not run for the call to supermeta when making submeta (this goes to type instead)but is run for the sub meta call when making spam inheriting normally from supermeta does not suffice to coding metaclasses |
1,930 | operator overloading methodssupermeta' __call__ is then acquired by spamcausing spam instance creation calls to fail before any instance is ever created subtle but truehere' an illustration of the issue in simpler terms-- normal superclass is skipped for built-insbut not for explicit fetches and callsthe latter relying on normal attribute name inheritanceclass supermeta(type)def __call__(metaclassnamesupersclassdict)by namenot built-in print('in supermeta call:'classnamereturn type __call__(metaclassnamesupersclassdictclass submeta(supermeta)def __init__(classclassnamesupersclassdict)print('in submeta init:'classnamecreated by type default overrides type __init__ print(submeta __class__print([ __name__ for in submeta __mro__]print(print(submeta __call__not data descriptor if found by name print(submeta __call__(submeta'xxx'(){}explicit calls workclass inheritance print(submeta('yyy'(){}but implicit built-in calls do nottype :\codepy - metaclass py ['submeta''supermeta''type''object'in supermeta callxxx in submeta initxxx in submeta inityyy of coursethis specific example is special casecatching built-in run on metaclassa likely rare usage related to __call__ here but it underscores core asymmetry and apparent inconsistencynormal attribute inheritance is not fully used for built-in dispatch --for both instances and classes to truly understand this example' subtletiesthoughwe need to get more formal about what metaclasses mean for python name resolution in general inheritance and instance because metaclasses are specified in similar ways to inheritance superclassesthey can be bit confusing at first glance few key points should help summarize and clarify the model metaclasses |
1,931 | although they have special rolemetaclasses are coded with class statements and follow the usual oop model in python for exampleas subclasses of typethey can redefine the type object' methodsoverriding and customizing them as needed metaclasses typically redefine the type class' __new__ and __init__ to customize class creation and initialization although it' less commonthey can also redefine __call__ if they wish to catch the end-of-class creation call directly (albeit with the complexities we saw in the prior section)and can even be simple functions or other callables that return arbitrary objectsinstead of type subclasses metaclass declarations are inherited by subclasses the metaclass= declaration in user-defined class is inherited by the class' normal subclassestooso the metaclass will run for the construction of each class that inherits this specification in superclass inheritance chain metaclass attributes are not inherited by class instances metaclass declarations specify an instance relationshipwhich is not the same as what we've called inheritance thus far because classes are instances of metaclassesthe behavior defined in metaclass applies to the classbut not the class' later instances instances obtain behavior from their classes and superclassesbut not from any metaclasses technicallyattribute inheritance for normal instances usually searches only the __dict__ dictionaries of the instanceits classand all its superclassesmetaclasses are not included in inheritance lookup for normal instances metaclass attributes are acquired by classes by contrastclasses do acquire methods of their metaclasses by virtue of the instance relationship this is source of class behavior that processes classes themselves technicallyclasses acquire metaclass attributes through the class' __class__ link just as normal instances acquire names from their classbut inheritance via __dict__ search is attempted firstwhen the same name is available to class in both metaclass and superclassthe superclass (inheritanceversion is used instead of that on metaclass (instancethe class' __class__howeveris not followed for its own instancesmetaclass attributes are made available to their instance classesbut not to instances of those instance classes (and see the earlier reference to dr seuss this may be easier to understand in code than in prose to illustrate all these pointsconsider the following examplefile metainstance py class metaone(type)def __new__(metaclassnamesupersclassdict)redefine type method print('in metaone new:'classnamereturn type __new__(metaclassnamesupersclassdictdef toast(self)return 'toastinheritance and instance |
1,932 | def spam(self)return 'spammetaclass inherited by subs too metaone run twice for two classes class sub(super)def eggs(self)return 'eggssuperclassinheritance versus instance classes inherit from superclasses but not from metaclasses when this code is run (as script or module)the metaclass handles construction of both client classesand instances inherit class attributes but not metaclass attributesfrom metainstance import in metaone newsuper in metaone newsub runs class statementsmetaclass run twice sub(normal instance of user-defined class eggs(inherited from sub 'eggsx spam(inherited from super 'spamx toast(not inherited from metaclass attributeerror'subobject has no attribute 'toastby contrastclasses both inherit names from their superclassesand acquire names from their metaclass (which in this example is itself inherited from superclass)sub eggs(xown method 'eggssub spam(xinherited from super 'spamsub toast(acquired from metaclass 'toastsub toast(xnot normal class method typeerrortoast(takes positional argument but were given notice how the last of the preceding calls fails when we pass in an instancebecause the name resolves to metaclass methodnot normal class method in factboth the object you fetch name from and its source become crucial here methods acquired from metaclasses are bound to the subject classwhile methods from normal classes are unbound if fetched through the class but bound when fetched through the instancesub toast sub spam spam we've studied the last two of these rules before in ' bound method coveragethe first is newbut reminiscent of class methods to understand why this works the way it doeswe need to explore the metaclass instance relationship further metaclasses |
1,933 | in even simpler termswatch what happens in the followingas an instance of the metaclass typeclass acquires ' attributebut this attribute is not made available for inheritance by ' own instances--the acquisition of names by metaclass instances is distinct from the normal inheritance used for class instancesclass (type)attr class (metaclass= )pass is meta instance and acquires meta attr ( inherits from class but not metab attr attr attributeerror'bobject has no attribute 'attr'attrin __dict__'attrin __dict__ (falsetrueby contrastif morphs from metaclass to superclassthen names inherited from an superclass become available to later instances of band are located by searching namespace dictionaries in classes in the tree--that isby checking the __dict__ of objects in the method resolution order (mro)much like the mapattrs example we coded back in class aattr class ( )pass inherits from class and supers ( attr attr 'attrin __dict__'attrin __dict__ (falsetruethis is why metaclasses often do their work by manipulating new class' namespace dictionaryif they wish to influence the behavior of later instance objects--instances will see names in classbut not its metaclass watch what happensthoughif the same name is available in both attribute sources--the inheritance name is used instead of instance acquisitionclass (type)attr class aattr class (ametaclass= )pass supers have precedence over metas ( attri attr ( 'attrin __dict__'attrin __dict__'attrin __dict__ (falsetruetruethis is true regardless of the relative height of the inheritance and instance sources-python checks the __dict__ of each class on the mro (inheritance)before falling back on metaclass acquisition (instance)class (type)attr class aattr inheritance and instance |
1,934 | class (bmetaclass= )pass ( attrc attr ( [ __name__ for in __mro__[' '' '' ''object'super two levels above metastill wins see for all things mro in factclasses acquire metaclass attributes through their __class__ linkin the same way that normal instances inherit from classes through their __class__which makes sensegiven that classes are also instances of metaclasses the chief distinction is that instance inheritance does not follow class' __class__but instead restricts its scope to the __dict__ of each class in tree per the mro--following __bases__ at each class onlyand using only the instance' __class__ link oncei __class__ __bases__ (, __class__ __class__ attr followed by inheritanceinstance' class followed by inheritanceclass' supers followed by instance acquisitionmetaclass another way to get to metaclass attributes if you study thisyou'll probably notice nearly glaring symmetry herewhich leads us to the next section inheritancethe full story as it turns outinstance inheritance works in similar wayswhether the "instanceis created from normal classor is class created from metaclass subclass of type-- single attribute search rulewhich fosters the grander and parallel notion of metaclass inheritance hierarchies to illustrate the basics of this conceptual mergerin the followingthe instance inherits from all its classesthe class inherits from both classes and metaclassesand metaclasses inherit from higher metaclasses (supermetaclasses?)class (type)attr class ( )attr metaclass inheritance tree gets __bases____class____mro__ class attr class ( ,metaclass= )attr superclass inheritance tree gets __bases____class____mro__ ( attr attr ( attr attr attr attr ( attr attr ( gets __class__ but not others instance inherits from super tree metaclasses class gets names from both treesmetaclass inherits names too |
1,935 | explicitlyi __class__ __bases__ (,links followed at instance with no __bases__ __class__ __bases__ (,links followed at class after __bases__ __class__ attr route inheritance to the class' meta tree attr though class' __class__ not followed normally attributeerror' object has no attribute 'attr __class__ [ __name__ for in __mro__[' '' ''object'[ __name__ for in __mro__[' '' ''type''object'both trees have mros and instance links __bases__ tree from __class__ __bases__ tree from __class__ if you care about metaclassesor must use code that doesstudy these examplesand then study them again in effectinheritance follows __bases__ before following single __class__normal instances have no __bases__and classes have both--whether normal or metaclass in factunderstanding this example is important to python name resolution in generalas the next section explains python' inheritance algorithmthe simple version now that we know about metaclass acquisitionwe're finally able to formalize the inheritance rules that they augment technicallyinheritance deploys two distinct but similar lookup routinesand is based on mros because __bases__ are used to construct the __mro__ ordering at class creation timeand because class' __mro__ includes itselfthe prior section' generalization is the same as the following-- first-cut definition of python' new-style inheritance algorithmto look up an explicit attribute name from an instance isearch the instancethen its classand then all its superclassesusinga the __dict__ of the instance the __dict__ of all classes on the __mro__ found at ' __class__from left to right from class csearch the classthen all its superclassesand then its metaclasses treeusinginheritance and instance |
1,936 | the __dict__ of all metaclasses on the __mro__ found at ' __class__from left to right in both rule and give precedence to data descriptors located in step sources (see ahead in both rule and skip step and begin the search at step for built-in operations (see aheadthe first two steps are followed for normalexplicit attribute fetch only there are exceptions for both built-ins and descriptorsboth of which we'll clarify in moment in additiona __getattr__ or __getattribute__ may also be used for missing or all namesrespectivelyper most programmers need only be aware of the first of these rulesand perhaps the first step of the second--which taken together correspond to classic class inheritance there' an extra acquisition step added for metaclasses ( )but it' essentially the same as others-- fairly subtle equivalence to be surebut metaclass acquisition is not as novel as it may seem in factit' just one component of the larger model the descriptors special case at least that' the normal--and simplistic--case listed step in the prior section speciallybecause it doesn' apply to most codeand complicates the algorithm substantially it turns outthoughthat inheritance also has special case interaction with ' attribute descriptors in shortsome descriptors known as data descriptors --those that define __set__ methods to intercept assignments--are given precedencesuch that their names override other inheritance sources this exception serves some practical roles for exampleit is used to ensure that the special __class__ and __dict__ attributes cannot be redefined by the same names in an instance' own __dict__class cpass ( __class__i __dict__ ({}inheritance special case # class data descriptors have precedence __dict__['name''bobi __dict__['__class__''spami __dict__['__dict__'{dynamic data in the instance assign keysnot attributes name name comes from __dict__ as usual 'bobbut __class__ and __dict__ do noti __class__i __dict__ ({'__class__''spam''__dict__'{}'name''bob'}this data descriptor exception is tested before the preceding two inheritance rules as preliminary stepmay be more important to python implementers than python programmersand can be reasonably ignored by most application code in any event--that metaclasses |
1,937 | special case precedence ruleclass ddef __get__(selfinstanceowner)print('__get__'def __set__(selfinstancevalue)print('__set__'class cd ( ( __get__ __set__ __dict__[' ''spami __get__ data descriptor attribute inherited data descriptor access define same name in instance namespace dict but doesn' hide data descriptor in classconverselyif this descriptor did not define __set__the name in the instance' dictionary would hide the name in its class insteadper normal inheritanceclass ddef __get__(selfinstanceowner)print('__get__'class cd ( ( __get__ __dict__[' ''spami 'spaminherited nondata descriptor access hides class names per normal inheritance rules in both casespython automatically runs the descriptor' __get__ when it' found by inheritancerather than returning the descriptor object itself--part of the attribute magic we met earlier in the book the special status afforded to data descriptorshoweveralso modifies the meaning of attribute inheritanceand thus the meaning of names in your code python' inheritance algorithmthe somewhat-more-complete version with both the data descriptor special case and general descriptor invocation factored in with class and metaclass treespython' full new-style inheritance algorithm can be stated as follows-- complex procedurewhich assumes knowledge of descriptorsmetaclassesand mrosbut is the final arbiter of attribute names nonetheless (in the followingitems are attempted in sequence either as numberedor per their left-to-right order in "orconjunctions)to look up an explicit attribute name from an instance isearch the instanceits classand its superclassesas followsa search the __dict__ of all classes on the __mro__ found at ' __class__ if data descriptor was found in step acall it and exit inheritance and instance |
1,938 | elsecall nondata descriptor or return value found in step from class csearch the classits superclassesand its metaclasses treeas followsa search the __dict__ of all metaclasses on the __mro__ found at ' __class__ if data descriptor was found in step acall it and exit elsecall descriptor or return value in the __dict__ of class on ' own __mro__ elsecall nondata descriptor or return value found in step in both rule and built-in operations essentially use just step sources (see aheadnote here again that this applies to normalexplicit attribute fetch only the implicit lookup of method names for built-ins doesn' follow these rulesand essentially uses just step sources in both casesas the next section will demonstrate on top of all thismethod __getattr__ may be run if defined when an attribute is not foundand method __getattribute__ may be run for every attribute fetchthough they are special-case extensions to the name lookup model see for more on these tools and descriptors assignment inheritance also note that the prior section defines inheritance in terms of attribute reference (lookup)but parts of it apply to attribute assignment as well as we've learnedassignment normally changes attributes in the subject object itselfbut inheritance is also invoked on assignment to test first for some of ' attribute management toolsincluding descriptors and properties when presentsuch tools intercept attribute assignmentand may route it arbitrarily for examplewhen an attribute assignment is run for new-style classesa data descriptor with __set__ method is acquired from class by inheritance using the mroand has precedence over the normal storage model in terms of the prior section' ruleswhen applied to an instancesuch assignments essentially follow steps through of rule searching the instance' class treethough step calls __set__ instead of __get__and step stops and stores in the instance instead of attempting fetch when applied to classsuch assignments run the same procedure on the class' metaclass treeroughly the same as rule but step stops and stores in the class because descriptors are also the basis for other advanced attribute tools such as properties and slotsthis inheritance pre-check on assignment is utilized in multiple contexts the net effect is that descriptors are treated as an inheritance special case in newstyle classesfor both reference and assignment metaclasses |
1,939 | at least that' almost the full story as we've seenbuilt-ins don' follow these rules instances and classes may both be skipped for built-in operations onlyas special case that differs from normal or explicit name inheritance because this is context-specific divergenceit' easier to demonstrate in code than to weave into single algorithm in the followingstr is the built-in__str__ is its explicit name equivalentand the instance is skipped for the built-in onlyclass cinheritance special case # attr built-ins skip step def __str__(self)return('class' ( __str__()str( ('class''class'both from class if not in instance __str__ lambda'instancei __str__()str( ('instance''class'explicit=>instancebuilt-in=>classi attr attr attr asymmetric with normal or explicit names as we saw in metaclass py earlierthe same holds true for classesexplicit names start at the classbut built-ins start at the class' classwhich is its metaclassand defaults to typeclass (type)def __str__(self)return(' class'class ( )pass __str__( )str( (' class'""explicit=>superbuilt-in=>metaclassclass ( )def __str__(self)return(' class' __str__( )str(cexplicit=>classbuilt-in=>metaclass(' class'""class (metaclass= )def __str__(self)return(' class' __str__( )str(cbuilt-in=>user-defined metaclass (' class'' class'in factit can sometimes be nontrivial to know where name comes from in this modelsince all classes also inherit from object--including the default type metaclass in the following' explicit callc appears to get default __str__ from object instead of the metaclassper the first source of class inheritance (the class' own mro)by contrastthe built-in skips ahead to the metaclass as beforeinheritance and instance |
1,940 | pass __str__( )str( (""' class'explicit=>objectbuilt-in=>metaclass __str__ for in (cc __class__type)print([ __name__ for in __mro__][' ''object'[' ''type''object'['type''object'all of which leads us to this book' final import this quote-- tenet that seems to conflict with the status given to descriptors and built-ins in the attribute inheritance mechanism of new-style classesspecial cases aren' special enough to break the rules some practical needs warrant exceptionsof course we'll forgo rationales herebut you should carefully consider the implications of an object-oriented language that applies inheritance--its foundational operation--in such an uneven and inconsistent fashion at minimumthis should underscore the importance of keeping your code simpleto avoid making it dependent on such convoluted rules as alwaysyour code' users and maintainers will be glad you did for more fidelity on this storysee python' internal implementation of inheritance- complete saga chronicled today in its object and typeobject cthe former for normal instancesand the latter for classes delving into internals shouldn' be required to use pythonof coursebut it' the ultimate source of truth in complex and evolving systemand sometimes the best you'll find this is especially true in boundary cases born of accrued exceptions for our purposes herelet' move on to the last bit of metaclass magic metaclass methods just as important as the inheritance of namesmethods in metaclasses process their instance classes--not the normal instance objects we've known as "self,but classes themselves this makes them similar in spirit and form to the class methods we studied in though they again are available in the metaclasses instance realm onlynot to normal instance inheritance the failure at the end of the followingfor examplestems from the explicit name inheritance rules of the prior sectionclass (type)def (cls)print('ax'clsdef (cls)print('ay'clsa metaclass (instances=classesy is overridden by instance class (metaclass= )def (self)print('by'selfdef (self)print('bz'selfa normal class (normal instancesnamespace dict holds and metaclasses |
1,941 | (ax and defined in class itself metaclass method callgets cls (instance method callsget inst (by (bz (instance doesn' see meta names attributeerror'bobject has no attribute 'xmetaclass methods versus class methods though they differ in inheritance visibilitymuch like class methodsmetaclass methods are designed to manage class-level data in facttheir roles can overlap--much as metaclasses do in general with class decorators--but metaclass methods are not accessible except through the classand do not require an explicit classmethod class-level data declaration in order to be bound with the class in other wordsmetaclass methods can be thought of as implicit class methodswith limited visibilityclass (type)def (cls)cls cls cls metaclass methodgets class class (metaclass= )yz @classmethod def (cls)return cls class methodgets class ( call metaclass methodvisible to class only creates class data on baccessible to normal instances ( xi yi ( (class methodsends classnot instancevisible to instance (metaclass methodsaccessible through class only attributeerror'bobject has no attribute 'ametaclass methods |
1,942 | just like normal classesmetaclasses may also employ operator overloading to make built-in operations applicable to their instance classes the __getitem__ indexing method in the following metaclassfor exampleis metaclass method designed to process classes themselves--the classes that are instances of the metaclassnot those classesown later instances in factper the inheritance algorithms sketched earliernormal class instances don' inherit names acquired via the metaclass instance relationship at allthough they can access names present on their own classesclass (type)def __getitem__(clsi)return cls data[iclass (metaclass= )data 'spammeta method for processing classesbuilt-ins skip classuse meta explicit names search class meta data descriptors in meta used first [ metaclass instance namesvisible to class only 'sb __getitem__ ( datab data normal inheritance namesvisible to instance and class ('spam''spam' [ typeerror'bobject does not support indexing it' possible to define __getattr__ on metaclass toobut it can be used to process its instance classes onlynot their normal instances--as usualit' not even acquired by class' instancesclass (type)def __getattr__(clsname)return getattr(cls datanameacquired by class getitem but not run same by built-ins class (metaclass= )data 'spamb upper('spamb upper __getattr__ ( upper attributeerror'bobject has no attribute 'upperi __getattr__ attributeerror'bobject has no attribute '__getattr__moving the __getattr__ to metaclass doesn' help with its built-in interception shortcomingsthough in the following continuationexplicit attributes are routed to the metaclasses |
1,943 | to metaclass' __getitem__ in the first example of the section--strongly suggesting that new-style __getattr__ is special case of special caseand further recommending code simplicity that avoids dependence on such boundary casesb data [ append( explicit normal names routed to meta' getattr data [ __getitem__( explicit special names routed to meta' gettarr [ but built-ins skip meta' gettatr too?typeerror'aobject does not support indexing as you can probably tellmetaclasses are interesting to explorebut it' easy to lose track of their big picture in the interest of spacewe'll omit additional fine points here for the purposes of this it' more important to show why you' care to use such tool in the first place let' move on to some larger examples to sample the roles of metaclasses in action as we'll findlike so many tools in pythonmetaclasses are first and foremost about easing maintenance work by eliminating redundancy exampleadding methods to classes in this and the following sectionwe're going to study examples of two common use cases for metaclassesadding methods to classand decorating all methods automatically these are just two of the many metaclass roleswhich unfortunately will consume the space we have left for this againyou should consult the web for more advanced applications these examples are representative of metaclasses in actionthoughand they suffice to illustrate their application moreoverboth give us an opportunity to contrast class decorators and metaclasses-our first example compares metaclassand decorator-based implementations of class augmentation and instance wrappingand the second applies decorator with metaclass first and then with another decorator as you'll seethe two tools are often interchangeableand even complementary manual augmentation earlier in this we looked at skeleton code that augmented classes by adding methods to them in various ways as we sawsimple class-based inheritance suffices if the extra methods are statically known when the class is coded composition via object embedding can often achieve the same effect too for more dynamic scenariosthoughother techniques are sometimes required--helper functions can usually sufficebut metaclasses provide an explicit structure and minimize the maintenance costs of changes in the future exampleadding methods to classes |
1,944 | of manual class augmentation--it adds two methods to two classesafter they have been createdextend manually adding new methods to classes class client def __init__(selfvalue)self value value def spam(self)return self value class client value 'ni?def eggsfunc(obj)return obj value def hamfunc(objvalue)return value 'hamclient eggs eggsfunc client ham hamfunc client eggs eggsfunc client ham hamfunc client ('ni!'print( spam()print( eggs()print( ham('bacon') client (print( eggs()print( ham('bacon')this works because methods can always be assigned to class after it' been createdas long as the methods assigned are functions with an extra first argument to receive the subject self instance--this argument can be used to access state information accessible from the class instanceeven though the function is defined independently of the class when this code runswe receive the output of method coded inside the first classas well as the two methods added to the classes after the factc:\codepy - extend-manual py ni!nini!ni!ni!nibaconham ni?ni?ni?nibaconham this scheme works well in isolated cases and can be used to fill out class arbitrarily at runtime it suffers from potentially major downsidethoughwe have to repeat the metaclasses |
1,945 | onerous to add the two methods to both classesbut in more complex scenarios this approach can be time-consuming and error-prone if we ever forget to do this consistentlyor we ever need to change the augmentationwe can run into problems metaclass-based augmentation although manual augmentation worksin larger programs it would be better if we could apply such changes to an entire set of classes automatically that waywe' avoid the chance of the augmentation being botched for any given class moreovercoding the augmentation in single location better supports future changes--all classes in the set will pick up changes automatically one way to meet this goal is to use metaclasses if we code the augmentation in metaclassevery class that declares that metaclass will be augmented uniformly and correctly and will automatically pick up any changes made in the future the following code demonstratesextend with metaclass supports future changes better def eggsfunc(obj)return obj value def hamfunc(objvalue)return value 'hamclass extender(type)def __new__(metaclassnamesupersclassdict)classdict['eggs'eggsfunc classdict['ham'hamfunc return type __new__(metaclassnamesupersclassdictclass client (metaclass=extender)def __init__(selfvalue)self value value def spam(self)return self value class client (metaclass=extender)value 'ni? client ('ni!'print( spam()print( eggs()print( ham('bacon') client (print( eggs()print( ham('bacon')this timeboth of the client classes are extended with the new methods because they are instances of metaclass that performs the augmentation when runthis version' exampleadding methods to classes |
1,946 | :\codepy - extend-meta py ni!nini!ni!ni!nibaconham ni?ni?ni?nibaconham notice that the metaclass in this example still performs fairly static taskadding two known methods to every class that declares it in factif all we need to do is always add the same two methods to set of classeswe might as well code them in normal superclass and inherit in subclasses in practicethoughthe metaclass structure supports much more dynamic behavior for instancethe subject class might also be configured based upon arbitrary logic at runtimecan also configure class based on runtime tests class metaextend(type)def __new__(metaclassnamesupersclassdict)if sometest()classdict['eggs'eggsfunc elseclassdict['eggs'eggsfunc if someothertest()classdict['ham'hamfunc elseclassdict['ham'lambda *args'not supportedreturn type __new__(metaclassnamesupersclassdictmetaclasses versus class decoratorsround keep in mind again that the prior class decorators often overlap with this metaclasses in terms of functionality this derives from the fact thatclass decorators rebind class names to the result of function at the end of class statementafter the new class has been created metaclasses work by routing class object creation through an object at the end of class statementin order to create the new class although these are slightly different modelsin practice they can often achieve the same goalsalbeit in different ways as you've now seenclass decorators correspond directly to metaclass __init__ methods called to initialize newly created classes decorators have no direct analog to the metaclass __new__ (called to make classes in the first placeor to metaclass methods (used to process instance classes)but many or most use cases for these tools do not require these extra steps because of thisboth tools in principle can be used to manage both instances of class and the class itself in practicethoughmetaclasses incur extra steps to manage instancesand decorators incur extra steps to create new classes hencewhile their roles metaclasses |
1,947 | translate these ideas to code decorator-based augmentation in pure augmentation casesdecorators can often stand in for metaclasses for examplethe prior section' metaclass examplewhich adds methods to class on creationcan also be coded as class decoratorin this modedecorators roughly correspond to the __init__ method of metaclassessince the class object has already been created by the time the decorator is invoked also as for metaclassesthe original class type is retainedsince no wrapper object layer is inserted the output of the followingfile extenddeco pyis the same as that of the prior metaclass codeextend with decoratorsame as providing __init__ in metaclass def eggsfunc(obj)return obj value def hamfunc(objvalue)return value 'hamdef extender(aclass)aclass eggs eggsfunc aclass ham hamfunc return aclass @extender class client def __init__(selfvalue)self value value def spam(self)return self value manages classnot instance equiv to metaclass __init__ client extender(client rebound at end of class stmt @extender class client value 'ni? client ('ni!'print( spam()print( eggs()print( ham('bacon') is client instance client (print( eggs()print( ham('bacon')in other wordsat least in certain casesdecorators can manage classes as easily as metaclasses the converse isn' quite so straightforwardthoughmetaclasses can be used to manage instancesbut only with certain amount of extra magic the next section demonstrates exampleadding methods to classes |
1,948 | as we've just seenclass decorators can often serve the same class-management role as metaclasses metaclasses can often serve the same instance-management role as decoratorstoobut this requires extra code and may seem less natural that isclass decorators can manage both classes and instancesbut don' create classes normally metaclasses can manage both classes and instancesbut instances require extra work that saidcertain applications may be better coded in one or the other for exampleconsider the following class decorator example from the prior it' used to print trace message whenever any normally named attribute of class instance is fetchedclass decorator to trace external instance attribute fetches def tracer(aclass)class wrapperdef __init__(self*args**kargs)self wrapped aclass(*args**kargsdef __getattr__(selfattrname)print('trace:'attrnamereturn getattr(self wrappedattrnamereturn wrapper @tracer class persondef __init__(selfnamehoursrate)self name name self hours hours self rate rate def pay(self)return self hours self rate bob person('bob' print(bob nameprint(bob pay()on decorator on instance creation use enclosing scope name catches all but wrapped delegate to wrapped object person tracer(personwrapper remembers person in-method fetch not traced bob is really wrapper wrapper embeds person triggers __getattr__ when this code is runthe decorator uses class name rebinding to wrap instance objects in an object that produces the trace lines in the following outputc:\codepy - manage-inst-deco py tracename bob tracepay although it' possible for metaclass to achieve the same effectit seems less straightforward conceptually metaclasses are designed explicitly to manage class object creationand they have an interface tailored for this purpose to use metaclass just to manage instanceswe have to also take on responsibility for creating the class too--an metaclasses |
1,949 | file manage-inst-meta pyhas the same effect as the prior decoratormanage instances like the prior examplebut with metaclass def tracer(classnamesupersclassdict)aclass type(classnamesupersclassdictclass wrapperdef __init__(self*args**kargs)self wrapped aclass(*args**kargsdef __getattr__(selfattrname)print('trace:'attrnamereturn getattr(self wrappedattrnamereturn wrapper on class creation call make client class class person(metaclass=tracer)def __init__(selfnamehoursrate)self name name self hours hours self rate rate def pay(self)return self hours self rate make person with tracer wrapper remembers person bob person('bob' print(bob nameprint(bob pay()bob is really wrapper wrapper embeds person triggers __getattr__ on instance creation catches all but wrapped delegate to wrapped object in-method fetch not traced this worksbut it relies on two tricks firstit must use simple function instead of classbecause type subclasses must adhere to object creation protocols secondit must manually create the subject class by calling type manuallyit needs to return an instance wrapperbut metaclasses are also responsible for creating and returning the subject class reallywe're using the metaclass protocol to imitate decorators in this examplerather than vice versabecause both run at the conclusion of class statementin many roles they are just variations on theme this metaclass version produces the same output as the decorator when run livec:\codepy - manage-inst-meta py tracename bob tracepay you should study both versions of these examples for yourself to weigh their tradeoffs in generalthoughmetaclasses are probably best suited to class managementdue to their designclass decorators can manage either instances or classesthough they may not be the best option for more advanced metaclass roles that we don' have space to cover in this book see the web for more metaclass examplesbut keep in mind that some are more appropriate than others (and some of their authors may know less of python than you do!exampleadding methods to classes |
1,950 | the preceding section illustrated that metaclasses incur an extra step to create the class when used in instance management rolesand hence can' quite subsume decorators in all use cases but what about the inverse--are decorators replacement for metaclassesjust in case this has not yet managed to make your head explodeconsider the following metaclass coding alternative too-- class decorator that returns metaclass instancea decorator can call metaclassthough not vice versa without type(class metaclass(type)def __new__(metaclsnamesupersattrdict)print('in __new__:'print([clsnamesuperslist(attrdict keys())]return type __new__(metaclsnamesupersattrdictdef decorator(cls)return metaclass(cls __name__cls __bases__dict(cls __dict__)class ax @decorator class ( ) def (self)return self self in __new__[' '(,)['__qualname__''__doc__'' '' ''__module__'] xb ( ( xi yi (( this nearly proves the equivalence of the two toolsbut really just in terms of dispatch at class construction time againdecorators essentially serve the same role as metaclass __init__ methods because this decorator returns metaclass instancemetaclasses--or at least their type superclass--are still assumed here moreoverthis winds up triggering an additional metaclass call after the class is createdand isn' an ideal scheme in real code--you might as well move this metaclass to the first creation stepclass (ametaclass=metaclass)same effectbut makes just one class stillthere is some tool redundancy hereand decorator and metaclass roles often overlap in practice and although decorators don' directly support the notion of class-level methods in metaclasses discussed earliermethods and state in proxy objects created by decorators can achieve similar effectsthough for space we'll leave this last observation in the suggested explorations column metaclasses |
1,951 | --although metaclass can take the form of simple callable that invokes type to create the class directly and passes it on to the decorator in other wordsthe crucial hook in the model is the type call issued for class construction given thatmetaclasses and class decorators are often functionally equivalentwith varying dispatch protocol modelsdef metaclass(clsnamesupersattrdict)return decorator(type(clsnamesupersattrdict)def decorator(cls)class (ametaclass=metaclass)metas can call decos and vice versa in factmetaclasses need not necessarily return type instance either--any object compatible with the class coder' expectations will do--and this further blurs the decorator/metaclass distinctiondef func(namesupersattrs)return 'spamclass (metaclass=func)attr 'huh? class whose metaclass makes it stringcc upper(('spam''spam'def func(cls)return 'spam@func class cattr 'huh? class whose decorator makes it stringcc upper(('spam''spam'odd metaclass and decorator tricks like these asidetiming often determines roles in practiceas stated earlierbecause decorators run after class is createdthey incur an extra runtime step in class creation roles because metaclasses must create classesthey incur an extra coding step in instance management roles in other wordsneither completely subsumes the other strictly speakingmetaclasses might be functional supersetas they can call decorators during class creationbut metaclasses can also be substantially heavier to understand and codeand many roles intersect completely in practicethe need to take over class creation entirely is probably much less important than tapping into the process in general exampleadding methods to classes |
1,952 | roles that may be bit more typical and practical the next section concludes this with one more common use case--applying operations to class' methods automatically at class creation time exampleapplying decorators to methods as we saw in the prior sectionbecause they are both run at the end of class statementmetaclasses and decorators can often be used interchangeablyalbeit with different syntax the choice between the two is arbitrary in many contexts it' also possible to use them in combinationas complementary tools in this sectionwe'll explore an example of just such combination--applying function decorator to all the methods of class tracing with decoration manually in the prior we coded two function decoratorsone that traced and counted all calls made to decorated function and another that timed such calls they took various forms theresome of which were applicable to both functions and methods and some of which were not the following collects both decoratorsfinal forms into module file for reuse and reference herefile decotools pyassorted decorator tools import time def tracer(func)use functionnot class with __call__ calls else self is decorator instance only def oncall(*args**kwargs)nonlocal calls calls + print('call % to % (callsfunc __name__)return func(*args**kwargsreturn oncall 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 metaclasses |
1,953 | them from the module and code the decoration syntax before each method we wish to trace or timefrom decotools import tracer class person@tracer def __init__(selfnamepay)self name name self pay pay @tracer def giveraise(selfpercent)self pay *( percent@tracer def lastname(self)return self name split()[- bob person('bob smith' sue person('sue jones' print(bob namesue namesue giveraise print(' fsue payprint(bob lastname()sue lastname()giveraise tracer(giverraiseoncall remembers giveraise lastname tracer(lastnameruns oncall(sue runs oncall(bob)remembers lastname when this code is runwe get the following output--calls to decorated methods are routed to logic that intercepts and then delegates the callbecause the original method names have been bound to the decoratorc:\codepy - decoall-manual py call to __init__ call to __init__ bob smith sue jones call to giveraise call to lastname call to lastname smith jones tracing with metaclasses and decorators the manual decoration scheme of the prior section worksbut it requires us to add decoration syntax before each method we wish to trace and to later remove that syntax when we no longer desire tracing if we want to trace every method of classthis can become tedious in larger programs in more dynamic contexts where augmentations depend upon runtime parametersit may not be possible at all it would be better if we could somehow apply the tracer decorator to all of class' methods automatically with metaclasseswe can do exactly that--because they are run when class is constructedthey are natural place to add decoration wrappers to class' methods by exampleapplying decorators to methods |
1,954 | automatically run methods through the decorator and rebind the original names to the results the effect is the same as the automatic method name rebinding of decoratorsbut we can apply it more globallymetaclass that adds tracing decorator to every method of client class from types import functiontype from decotools import tracer class metatrace(type)def __new__(metaclassnamesupersclassdict)for attrattrval in classdict items()if type(attrvalis functiontypeclassdict[attrtracer(attrvalreturn type __new__(metaclassnamesupersclassdictmethoddecorate it make class class person(metaclass=metatrace)def __init__(selfnamepay)self name name self pay pay def giveraise(selfpercent)self pay *( percentdef lastname(self)return self name split()[- bob person('bob smith' sue person('sue jones' print(bob namesue namesue giveraise print(' fsue payprint(bob lastname()sue lastname()when this code is runthe results are the same as before--calls to methods are routed to the tracing decorator first for tracingand then propagated on to the original methodc:\codepy - decoall-meta py call to __init__ call to __init__ bob smith sue jones call to giveraise call to lastname call to lastname smith jones the result you see here is combination of decorator and metaclass work--the metaclass automatically applies the function decorator to every method at class creation timeand the function decorator automatically intercepts method calls in order to print the trace messages in this output the combination "just works,thanks to the generality of both tools metaclasses |
1,955 | the prior metaclass example works for just one specific function decorator--tracing howeverit' trivial to generalize this to apply any decorator to all the methods of class all we have to do is add an outer scope layer to retain the desired decoratormuch like we did for decorators in the prior the followingfor examplecodes such generalization and then uses it to apply the tracer decorator againmetaclass factoryapply any decorator to all methods of class from types import functiontype from decotools import tracertimer def decorateall(decorator)class metadecorate(type)def __new__(metaclassnamesupersclassdict)for attrattrval in classdict items()if type(attrvalis functiontypeclassdict[attrdecorator(attrvalreturn type __new__(metaclassnamesupersclassdictreturn metadecorate class person(metaclass=decorateall(tracer))def __init__(selfnamepay)self name name self pay pay def giveraise(selfpercent)self pay *( percentdef lastname(self)return self name split()[- apply decorator to all bob person('bob smith' sue person('sue jones' print(bob namesue namesue giveraise print(' fsue payprint(bob lastname()sue lastname()when this code is run as it isthe output is again the same as that of the previous examples--we're still ultimately decorating every method in client class with the tracer function decoratorbut we're doing so in more generic fashionc:\codepy - decoall-meta-any py call to __init__ call to __init__ bob smith sue jones call to giveraise call to lastname call to lastname smith jones nowto apply different decorator to the methodswe can simply replace the decorator name in the class header line to use the timer function decorator shown earlierfor exampleapplying decorators to methods |
1,956 | examplewe could use either of the last two header lines in the following when defining our class--the first accepts the timer' default argumentsand the second specifies label textclass person(metaclass=decorateall(tracer))apply tracer class person(metaclass=decorateall(timer()))class person(metaclass=decorateall(timer(label='**')))apply timerdefaults decorator arguments notice that this scheme cannot support nondefault decorator arguments differing per method in the client classbut it can pass in decorator arguments that apply to all such methodsas done here to testuse the last of these metaclass declarations to apply the timerand add the following lines at the end of the script to see the timer' extra informational attributesif using timertotal time per method print('-'* print(' fperson __init__ alltimeprint(' fperson giveraise alltimeprint(' fperson lastname alltimethe new output is as follows--the metaclass wraps methods in timer decorators nowso we can tell how long each and every call takesfor every method of the classc:\codepy - decoall-meta-any py **__init__ **__init__ bob smith sue jones **giveraise **lastname **lastname smith jones metaclasses versus class decoratorsround (and lastas you might expectclass decorators intersect with metaclasses heretoo the following version replaces the preceding example' metaclass with class decorator that isit defines and uses class decorator that applies function decorator to all methods of class although the prior sentence may sound more like zen statement than technical descriptionthis all works quite naturally--python' decorators support arbitrary nesting and combinationsclass decorator factoryapply any decorator to all methods of class from types import functiontype from decotools import tracertimer metaclasses |
1,957 | def decodecorate(aclass)for attrattrval in aclass __dict__ items()if type(attrvalis functiontypesetattr(aclassattrdecorator(attrval)return aclass return decodecorate @decorateall(tracerclass persondef __init__(selfnamepay)self name name self pay pay def giveraise(selfpercent)self pay *( percentdef lastname(self)return self name split()[- not __dict__ use class decorator applies func decorator to methods person decorateall)(personperson decodecorate(personbob person('bob smith' sue person('sue jones' print(bob namesue namesue giveraise print(' fsue payprint(bob lastname()sue lastname()when this code is run as it isthe class decorator applies the tracer function decorator to every method and produces trace message on calls (the output is the same as that of the preceding metaclass version of this example) :\codepy - decoall-deco-any py call to __init__ call to __init__ bob smith sue jones call to giveraise call to lastname call to lastname smith jones notice that the class decorator returns the originalaugmented classnot wrapper layer for it (as is common when wrapping instance objects insteadas for the metaclass versionwe retain the type of the original class--an instance of person is an instance of personnot of some wrapper class in factthis class decorator deals with class creation onlyinstance creation calls are not intercepted at all this distinction can matter in programs that require type testing for instances to yield the original classnot wrapper when augmenting class instead of an instanceclass decorators can retain the original class type the class' methods are not their original functions because they are rebound to decoratorsbut this is likely less important in practiceand it' true in the metaclass alternative as well also note thatlike the metaclass versionthis structure cannot support function decorator arguments that differ per method in the decorated classbut it can handle such exampleapplying decorators to methods |
1,958 | decoratorfor exampleeither of the last two decoration lines in the following will suffice if coded just before our class definition--the first uses decorator argument defaultsand the second provides one explicitly@decorateall(tracerdecorate all with tracer @decorateall(timer()@decorateall(timer(label='@@')decorate all with timerdefaults same but pass decorator argument as beforelet' use the last of these decorator lines and add the following at the end of the script to test our example with different decorator (better schemes are possible on both the testing and timing fronts hereof coursebut we're at endimprove as desired)if using timertotal time per method print('-'* print(' fperson __init__ alltimeprint(' fperson giveraise alltimeprint(' fperson lastname alltimethe same sort of output appears--for every method we get timing data for each and all callsbut we've passed different label argument to the timer decoratorc:\codepy - decoall-deco-any py @@__init__ @@__init__ bob smith sue jones @@giveraise @@lastname @@lastname smith jones finallyit' possible to combine decorators such that each runs per method callbut it will likely require changes to those we've coded here as isnesting calls to them directly winds up tracing or timing the other' creation-time applicationlisting the two on separate lines results in tracing or timing the other' wrapper before running the original methodand metaclasses seem to fare no better on this front@decorateall(tracer(timer(label='@@'))class persontraces applying the timer @decorateall(tracer@decorateall(timer(label='@@')class persontraces oncall wrappertimes methods @decorateall(timer(label='@@') metaclasses |
1,959 | class persontimes oncall wrappertraces methods pondering this further will have to remain suggested study--both because we're out of space and timeand because this may quite possibly be illegal in some statesas you can seemetaclasses and class decorators are not only often interchangeablebut also commonly complementary both provide advanced but powerful ways to customize and manage both class and instance objectsbecause both ultimately allow you to insert code into the class creation process although some more advanced applications may be better coded with one or the otherthe way you choose or combine these two tools in many cases is largely up to you summary in this we studied metaclasses and explored examples of them in action metaclasses allow us to tap into the class creation protocol of pythonin order to manage or augment user-defined classes because they automate this processthey may provide better solutions for api writers than manual code or helper functionsbecause they encapsulate such codethey may minimize maintenance costs better than some other approaches along the waywe also saw how the roles of class decorators and metaclasses often intersectbecause both run at the conclusion of class statementthey can sometimes be used interchangeably class decorators and metaclasses can both be used to manage both class and instance objectsthough each tool may present tradeoffs in some use cases since this covered an advanced topicwe'll work through just few quiz questions to review the basics (candidlyif you've made it this far in on metaclassesyou probably already deserve extra credit!because this is the last part of the bookwe'll forgo the end-of-part exercises be sure to see the appendixes that follow for python changesthe solutions to the prior partsexercisesand morethe last of these includes sampling of typical application-level programs for self-study once you finish the quizyou've officially reached the end of this book' technical material the next and final offers some brief closing thoughts to wrap up the book at large 'll see you there in the python benediction after you work through this final quiz test your knowledgequiz what is metaclass how do you declare the metaclass of class how do class decorators overlap with metaclasses for managing classestest your knowledgequiz |
1,960 | would you rather count decorators or metaclasses amongst your weaponry(and please phrase your answer in terms of popular monty python skit test your knowledgeanswers metaclass is class used to create class normal new-style classes are instances of the type class by default metaclasses are usually subclasses of the type classwhich redefines class creation protocol methods in order to customize the class creation call issued at the end of class statementthey typically redefine the methods __new__ and __init__ to tap into the class creation protocol metaclasses can also be coded other ways--as simple functionsfor example--but they are always responsible for making and returning an object for the new class metaclasses may have methods and data to provide behavior for their classes too--and constitute secondary pathway for inheritance search--but their attributes are accessible only to their class instancesnot to their instance' instances in python xuse keyword argument in the class header lineclass (meta class=min python xuse class attribute instead__metaclass__ in xthe class header line can also name normal superclasses before the metaclass keyword argumentin you generally should derive from object toothough this is sometimes optional because both are automatically triggered at the end of class statementclass decorators and metaclasses can both be used to manage classes decorators rebind class name to callable' result and metaclasses route class creation through callablebut both hooks can be used for similar purposes to manage classesdecorators simply augment and return the original class objects metaclasses augment class after they create it decorators may have slight disadvantage in this role if new class must be definedbecause the original class has already been created because both are automatically triggered at the end of class statementwe can use both class decorators and metaclasses to manage class instancesby inserting wrapper (proxyobject to catch instance creation calls decorators may rebind the class name to callable run on instance creation that retains the original class object metaclasses can do the samebut may have slight disadvantage in this rolebecause they must also create the class object our chief weapon is decorators decorators and metaclasses metaclasses and decorators our two weapons are metaclasses and decorators and ruthless efficiency our three weapons are metaclassesdecoratorsand ruthless efficiency and an almost fanatical devotion to python our four no amongst our weapons amongst our weaponry are such elements as metaclassesdecorators 'll come in again metaclasses |
1,961 | all good things welcome to the end of the booknow that you've made it this fari want to say few words in closing about python' evolution before turning you loose on the software field this topic is subjective by natureof coursebut vital to all python users nonetheless you've now had chance to see the entire language yourself--including some advanced features that may seem at odds with its scripting paradigm though many will understandably accept this as status quoin an open source project it' crucial that some ask the "whyquestions too ultimatelythe trajectory of the python story--and its true conclusion--is at least in part up to you the python paradox if you've read this bookor reasonable subsets of ityou should now be able to weigh python' tradeoffs fairly as you've seenpython is powerfulexpressiveand even fun programming languagewhich will serve as an enabling technology for wherever you choose to go next at the same timeyou've also seen that today' python is something of paradoxit has expanded to incorporate tools that many consider both needlessly redundant and curiously advanced--and at rate that appears to be only accelerating for my partas one of python' earliest advocatesi've watched it morph over the years from simple to sophisticated toolwith steadily shifting scope by most measuresit seems to have grown at least as complex as other languages that drove many of us to python in the first place and just as in those other languagesthis has inevitably fostered growing culture in which obscurity is badge of honor that' as contrary to python' original goals as it could be run an import this in any python interactive session to see what mean--the creed 've quoted from repeatedly in this book in contexts where it was clearly violated on many levelsits core ideals of explicitnesssimplicityand lack of redundancy have been either naively forgotten or carelessly abandoned |
1,962 | some of the same terms used in the perl sidebar of while python still has much to offerthis trend threatens to negate much of its perceived advantageas the next section explains on "optionallanguage features included quote near the start of the prior about metaclasses not being of interest to of python programmersto underscore their perceived obscurity that statement is not quite accuratethoughand not just numerically so the quote' author is noted python contributor and friend from the early days of pythonand don' mean to pick on anyone unfairly moreoveri've often made such statements about language feature obscurity myself--in the various editions of this very bookin fact the problemthoughis that such statements really apply only to people who work alone and only ever use code that they've written themselves as soon as an "optionaladvanced language feature is used by anyone in an organizationit is no longer optional --it is effectively imposed on everyone in the organization the same holds true for externally developed software you use in your systems--if the software' author uses an advanced or extraneous language featureit' no longer entirely optional for youbecause you have to understand the feature to reuse or change the code this observation applies to all the advanced topics covered in this bookincluding those listed as "magichooks near the beginning of the prior and many othersgeneratorsdecoratorsslotspropertiesdescriptorsmetaclassescontext managersclosuressupernamespace packagesunicodefunction annotationsrelative importskeyword-only argumentsclass and static methodsand even obscure applications of comprehensions and operator overloading if any person or program you need to work with uses such toolsthey automatically become part of your required knowledge base too to see just how daunting this can beone need only consider ' new-style inheritance procedure-- horrifically convoluted model that can make descriptors and metaclasses prerequisite to understanding even basic name resolution ' super similarly ups the intellectual ante--imposing an obscenely implicit and artificial mro algorithm on readers of any code that uses this tool the net effect of such over-engineering is to either escalate learning requirements radicallyor foster user base that only partially understands the tools they employ this is obviously less than ideal for those hoping to use python in simpler waysand contradictory to the scripting motif all good things |
1,963 | this observation also applies to the many redundant features we've seensuch as ' str format method and ' with statement--tools borrowed from other languagesand overlapping with others long present in python when programmers use multiple ways to achieve the same goalall become required knowledge let' be honestpython has grown rife with redundancy in recent years as suggested in the preface--and as you've now seen first-hand--today' python world comes replete with all the functional duplications and expansions chronicled in table - among others we've seen in this book table - sampling of redundancy and feature explosion in python category specifics major paradigms proceduralfunctionalobject-oriented incompatible lines and xwith new-style classes in both string formatting tools expressionstr formatstring template attribute accessor tools __getattr____getattribute__propertiesdescriptors finalization statements try/finallywith varieties of comprehension listgeneratorsetdictionary class augmentation tools function callsdecoratorsmetaclasses kinds of methods instancestaticclassmetaclass attribute storage systems dictionariesslots flavors of imports modulepackagepackage relativenamespace package superclass dispatch protocols direct callssuper mro assignment statement forms basicmultinameaugmentedsequencestarred types of functions normalgenerator function argument forms basicname=value*pargs**kargskeyword-only class behavior sources superclassesmetaclasses state retention options classesclosuresfunction attributesmutables class models classic new-style in xmandated new-style in unicode models optional in xmandated in pydoc modes gui clientrequired all-browser in recent byte code storage schemes original__pycache__ only in recent if you care about pythonyou should take moment to browse this table it reflects virtual explosion in functionality and toolbox size-- concepts that are all fair game for newcomers most of its categories began with just one original member in pythonmany were expanded in part to imitate other languagesand only the last few can be the python paradox |
1,964 | programmers 've stressed avoiding unwarranted complexity in this bookbut in practiceboth advanced and new tools tend to encourage their own adoption--often for no better reason than programmer' personal desire to demonstrate prowess the net result is that much python code today is littered with these complex and extraneous tools that isnothing is truly "optionalif nothing is truly optional complexity versus power this is why some python old-timers (myself includedsometimes worry that python seems to have grown larger and more complex over time new features added by veteransconvertsand even amateurs may have raised the intellectual bar for newcomers although python' core ideaslike dynamic typing and built-in typeshave remained essentially the sameits advanced additions can become required reading for any python programmer chose to cover these topics here for this reasondespite their omission in early editions it' not possible to skip the advanced stuff if it' in code you have to understand on the other handas mentioned in to most observers python is still noticeably simpler than most of its contemporariesand perhaps only as complex as its many roles require though it' acquired many of the same tools as javac#and ++they tend to be lighter weight in the context of dynamically typed scripting language for all its growth over the yearspython is still relatively easy to learn and use when compared to the alternativesand new learners can often pick up advanced topics as needed and franklyapplication programmers tend to spend most of their time dealing with libraries and extensionsnot advanced and sometimes-arcane language features for instancethe book programming python-- follow-up to this one--deals mostly with the marriage of python to application libraries for tasks such as guisdatabasesand the webnot with esoteric language tools (though unicode still forces itself onto many stagesand the odd generator expression and yield crop up along the waymoreoverthe flipside of this growth is that python has become more powerful when used welltools like decorators and metaclasses are not only arguably "cool,but allow creative programmers to build more flexible and useful apis for other programmers to use as we've seenthey can also provide good solutions to problems of encapsulation and maintenance simplicity versus elitism whether this justifies the potential expansion of required python knowledge is up to you to decide for better or worsea person' skill level often decides this issue by default--more advanced programmers like more advanced tools and tend to forget all good things |
1,965 | programmers also understand that simplicity is good engineeringand advanced tools should be used only when warranted this is true in any programming languagebut especially in one like python that is frequently exposed to new or novice programmers as an extension tool and if you're still not buying thiskeep in mind that many people using python are not comfortable with even basic oop trust me on thisi've met thousands of them although python was never trivial subjectthe reports from the software trenches are very clear on this pointunwarranted added complexity is never welcome featureespecially when it is driven by the personal preferences of an unrepresentative few whether intended or notthis is often understandably perceived as elitism-- mindset that is both unproductive and rudeand has no place in tool as widely used as python this is also social issueof courseand pertains as much to individual programmers as to language designers in the "real worldwhere open source software is measuredthoughpython-based systems that require their users to master the nuances of metaclassesdescriptorsand the like should probably scale their market expectations accordingly hopefullyif this book has done its jobyou'll find the importance of simplicity in programming to be one of its most important and lasting takeaways closing thoughts so there you have it--some observations from someone who has been usingteachingand advocating python for two decadesand still wishes nothing but the best for its future none of these concerns are entirely newof course indeedthe growth of this very book over the years seems testament to the effect of python' own growth--if not an ironic eulogy to its original conception as tool that would simplify programming and be accessible to both experts and nonspecialists alike judging by language heft alonethat dream seems to have been either neglected or abandoned entirely that saidpython' present rise in popularity seems to show no signs of abating-- powerful counterargument to complexity concerns today' python world may be understandably less concerned with its original and perhaps idealistic goals than with applying its present form in their work python gets many job done in the practical world of complex programming requirementsand this is still ample cause to recommend it for many tasks original goals asidemass appeal does qualify as one form of successthough one whose significance will have to await the verdict of time if you're interested in musing further over python' evolution and learning curvei wrote more in-depth article in on such thingsanswer me these questions three available online at important pragmatic questions that are crucial to python' futureand deserve more attention than 've given here but these are highly subjective issuesthis is not philosophy textand this book has already exceeded its page-count targets the python paradox |
1,966 | must be formed anew by each wave of newcomers hope the wave you ride in will have as much common sense as fun while plotting python' future where to go from here and that' wrapfolks you've officially reached the end of this book now that you know python inside and outyour next stepshould you choose to take itis to explore the librariestechniquesand tools available in the application domains in which you work because python is so widely usedyou'll find ample resources for using it in almost any application you can think of--from guisthe weband databases to numeric programmingroboticsand system administration see and your favorite web browser for pointers to popular tools and topics this is where python starts to become truly funbut this is also where this book' story endsand othersbegin for pointers on where to turn after this booksee the recommended follow-up texts mentioned in the preface hope to see you in an applications programming domain soon good luck with your journey and of course"always look on the bright side of life!encoreprint your own completion certificateand one last thingin lieu of exercises for this part of the booki' going to post bonus script here for you to study and run on your own can' provide completion certificates for readers of this book (and the certificates would be worthless if could)but can include an arguably cheesy python script that does--the following filecertificate pyis python and script that creates simple book completion certificate in both text and html file formsand pops them up in web browser on your machine by default #!/usr/bin/python ""file certificate pya python and script generate bare-bones class completion certificateprintedand saved in text and html files displayed in web browser ""from __future__ import print_function compatibility import timesyswebbrowser if sys version_info[ = input raw_input import cgi htmlescape cgi escape elseimport html all good things compatibility |
1,967 | maxline browser true saveto 'certificate txttemplate ""% for seperator lines display in browser output filenames ===official certificate <==date% this certifies that\ % has survived the massive tome\ % and is now entitled to all privileges thereofincluding the right to proceed on to learning how to develop web sitesdesktop guisscientific modelsand assorted appswith the possible assistance of follow-up applications books such as programming python (shameless plug intended--mark lutzinstructor (notecertificate void where obtained by skipping ahead % ""interactsetup for in 'congratulations!upper()print(cend='sys stdout flush(else some shells wait for \ time sleep( print(date time asctime(name input('enter your name'strip(or 'an unknown readersept '*maxline book 'learning python th editionmake text file version file open(saveto' 'text template (septdatenamebookseptprint(textfile=filefile close(make html file version htmlto saveto replace(txt'html'file open(htmlto' 'encoreprint your own completion certificate |
1,968 | tags tags replace('===>'''tags tags replace(''insert few tags tags tags split('\ 'line-by-line mods tags ['if line ='else line for line in tagstags ['%shtmlescape(lineif line[: ='\telse line for line in tagstags '\njoin(tagslink '\ \ % \nlink tags 'tags foot 'print(tagsfile=filefile close(display results print('[file% ]savetoend=''print('\ open(savetoread()if browserwebbrowser open(savetonew=truewebbrowser open(htmltonew=falseif sys platform startswith('win')input('[press enter]'keep window open if clicked on windows run this script on your ownand study its code for summary of some of the ideas we've covered in this book fetch it from this book' website described in the preface if you wish you won' find any descriptorsdecoratorsmetaclassesor super calls in this codebut it' typical python nonetheless when runit generates the web page captured in the fully gratuitous figure - this could be much more grandioseof coursesee the web for pointers to python support for pdfs and other document tools such as sphinx surveyed in but heyif you've made it to the end of this bookyou deserve another joke or two all good things |
1,969 | encoreprint your own completion certificate |
1,970 | appendixes |
1,971 | installation and configuration this appendix provides additional installation and configuration details as resource for people new to these topics it' located here because not all readers will need to deal with these subjects up front because it covers some peripheral topics such as environment variables and command-line argumentsthoughthis material probably merits at least quick scan for most readers installing the python interpreter because you need the python interpreter to run python scriptsthe first step in using python is usually installing python unless one is already available on your machineyou'll need to fetchinstalland possibly configure recent version of python on your computer you'll only need to do this once per machineand if you will be running frozen binary (described in or self-installing systemyour setup tasks may be trivial or null is python already presentbefore you do anything elsecheck whether you already have recent python on your machine if you are working on linuxmac os xor some unix systemspython is probably already installed on your computerthough it may be one or two releases behind the cutting edge here' how to checkon windows and earliercheck whether there is python entry in the start button' all programs menu (at the bottom left of the screenon windows look for python in start screen tileyour search toolthe "all appsdisplay on your start screenor file explorer in desktop mode (more on windows in an upcoming sidebaron mac os xopen terminal window (applications-utilities-terminaland type python at the prompt pythonidleand its tkinter gui toolkit are standard components of this system |
1,972 | see what happens alternativelytry searching for "pythonin the usual places --/usr/bin/usr/local/binetc as on macspython is standard part of linux systems if you find pythonmake sure it' recent version although any recent python will do for most of this textthis edition focuses on python and specificallyso you may want to install one of these to run some of the examples in this book speaking of versionsper the prefacei recommend starting out with python or later if you're learning python anew and don' need to deal with existing codeotherwiseyou should generally use python some popular python-based systems still use older releasesthough ( and even are still widespread)so if you're working with existing systems be sure to use version relevant to your needsthe next section describes locations where you can fetch variety of python versions where to get python if there is no python on your machineyou will need to install one yourself the good news is that python is an open source system that is freely available on the web and very easy to install on most platforms you can always fetch the latest and greatest standard python release from python orgpython' official website look for the downloads link on that pageand choose release for the platform on which you will be working you'll find prebuilt self-installer files for windows (run to install)installer disk images for mac os (installed per mac conventions)the full source code distribution (typically compiled on linuxunixor os machines to generate an interpreter)and more although python is standard on linux these daysyou can also find rpms for linux on the web (unpack them with rpmpython' website also has links to pages where versions for other platforms are maintainedeither at python org orgitself or offsite for exampleyou can find third-party python installers for google' androidas well as apps to install python on apple' ios google web search is another great way to find python installation packages among other platformsyou can find python prebuilt for ipodspalm handheldsnokia cell phonesplaystation and pspsolarisas/ and windows mobilethough some of these are typically few releases behind the curve if you find yourself pining for unix environment on windows machineyou might also be interested in installing cygwin and its version of python (see comcygwin is gpl-licensed library and toolset that provides full unix functionality on windows machinesand it includes prebuilt python that makes use of all the unix tools provided appendix ainstallation and configuration |
1,973 | with some products and computer systemsand enclosed with some other python books these tend to lag behind the current release somewhatbut usually not seriously so in additionyou can find python in some free and commercial development bundles at this writingthis alternative distributions category includesactivestate activepython package that combines python with extensions for scientificwindowsand other development needsincluding pywin and the pythonwin ide enthought python distribution combination of python and host of additional libraries and tools oriented toward scientific computing needs portable python blend of python and add-on packages configured to run directly from portable device pythonxy scientific-oriented python distribution based on qt and spyder conceptive python sdk bundle targeted at businessdesktopand database applications pyimsl studio commercial distribution for numerical analysis anaconda python distribution for analysis and visualization of large data sets this set is prone to changeso search the web for details on all of the aboveand others some of these are freesome are notand some have both free and nonfree versions all combine the standard python freely available at finallyif you are interested in alternative python implementationsrun web search to check out jython (the python port to the java environmentand ironpython (python for the #net world)both of which are described in installation of these systems is beyond the scope of this book installation steps once you've downloaded pythonyou need to install it installation steps are very platform-specificbut here are few pointers for the major python platforms (biased in volume toward windowsonly because that is the platform where most python newcomers are likely to encounter the language first)installing the python interpreter |
1,974 | for windows (including xpvista and )python comes as self-installer msi program file--simply double-click on its file iconand answer yes or next at every prompt to perform default install the default install includes python' documentation set and support for tkinter (tkinter in python xguisshelve databasesand the idle development gui python and are normally installed in the directories :\python and :\python though this can be changed at install time for convenienceon windows and earlier python shows up after the install in the start button' all programs menu (see ahead for windows notespython' menu there has five entries that give quick access to common tasksstarting the idle user interfacereading module documentationstarting an interactive sessionreading python' standard manualsand uninstalling most of these options involve concepts explored in detail elsewhere in this text when installed on windowspython also automatically uses filename associations to register itself to be the program that opens python files when their icons are clicked ( program launch technique described in it is also possible to build python from its source code on windowsbut this is not commonly done so we'll skip the details here (see python orgthree additional install-related notes for windows usersfirstbe sure to see the next appendix for an introduction to the new windows launcher shipped with it changes some of the rules for installationfile associationsand command linesbut can be an asset if you have multiple python versions on your computer ( both and xper appendix bpython ' msi installer also has an option to set your path variable to include python' directory secondwindows users should see the sidebar in this appendix "using python on windows on page standard python installs and works the same on windows where it runs in desktop modebut you won' get the start button menu described earlierand the tablet interface on top is not yet directly supported finallysome windows vista users may run into install issues related to security features this seems to have been resolved over time (and vista is relatively rare these days)but if running the msi installer file directly doesn' work as expectedit' probably because msi files are not true executables and do not correctly inherit administrator permissions (they run per the registryto fixrun the installer from command line with appropriate permissionsselect command promptchoose "run as administrator,cd to the directory where your python msi file residesand run the msi installer with command line of the formmsiexec / pythonmsi linux for linuxif python or your desired flavor of it is not already presentyou can probably obtain it as one or more rpm fileswhich you unpack in the usual way (consult the rpm manpage for detailsdepending on which rpms you download appendix ainstallation and configuration |
1,975 | and the idle environment because linux is unix-like systemthe next paragraph applies as well unix for unix systemspython is usually compiled from its full source code distribution this usually only requires you to unpack the file and run simple config and make commandspython configures its own build procedure automaticallyaccording to the system on which it is being compiled howeverbe sure to see the package' readme file for more details on this process because python is open sourceits source code may be used and distributed free of charge on other platforms the installation details can differ widelybut they generally follow the platform' normal conventions for exampleinstalling the "pippyport of python for palmos required hotsync operation with your pdaand python for the sharp zaurus linux-based pda was one or more ipk fileswhich you simply ran to install (these likely still workthough finding the devices today may be logistical challenge!more recentlypython can be installed and used on android and ios platforms toobut installation and usage techniques are too platform-specific to cover here for additional install procedures and the latest on available portstry both python' website and web search using python on windows windows was released as this edition was being written as mentioned in the prefacethis book was developed on both windows and but mostly under windows because the choice is irrelevant to almost everything in this book--both python and presently work only in desktop mode on windows but install and run there the same as in windows vistaxpand others once you navigate past the tabletlike layer at the topusage is almost entirely as before the only notable exception to this is windows ' lack of start button menu in desktop mode you don' get the nice menu of python options automaticallythough you can simulate it manually although this story is prone to change (and you should take this sidebar as an early report)here are few windows usage notes at this writingthe standard python windows msi installer program installs python on windows correctlyand exactly as in the pastyou get the same filename associations for icon clicksaccess from command linesand so on the installer also creates start screen button on windows but python itself runs in windows ' desktop modewhich is essentially the same as windows without start button menu for examplethe windows start screen button created by the python install simply switches control to desktop mode to open python interactive shell the upside to this is that all existing python software works on windows ' desktop just as before one downside is that you'll need to create shortcuts for the user-friendly start button menu items created automatically on former windows versions this ininstalling the python interpreter |
1,976 | this isn' showstopper--you can emulate the former start button menu' items with either tiles on the start screen or shortcuts on the desktop taskbar to do soyou might look up these tools in variety of waysby navigating to their corresponding filename in file exploreropened by rightclicking the screen' lower-left corner by searching for their name in the search "charm,opened by pulling down the screen' top-right corner by finding their entry after right-clicking on the start screen to open the all apps displaywhich is reminiscent of the former start button menus by locating their tiles on your start screenif they have any for exampleyou can locate idle by navigating to the file idle py in :\python \libby searching on "idle,by finding idle in "all apps,or by clicking start screen tile if one exists you can find python itself in the same ways (and probably othersthis isn' quite as nice as the original start button menus out of the boxbut it suffices probably the bigger potential downside on windows is that while python runs fine in desktop modeit doesn' yet have an official port to run as start screen style "app that isstandard python does not yet run programs in the winrt (formerly known as metroenvironment--the tile-based media consumption layer that appears first when you start windows and before you can click your way to the desktop this may be temporary statethoughas number of options either already exist or are being actively explored on one frontit' not impossible that python' installer may be enhanced for windows ' nondesktop mode there has already been work on porting python to run as start screen "app,though this may appear as separate installer package due to differences in the underlying libraries (in shortwinrt runs programs in classic "sandboxmodelwith restricted subset of the libraries available normallyon other frontsthe #net-based ironpython system may offer additional windows "appdevelopment optionsand some of python' major gui toolkits such as tkinterwxpythonand pyqt could eventually provide portability to the windows "appsenvironment as well the qt library underlying the latter of these seems to have already showed some progress in this department for nowexisting python software runs fine in windows ' desktop mode unchanged developing or running python code in the start screen "appsenvironment will likely require special handling and platform-specific apis not unlike those required to run python on other tabletand phone-oriented platforms based on google' android and apple' ios (iphone and ipadoperating systems also note that much of this sidebar applies to window but not windows rt the latter does not run third-party desktop mode applications directlyand may need to await sanctioned python installer that supports the winrt "appapi in general appendix ainstallation and configuration |
1,977 | in both windows and python' installer for it for nowa simple tile click or windowskey press to hop into desktop mode will allow most python programmers on windows to safely ignore the tablet-like interface on top--at least until "appstrounce "programsaltogether configuring python after you've installed pythonyou may want to configure some system settings that impact the way python runs your code (if you are just getting started with the languageyou can probably skip this section completelythere is usually no need to specify any system settings for basic programs generally speakingparts of the python interpreter' behavior can be configured with environment variable settings and command-line options in this sectionwe'll take brief look at bothbut be sure to see other documentation sources for more details on the topics we introduce here python environment variables environment variables--known to some as shell variablesor dos variables--are system-wide settings that live outside python and thus can be used to customize the interpreter' behavior each time it is run on given computer python recognizes handful of environment variable settingsbut only few are used often enough to warrant explanation here table - summarizes the main python-related environment variable settings (you'll find information on others in python reference resourcestable - important environment variables variable role path (or pathsystem shell search path (for finding "python"pythonpath python module search path (for importspythonstartup path to python interactive startup file tcl_librarytk_library gui extension variables (tkinterpy_pythonpy_python py_python windows launcher defaults (see appendix bthese variables are straightforward to usebut here are few pointers lest that seem too sarcastici should note that windows may address some launch screen and start button (if not menuconcerns per late-breaking rumorsand this edition' new windows sidebar replaces one in prior editions that discussed windows vista issue any similarities you might deduce from that are officially coincidental configuring python |
1,978 | the path setting lists set of directories that the operating system searches for executable programswhen they are invoked without full directory path it should normally include the directory where your python interpreter lives (the python program on unixor the python exe file on windowsyou don' need to set this variable at all if you are willing to work in the directory where python residesor type the full path to python in command lines on windowsfor instancethe path is irrelevant if you run cd :\python before running any code (to change to the directory where python lives--though you shouldn' generally store your own code in this directory per )or always type :\python \python instead of just python (giving full pathalso note that path settings are mostly for launching programs from command linesthey are usually irrelevant when launching via icon clicks and ides--the former uses filename associationsand the latter uses built-in mechanismsand doesn' generally require this configuration step see also appendix for details on ' automatic path setting option at install time pythonpath the pythonpath setting serves role similar to paththe python interpreter consults the pythonpath variable to locate module files when you import them in program if usedthis variable is set to platform-dependent list of directory namesseparated by colons on unix and semicolons on windows this list normally includes just your own source code directories its content is merged into the sys path module import search pathalong with the script' container directoryany pth path file settingsand standard library directories you don' need to set this variable unless you will be performing cross-directory imports--because python always searches the home directory of the program' toplevel file automaticallythis setting is required only if module needs to import another module that lives in different directory see also the discussion of pth path files later in this appendix for an alternative to pythonpath for more on the module search pathrefer to pythonstartup if pythonstartup is set to the pathname of file of python codepython executes the file' code automatically whenever you start the interactive interpreteras though you had typed it at the interactive command line this is rarely used but handy way to make sure you always load certain utilities when working interactivelyit saves an import each time you start python session tkinter settings if you wish to use the tkinter gui toolkit (named tkinter in )you might have to set the two gui variables in the last line of table - to the names of the source library directories of the tcl and tk systems (much like pythonpathhoweverthese settings are not required on windows systems (where tkinter support is installed alongside python)and are usually not required on mac os and linux appendix ainstallation and configuration |
1,979 | nonstandard directories (see python org' download page for more detailspy_pythonpy_python py_python these settings are used to specify default pythons when you are using the new (at this writingwindows launcher that ships with python and is available separately for other versions since we'll be exploring the launcher in appendix bi'll postpone further details here note that because these environment settings are external to python itselfwhen you set them is usually irrelevantthis can be done before or after python is installedas long as they are set the way you require before python is actually run--be sure to restart your python ides and interactive sessions after making such changes if you want them to apply tkinter and idle guis on linux and macs the idle interface described in is python tkinter gui program the tkinter module (named tkinter in xis gui toolkit that is automatically installed with standard python on windowsand is an inherent part of mac os and most linux installations on some linux systemsthoughthe underlying gui library may not be standard installed component to add gui support to your python on linux if neededtry running command line of the form yum tkinter to automatically install tkinter' underlying libraries this should work on linux distributions (and some other systemson which the yum installation program is availablefor otherssee your platform' installation documentation as also discussed in on mac os idle probably lives in the macpython (or python mfolder of your applications folder (along with pythonlauncherused for starting programs with clicks in finder)but be sure to see the download page at python org if idle has problemsyou may need to install an update on some os versions (see how to set configuration options the way to set python-related environment variablesand what to set them todepends on the type of computer you're working on and againremember that you won' necessarily have to set these at all right awayespecially if you're working in idle (described in and save all your files in the same directoryconfiguration is probably not required up front but supposefor illustrationthat you have generally useful module files in directories called utilities and package somewhere on your machineand you want to be able to import these modules from files located in other directories that isto load file called configuring python |
1,980 | another file in another directoryimport spam to make this workyou'll have to configure your module search path one way or another to include the directory containing spam py here are few tips on this process using pythonpath as an exampledo the same for other settings like path as needed (though can set path automaticallysee appendix bunix/linux shell variables on unix systemsthe way to set environment variables depends on the shell you use under the csh shellyou might add line like the following in your cshrc or login file to set the python module search pathsetenv pythonpath /usr/home/pycode/utilities:/usr/lib/pycode/package this tells python to look for imported modules in two user-defined directories alternativelyif you're using the ksh shellthe setting might instead appear in your kshrc file and look like thisexport pythonpath="/usr/home/pycode/utilities:/usr/lib/pycode/package other shells may use different (but analogoussyntax dos variables (and older windowsif you are using ms-dos or some now fairly old flavors of windowsyou may need to add an environment variable configuration command to your :\autoexec bat fileand reboot your machine for the changes to take effect the configuration command on such machines has syntax unique to dosset pythonpath= :\pycode\utilities; :\pycode\package you can type such command in dos console windowtoobut the setting will then be active only for that one console window changing your bat file makes the change permanent and global to all programsthough this technique has been superseded in recent years by that described in the next section windows environment variable gui on all recent versions of windows (including xpvista and )you can instead set pythonpath and other variables via the system environment variable gui without having to edit filestype command linesor reboot select the control panel (in your start button in windows and earlierand in the desktop mode' settings "charmon windows )choose the system iconpick the advanced settings tab or linkand click the environment variables button at the bottom to edit or add new variables (python path is usually new user variableuse the same variable name and values syntax appendix ainstallation and configuration |
1,981 | verify operations along the way you do not need to reboot your machine after thisbut be sure to restart python if it' open so that it picks up your changes--it configures its import search path at startup time only if you're working in windows command prompt windowyou'll probably need to restart that to pick up your changes as well windows registry if you are an experienced windows useryou may also be able to configure the module search path by using the windows registry editor to open this tooltype regedit in the start-run interface on some windowsin the search field at the bottom of the start button display on windows and in command prompt window on windows and others (among other routesassuming the typical registry tool is available on your machineyou can then navigate to python' entries and make your changes this is delicate and error-prone procedurethoughso unless you're familiar with the registryi suggest using other options (indeedthis is akin to performing brain surgery on your computerso be careful!path files finallyif you choose to extend the module search path with pth path file instead of the pythonpath variableyou might instead code text file that looks like the following on windows ( file :\python \mypath pth) :\pycode\utilities :\pycode\package its contents will differ per platformand its container directory may differ per both platform and python release python locates this file automatically when it starts up directory names in path files may be absoluteor relative to the directory containing the path filemultiple pth files can be used (all their directories are added)and pth files may appear in various automatically checked directories that are platformand version-specific in generala python release numbered python typically looks for path files in :\pythonnm and :\pythonnm\lib\site-packages on windowsand in usr/local/lib/pythonn /site-packages and /usr/local/lib/site-python on unix and linux see for more on using path files to configure the sys path import search path because environment settings are often optionaland because this isn' book on operating system shellsi'll defer to other sources for further details consult your system shell' manpages or other documentation for more informationand if you have trouble figuring out what your settings should beask your system administrator or another local expert for help configuring python |
1,982 | when you start python from system command line ( shell promptor command prompt window)you can pass in variety of option flags to control how python runs your code unlike the system-wide environment variables of the prior sectioncommand-line arguments can be different each time you run script the complete form of python command-line invocation in looks like this ( is roughly the samewith few differences described ahead)python [-bbdehioqssuvvwxx[- command - module-name script [argsthe rest of this section briefly demonstrates some of python' most commonly used arguments for more details on available command-line options not covered heresee the python manuals or reference texts or better yetask python itself--run command line form like thisc:\codepython - to request python' help displaywhich documents all available command-line options if you deal with complex command linesbe sure to also check out the standard library modules in this domainthe original getopthe newer argparseand the now-deprecated (since optparsewhich support more sophisticated command-line processing also see python' library manuals and other references for more on the pdb and profile modules the following tour deploys running script files with arguments most command lines make use of only the script and args parts of the last section' python command-line formatto run program' source file with arguments to be used by the program itself to illustrateconsider the following script-- text file named showargs pycreated in directory :\code or another of your choosing--which prints the command-line arguments made available to the script as sys argva python list of python strings (if you don' yet know how to create or run python script filessee the full coverage in and we're interested only in command-line arguments here)file showargs py import sys print(sys argvin the following command lineboth python and showargs py can also be complete directory paths--the former is assumed to be on your path hereand the latter is assumed to be in the current directory the three arguments ( -cmeant for the script show up in the sys argv list and can be inspected by your script' code therethe first item in sys argv is always the script file' namewhen it is knownc:\codepython showargs py - ['showargs py'' '' ''- ' appendix ainstallation and configuration most commonrun script file |
1,983 | display in quotes running code given in arguments and standard input other code format specification options allow you to give python code to be run on the command line itself (- )and accept code to run from the standard input stream ( means read from pipe or redirected input stream fileterms also defined in full elsewhere in this text) :\codepython - "print( * ) read code from command argument :\codepython - "import showargs['- 'import file to run its code :\codepython showargs py - ['-'' '' ''- 'read code from standard input :\codepython - showargs py ['-'' '' ''- 'same effect as prior line running modules on the search path the - code specification locates module on python' module search path and then runs it as top-level script (as module __main__that isit looks up script the same way import operations dousing the directory list normally known as sys pathwhich includes the current directorypythonpath settingsand standard libraries leave off the pysuffix hereas the filename is treated as module :\codepython - showargs - [' :\\code\\showargs py'' '' ''- 'locate/run module as script the - option also supports running toolsmodules in packages with and without relative import syntaxand modules located in zip archives for instancethis switch is commonly used to run the pdb debugger and profile profiler modules from command line for script invocationrather than interactivelyc:\codepython import pdb pdb run('import showargs'more omittedsee pdb docs interactve debugger session :\codepython - pdb showargs py - :\code\showargs py( )(-import sys (pdbc ['showargs py'' '' ''- 'more omittedq to exit debugging script ( =continuethe profiler runs and times your codeits output can vary per pythonoperating systemand computerconfiguring python |
1,984 | profiling script :\codepython - profile showargs py - ['showargs py'' '' ''- ' function calls in seconds ordered bystandard name ncalls tottime percall cumtime more omittedsee profile docs percall filename:lineno(function : (charmap_encode : (execyou might also use the - switch to spawn ' idle gui program located in the standard library from any other directoryand to start the pydoc and timeit tools modules with command lines as we do in this book in and (see those for more details on the tools launched here) :\codepython - idlelib idle - run idle in packageno subprocess :\codepython - pydoc - run pydoc and timeit tools modules :\codepython - timeit - - - " [ , , , , ]" [ for in ]optimized and unbuffered modes immediately after the "pythonand before the designation of code to be runpython accepts additional arguments that control its own behavior these arguments are consumed by python itself and are not meant for the script being run for example- runs python in optimized mode and - forces standard streams to be unbuffered--with the latterany printed text will be finalized immediatelyand won' be delayed in bufferc:\codepython - showargs py - optimizedmake/run pyobyte code :\codepython - showargs py - unbuffered standard output stream post-run interactive mode finallythe - flag enters interactive mode after running script--especially useful as debugging toolbecause you can print variablesfinal values after successful run to get more detailsc:\codepython - showargs py - ['showargs py'' '' ''- 'sys ^ go to interactive mode on script exit final value of sysimported module you can also print variables this way after an exception shuts down your script to see what they looked like when the exception occurredeven if not running in debug mode --though you can start the debugger' postmortem tool here as well (type is the windows file display commandtry cat or other elsewhere) :\codetype divbad py appendix ainstallation and configuration |
1,985 | :\codepython divbad py error text omitted zerodivisionerrordivision by zero run the buggy script :\codepython - divbad py error text omitted zerodivisionerrordivision by zero import pdb pdb pm( :\code\divbad py( )(-print( (pdbquit print variable values at error start full debugger session now python command-line arguments besides those just mentionedpython supports additional options that promote compatibility (- to warn about incompatibilitiesand - to control division operator modelsand detecting inconsistent tab indentation usagewhich is always detected and reported in (-tsee againyou can always ask python itself for more on the subject as neededc:\codec:\python \python - python windows launcher command lines technicallythe preceding section described the arguments you can pass to the python interpreter itself--the program usually named python exe on windowsand python on linux (the exe is normally omitted on windowsas we'll see in the next appendixthe windows launcher shipped with python augments this story for users of and later or the standalone launcher package it adds new executables that accept python version numbers as arguments in command lines used to start python and your scripts (file what py is listed and described in the next appendixand simply prints the python version number) :\codepy what py windows launcher command lines :\codepy - what py version number switch :\codepy - - what py - - - ^ arguments for all pypythonscript in factas the last run of the preceding example showscommand lines using the launcher can give arguments for the launcher itself (- )python itself (- )and your script (- -band -cthe launcher can also parse version numbers out of #unix lines configuring python |
1,986 | entirelythoughyou'll have to read on for the rest of this story for more help python' standard manual set today includes valuable pointers for usage on various platforms the standard manual set is available in your start button on windows and earlier after python is installed (option "python manuals")and online at python org look for the manual set' top-level section titled "using pythonfor more platform-specific pointers and hintsas well as up-to-date cross-platform environment and command-line details as alwaysthe web is your allytooespecially in field that often evolves faster than books like this can be updated given python' widespread adoptionchances are good that answers to any high-level usage questions you may have can be found with web search appendix ainstallation and configuration |
1,987 | the python windows launcher this appendix describes the new windows launcher for pythoninstalled with python automaticallyand available separately on the web for use with older versions though the new launcher comes with some pitfallsit provides some much-needed coherence for program execution when multiple pythons coexist on the same computer 've written this page for programmers using python on windows though it is platform-specific by natureit' targeted at both python beginners (most of whom get started on this platform)as well as python developers who write code to work portably between windows and unix as we will seethe new launcher changes the rules on windows radically enough to impact everyone who uses python on windowsor may in the future the unix legacy to fully understand the launcher' protocolswe have to begin with short history lesson unix developers long ago devised protocol for designating program to run script' code on unix systems (including linux and mac os )the first line in script' text file is special if it begins with two-character sequence#!sometimes called shebang (an arguably silly phrase promise not to repeat from here on gives brief overview of this topicbut here' another look in unix scriptssuch lines designate program to run the rest of the script' contentsby coding it after the #!--using either the directory path to the desired program itselfor an invocation of the env unix utility that looks up the target per your path settingthe customizable system environment variable that lists directories to be searched for executables#!/usr/local/bin/python script' code run under this specific program #!/usr/bin/env python script' code run under "pythonfound on path |
1,988 | giving just its filename in command linethe #line at the top then directs the unix shell to program that will run the rest of the file' code depending on the platform' install structurethe python that these #lines name might be real executableor symbolic link to version-specific executable located elsewhere these lines might also name more specific executable explicitlysuch as python either wayby changing #linessymbolic linksor path settingsunix developers can route script to the appropriate installed python none of this applies to windows itselfof coursewhere #lines have no inherent meaning python itself has historically ignored such lines as comments if present on windows ("#starts comment in the languagestillthe idea of selecting python executables on per-file basis is compelling feature in world where python and often coexist on the same machine given that many programmers coded #lines for portability to unix anyhowthe idea seemed ripe for emulating the windows legacy the install model has been very different on the other side of the fence in the past (wellin every python until )the windows installer updated the global windows registry such that the latest python version installed on your computer was the version that opened python files when they were clicked or run by direct filename in command lines some windows users may know this registry as filename associationsconfigurable in control panel' default programs dialog you do not need to give files executable privileges for this to workas you do for unix scripts in factthere' no such concept on windows--filename associations and commands suffice to launch files as programs under this install modelif you wished to open file with different version than the latest installyou had to run command line giving the full path to the python you wantedor update your filename associations manually to use the desired version you could also point generic python command lines to specific python by setting or changing your path settingbut python didn' set this for youand this wouldn' apply to scripts launched by icon clicks and other contexts this reflects the natural order on windows (when you click on doc filewindows usually opens it in the latest word installed)and has been the state of things ever since there was python on windows it' less ideal if you have python scripts that require different versions on the same machinethough-- situation that has become increasingly commonand perhaps even normal in the dual python / era running multiple pythons on windows prior to can be tedious for developersand discouraging for newcomers appendix bthe python windows launcher |
1,989 | the new windows launchershipped and installed automatically with python (and presumably later)and available as standalone package for use with other versionsaddresses these deficits in the former install model by providing two new executablespy exe for console programs pyw exe for nonconsole (typically guiprograms these two programs are registered to open py and pyw filesrespectivelyvia windows filename associations like python' original python exe main program (which they do not deprecate but can largely subsume)these new executables are also registered to open byte code files launched directly amongst their weaponsthese two new executablesautomatically open python source and byte-code files launched by icon clicks or filename commandsvia windows associations are normally installed on your system search path and do not require directory path or path settings when used as command lines allow python version numbers to be passed in easily as command-line argumentswhen starting both scripts and interactive sessions attempt to parse unix-style #comment lines at the top of scripts to determine which python version should be used to run file' code the net effect is that under the new launcherwhen multiple pythons are installed on windowsyou are no longer limited to either the latest version installed or explicit/full command lines insteadyou can now select versions explicitly on both per-file and per-command basisand specify versions in either partial or full form in both contexts here' how this works to select versions per fileuse unix-style top-of-script comments like these#!python #!/usr/bin/python #!/usr/bin/env python to select versions per commanduse command lines of the following formspy - py py - py py - py for examplethe first of these techniques can serve as sort of directive to declare which python version the script depends uponand will be applied by the launcher whenever the script is run by command line or icon click (these are variants of file named script py)introducing the new windows launcher |
1,990 | script #!python script #!python script runs under latest installed runs under latest installed runs under (onlyon windowscommand lines are typed in command prompt windowdesignated by its :\codeprompt in this appendix the first of the following is the same as both the second and an icon clickbecause of filename associationsc:\codescript py :\codepy script py run per file' #line if presentelse per default dittobut py exe is run explicitly alternativelythe second technique just listed can select versions with argument switches in command lines insteadc:\codepy - script py :\codepy - script py :\codepy - script py runs under latest runs under latest runs under (onlythis works both when launching scripts and starting the interactive interpreter (when no script is named) :\codepy - :\codepy - :\codepy - :\codepy starts latest xinteractive starts latest xinteractive starts (only)interactive starts default python (initially xsee aheadif there are both #lines in the file and version number switch in the command line used to start itthe command line' version overrides that in the file' directive#python script \codepy script py \codepy - script py runs under per file directive runs under even if present the launcher also applies heuristics to select specific python version when it is missing or only partly described for instancethe latest is run when only is specifiedand is preferred for files that do not name version in #line when launched by icon click or generic command lines ( py pym py)unless you configure the default to use instead by setting py_python or configuration file entry (more on this ahead appendix bthe python windows launcher |
1,991 | useful addition for windowswhere many (and probably mostnewcomers get their first exposure to the language although it is not without potential pitfalls--including failures on unrecognized unix #lines and puzzling default--it does allow for more graceful coexistence of and files on the same machineand provides rational approach to version control in command lines for the complete story on the windows launcherincluding more advanced features and use cases 'll either condense or largely omit heresee python' release notes and try web search to find the pep (the proposal documentamong other thingsthe launcher also allows selecting between and -bit installsspecifying defaults in configuration filesand defining custom #command string expansion windows launcher tutorial some readers familiar with unix scripting may find the prior section enough to get started for othersthis section provides additional context in the form of tutorialwhich gives concrete examples of the launcher in action for you to trace through this section also discloses additional launcher details along the waythoughso even wellseasoned unix veterans may benefit from quick scan here before ftping all their python scripts to the local windows box to get startedwe'll be using the following simple scriptwhat pywhich can be run under both and to echo the version number of the python that runs its code it uses sys version-- string whose first component after splitting on whitespace is python' version number#!python import sys print(sys version split()[ ]first part of string if you want to work alongtype this script' code in your favorite text file editoropen command prompt window for typing the command lines we'll be runningand cd to the directory where you've save the script ( :\code is where ' workingbut feel free to save this wherever you wishand see for more windows usage pointersthis script' first-line comment serves to designate the required python versionit must begin with #per unix conventionand allows for space before the python or not on my machine currently have pythons , and all installedlet' watch which version is invoked as the script' first line is modified in the following sectionsexploring file directivescommand linesand defaults along the way step using version directives in files as this script is codedwhen run by icon click or command linethe first line directs the registered py exe launcher to run using the latest installeda windows launcher tutorial |
1,992 | import sys print(sys version split()[ ] :\codewhat py run per file directive :\codepy what py dittolatest againthe space after #is optionali added space to demonstrate the point here note that the first what py command here is equivalent to both an icon click and full py what pybecause the py exe program is registered to open py files automatically in the windows filename associations registry when the launcher is installed also note that when launcher documentation (including this appendixtalks about the latest versionit means the highest-numbered version that isit refers to the latest releasednot the latest installed on your computer ( if you install after #python selects the latterthe launcher cycles through the pythons on your computer to find the highest-numbered version that matches your specification or defaultsthis differs from the former last-installed-wins model nowchanging the first line name to python triggers the latest (reallyhighest-numbered installed instead here' this change at worki'll omit the last two lines of our script from this point on because they won' be altered#python rest of script unchanged :\codewhat py run with latest per #and you can request more specific version if needed--for exampleif you don' want the latest in python line#python :\codewhat py run with per #this is true even if the requested version is not installed--which is treated as an error case by the launcher#python :\codewhat py requested python version ( is not installed unrecognized unix #lines are also treated as errorsunless you give version number as command-line switch to compensateas the next section describes in more detail (and as the section on launcher issues will revisit as pitfall) appendix bthe python windows launcher |
1,993 | :\codewhat py unable to create process using '/bin/python " :\code\what pyc:\codepy what py unable to create process using '/bin/python what pyc:\codepy - what py technicallythe launcher recognizes unix-style #lines at the top of script files that follow one of the following four patterns#!/usr/bin/env python#!/usr/bin/python#!/usr/local/bin/python#!pythonany #line that does not take one of these recognized and parseable forms is assumed to be fully specified command line to start process to run the filewhich is passed to windows as isand generates the error message we saw previously if it is not valid windows command (the launcher also supports "customizedcommand expansions via its configuration fileswhich are attempted before passing unrecognized commands on to windowsbut we'll gloss over these here in recognizable #linesdirectory paths are coded per unix conventionfor portability to that platform the part at the end of the four preceding recognized patterns denotes an optional python version numberin one of three formspartial ( python to run the version installed with the highest minor release number among those with the major release number given full ( python to run that specific version onlyoptionally suffixed by - to prefer -bit version ( pythonomitted ( pythonto run the launcher' default versionwhich is unless changed ( by setting the py_python environment variable to )another pitfall described ahead files with no #line at all behave the same as those that name just generic python-the aforementioned omitted case--and are influenced by py_python default settings the first casepartialsmay also be affected by version-specific environment settings ( set py_python to to select for python and set py_python to to pick for python we'll revisit defaults later in this tutorial firstthoughnote that anything after the part in #line' format is assumed to be command-line arguments to python itself ( program python exe)unless you also windows launcher tutorial |
1,994 | by the launcher#!python [any python exe arguments go herethese include all the python command-line arguments we met in appendix but this leads us to launcher command lines in generaland will suffice as natural segue to the next section step using command-line version switches as mentionedversion switches on command lines can be used to select python version if one isn' present in the file you run py or pyw command line to pass them switch this wayinstead of relying on filename associations in the registryand instead of (or in addition togiving versions in #lines in files in the followingwe modify our script so that it has no #directivenot launcher directive :\codepy - what py run per command-line switch :\codepy - what py dittolatest installed :\codepy - what py ditto specifically (and onlyc:\codepy what py run per launcher' default (aheadbut command-line switches also take precedence over version designation in file' directive#python :\codewhat py run per file directive :\codepy what py ditto :\codepy - what py switches override directives :\codepy - what py ditto formallythe launcher accepts the following command-line argument types (which exactly mirror the part at the end of file' #line described in the prior section) appendix bthe python windows launcher |
1,995 | - - - - launch the latest python version launch the latest python version launch the specified python version ( is or launch the specified -bit python version and the launcher' command lines take the following general formpy [py exe arg[python exe argsscript py [script py argsanything following the launcher' own argument (if presentis treated as though it were passed to the python exe program--typicallythis includes any arguments for python itselffollowed by the script filenamefollowed by any arguments meant for the script the usual - mod- cmdand program specification forms work in py command line tooas do all the other python command-line arguments covered in appendix as mentioned earlierarguments to python exe can also appear at the end of the #directive line in fileif usedthough arguments in py command lines override them to see how this workslet' write new script that extends the prior to display command-line argumentssys argv is the script' own argumentsand ' using the python (python exe- switchwhich directs it to the interactive prompt (after script runsargs pyshow my arguments too import sys print(sys version split()[ ]print(sys argvc:\codepy - - args py - - - ['args py''- '' ''- ''- '^ - py-ipythonrestscript :\codepy - args py - - - ['args py''- '' ''- ''- '^ args to pythonscript :\codepy - - print( - to pyrest to python"- cmdc:\codepy - - "print notice how the first two launches run the default python unless version is given in the command linebecause no #line appears in the script itself somewhat coincidentallythat leads us to the last topic of this tutorial step using and changing defaults as also mentionedthe launcher defaults to for generic python in #directive with no specific version number this is true whether this generic form appears in windows launcher tutorial |
1,996 | actioncoded in our original what py script#!python :\codewhat py same as #!/usr/bin/python run per launcher default the default is also applied when no directive is present at all--perhaps the most common case for code written to be used on windows primarily or exclusivelynot launcher directive :\codewhat py also run per default :\codepy what py ditto but you can set the launcher' default to with initialization file or environment variable settingswhich will apply to both files run from command lines and by icon clicks via their name' association with py exe or pyw exe in the windows registrynot launcher directive :\codewhat py run per default :\codeset py_python= :\codewhat py or via control panel/system run per changed default as suggested earlierfor more fine-grained control you can also set version-specific environment variables to direct partial selections to specific releaseinstead of falling back on the installed release with the highest minor number#!python :\codepy what py runs "latest :\codeset py_python = :\codepy what py use py_python for override highest-minor choice the set used in these interactions applies to its command prompt window onlymaking such settings in the control panel' system window will make them apply globally across your machine (see appendix for help with these settingsyou may or may not want to set defaults this way depending on the majority of the python code you'll appendix bthe python windows launcher |
1,997 | override them in #lines or py command lines as needed howeverthe setting used for directive-less filespy_pythonseems fairly crucial most programmers who have used python on windows in the past will probably expect to be the default after installing especially given that the launcher is installed by in the first place-- seeming paradoxwhich leads us to the next section pitfalls of the new windows launcher though the new windows launcher in is nice additionlike much in it may have been nicer had it appeared years ago unfortunatelyit comes with some backward incompatibilitieswhich may be an inevitable byproduct of today' multiversion python worldbut which may also break some existing programs this includes examples in books 've writtenand probably many others while porting code to 've come across three launcher issues worth notingunrecognized unix !lines now make scripts fail on windows the launcher defaults to using unless told otherwise the new path extension is off by default and seems contradictory the rest of this section gives rundown of each of these three issues in turn in the followingi use the programs in my book programming python th editionas an example to illustrate the impacts of launcher incompatibilitiesbecause porting these examples to was my first exposure to the new launcher in my specific caseinstalling broke numerous book examples that worked formerly under and the causes for these failures outlined here may break your code too pitfall unrecognized unix !lines fail the new windows launcher recognizes unix #lines that begin with #!/usr/bin/env python but not the other common unix form #!/bin/env python (which is actually mandated on some unixesscripts that use the latter of theseincluding some of my book examplesworked on windows in the past because their #lines coded for unix compatibility have been ignored as comments by all windows pythons to date these scripts now fail to run in because the new launcher doesn' recognize their directive' format and posts an error message more generallyscripts with any #unix line not recognized will now fail to run on windows this includes scripts having any first line that begins with #that is not followed by one of the four recognized patterns described earlier/usr/bin/env python*/usr/bin/python*/usr/local/bin/python*or pythonanything else won' workand requires code changes for instancea somewhat common #!/bin/python line also causes script to now fail on windowsunless version number is given in command-line switches pitfalls of the new windows launcher |
1,998 | common in programs meant to be run on unix too treating unrecognized unix directives as errors on windows seems bit extremeespecially given that this is new behavior in and will likely be unexpected why not just ignore unrecognized #lines and run the file with the default python--like every windows python to date hasit' possible that this might be improved in future release (there may be some pushback on this)but today you must change any files using #!/bin/env or other unrecognized patternif you want them to run under the launcher installed with python on windows book examples impact and fix with respect to the book examples ported to this broke roughly dozen scripts that started with #!/bin/env python regrettablythis includes some of the book' userfriendly and top-level demo launcher scripts (pygadgets and pydemosto fixi changed these to use the accepted #!/usr/bin/env python form instead altering your windows file associations to omit the launcher altogether may be another option ( associating py files with python exe instead of py exe)but this negates the launcher' benefitsand seems bit much to ask of usersespecially newcomers one open issue herestrangelypassing any command-line switch to the launchereven python exe argumentseems to negate this effect and fall back on the default python -- py and py py both issue errors on unrecognized #linesbut py - py runs such file with the default python this seems possible launcher bugbut also relies on the defaultthe subject of the next issue pitfall the launcher defaults to oddlythe windows launcher defaults to using an installed python when running scripts that don' select explicitly that isscripts that either have no #directive or use one that names python generically will be run by python by default when launched by icon clicksdirect filename command lines ( py)or launcher command lines that give no version switch (py pythis is true even if is installed after on your machineand has the potential to make many scripts fail initially the implications of this are potentially broad as one exampleclicking the icon of directive-less file just after installing may now failbecause the associated launcher assumes you mean to use by default this probably won' be pleasant first encounter for some python newcomersthis assumes the file has no #directive that provides an explicit python version numberbut most scripts meant to run on windows won' have #line at alland many files coded before the launcher came online won' accommodate its version number expectations most users will be basically compelled to set py_python after installing --hardly usability win program launches that don' give an explicit version number might be arguably ambiguous on unix tooand often rely on symbolic links from python to specific version appendix bthe python windows launcher |
1,999 | but as for the prior issuethis probably shouldn' trigger new error on windows in for scripts that worked there formerly most programmers wouldn' expect unix comment lines to matter on windowsand wouldn' expect to be used by default just after installing book examples impact and fix in terms of my book examples portthis default caused multiple script failures after installing for both scripts with no #lineas well as scripts with unixcompatible #!/usr/bin/python line to fix just the latterchange all scripts in this category to name python explicitly instead of just python to fix both the former and the latter in single stepset the windows launcher' default to be globally with either py ini configuration file (see the launcher' documentation for detailsor py_python environment variable setting as shown in the earlier examples ( set py_python= as mentioned in the prior pointmanually changing your file associations is another solutionbut none of these options seem simpler than those imposed by prior install schemes pitfall the new path extension option besides installing the new launcherthe windows python installer can automatically add the directory containing ' python exe executable to your system path setting the reasoning behind this is that it might make life easier for some windows beginners--they can type just python instead of the full directory path to it this isn' feature of the launcher per seand shouldn' cause scripts to fail in general it had no impact on the book examples but it seems to clash with the launcher' operation and goalsand may be best avoided this is bit subtlebut 'll explain why as describedthe new launcher' py and pyw executables are by default installed on your system search pathand running them requires neither directory paths nor path settings if you start scripts with py instead of python command linesthe new path feature is irrelevant in factpy completely subsumes python in most contexts given that file associations will launch py or pyw instead of python anyhowyou probably should too --using python instead of py may prove redundant and inconsistentand might even launch version different than that used in launcher contexts should the two schemessettings grow out of sync in shortadding python to path seems contradictory to the new launcher' worldviewand potentially error-prone also note that updating your path assumes you want python command to run normallyand this feature is disabled by defaultbe sure to select this in the install screen if you want this to work (but not if you don' !due to the second pitfall mentioned earliermany users may still need to set py_python to for programs run by icon clicks that invoke the new launcherwhich seems no simpler than setting patha step that the pitfalls of the new windows launcher |
Subsets and Splits