id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
4,500 | (continued from previous page @property method-name should be same as attribute 'radiushere def radius(self)return self _radius _radius can be changed with other name return self diameter/ _radius can be changed with other name @radius setter def radius(selfval)'valshould be float or int if not isinstance(val(floatint))raise typeerror("expectedfloat or int"self _radius float(valself diameter float(val multiple constructor below constructor is added for the 'research organizationwho are doing their work based on diameters@classmethod def diameter_init(clsdiameter)radius diameter/ change diameter to radius return cls(radiusreturn radius @staticmethod meter to centimeter conversion def meter_cm(meter)return( *meter def cost(self)return self price self quantity def area(self)return math pi self radius** self perimeter(wrong way to calculate perimeter self __perimeter(use local copy of perimeter( math pireturn math pi ** def perimeter(self)return math pi self radius local copy can be created in the lines after the actual method __perimeter perimeter make local copy of perimeter def main()print("center of the ring is at:"ring centermodify class variable ring(price= modify only price print("radius:{ }cost:{ }format( radiusr cost())print("radius:{ }perimeter:{ : }format( radiusr perimeter()) print(check the new constructor 'diameter_initd ring diameter_init(diameter= print("radius:{ }perimeter:{ : }area:{ : }formatd radiusd perimeter() area())print("radius:{ }perimeter:{ : }format( radiusd perimeter()) meter print("{ meter { centimeterformat(md meter_cm( )) if __name__ ='__main__'main(lets check the output of this file firstwhich is working fine as below note that the dictionarynow contains the 'diameterinstead of 'radius @property |
4,501 | from pythonic import ring( __dict__ dictionary contains 'diameternot 'radius{'date''''metal''copper''diameter' 'price' 'quantity' radius radius is still accessbile area(area is working fine diameter diameter is accessbile next verify the output for the 'box pyfile again from box import box diameter_init( area(area is working fine __dict__ {'date' 'metal''copper''diameter' 'price' 'quantity' @property |
4,502 | decorator and descriptors decorators decorator is function that creates wrapper around another function this wrapper adds some additional functionality to existing code in this tutorialvarious types of decorators are discussed function inside the function and decorator following is the example of function inside the function funcex py def addone(myfunc)def addoneinside( )print("adding one"return myfunc( return addoneinside def subthree( )return result addone(subthree print(subthree( )print(result( ) outputs adding one above code works as followsfunction 'subthreeis defined at lines - which subtract the given number with function 'addone(line has one argument myfuncwhich indicates that 'addonetakes the function as input sincesubthree function has only one input argumenttherefore one argument is set in the function 'addoneinside(line )which is used in return statement (line also"adding oneis printed before returning the value (line in line return value of addone ( function 'addoneinside'is stored in 'resulthence'resultis function which takes one input lastlyvalues are printed at line and note that "adding oneis printed by the result( and value is incremented by one to |
4,503 | another nice way of writing above code is shown below here (*args and **kwargsare usedwhich takes all the arguments and keyword arguments of the function funcex py def addone(myfunc)def addoneinside(*args**kwargs)print("adding one"return myfunc(*args**kwargs return addoneinside def subthree( )return result addone(subthree print(subthree( )print(result( ) outputs adding one nowin the below codethe return value of addone is stored in the 'subthreefunction itself (line ) funcex py def addone(myfunc)def addoneinside(*args**kwargs)print("adding one"return myfunc(*args**kwargs return addoneinside def subthree( )return subthree addone(subthree print(subthree( )outputs adding one lastlyin pythonthe line in above codecan be replaced by using decoratoras shown in line of below code funcex py def addone(myfunc)def addoneinside(*args**kwargs)print("adding one"return myfunc(*args**kwargs return addoneinside @addone def subthree( )return print(subthree( )outputs adding one decorators |
4,504 | in this sectionwe saw the basics of the decoratorwhich we will be used in this tutorial decorator without arguments in following codedecorator takes function as the input and print the name of the function and return the function debugex py def printname(func)func is the function to be wrapped def pn(*args**kwargs)print(func __name__return func(*args**kwargsreturn pn nextput the printname function as decorator in the mathex py file as belowmathex py from debugex import printname @printname def add num(xy)add two numbers print("add"return( +yprint(add num( )help(add numfinallyexecute the code and the name of each function will be printed before calculation as shown belowpython mathex py add help on function pn in module debugexpn(*args**kwargsfunc is the function to be wrapped importantdecorator brings all the debugging code at one places now we can add more debugging features to 'debugex pyfile and all the changes will be applied immediately to all the functions warningdecorators remove the help features of the function along with name etc thereforewe need to fix it using functools as shown next rewrite the decorator using wraps function in functools as belowdebugex py from functools import wraps def printname(func)func is the function to be wrapped (continues on next page decorators |
4,505 | (continued from previous pagewrap is used to exchange metadata between functions @wraps(funcdef pn(*args**kwargs)print(func __name__return func(*args**kwargsreturn pn if we execute the mathex py againit will show the help features again note@wraps exchanges the metadata between the functions as shown in above example decorators with arguments supposewe want to pass some argument to the decorator as shown belowmathex py from debugex import printname @printname('**'def add num(xy)'''add two numbers''return( +yprint(add num( )help(add numnoteto pass the argument to the decoratorall we need to write outer function which takes the input arguments and then write the normal decorator inside that function as shown belowdebugex py from functools import wraps def printname(prefix="")def addprefix(func)msg prefix func __name__ func is the function to be wrapped wrap is used to exchange metadata between functions @wraps(funcdef pn(*args**kwargs)print(msgreturn func(*args**kwargsreturn pn return addprefix nowrun the above codepython mathex py **add num decorators |
4,506 | error butabove code will generate error if we do not pass the argument to the decorator as shown belowmathex py from debugex import printname @printname def add num(xy)'''add two numbers''return( +yprint(add num( )help(add numfollowing error will be generate after running the codepython mathex py traceback (most recent call last)file "mathex py"line in print(add num( )typeerroraddprefix(takes positional argument but were given one solution is to write the two different codes 'printnameand 'printnamearg'then use these decorators as required but this will make code repetitive as shown belowdebugex py from functools import wraps def printname(func)func is the function to be wrapped wrap is used to exchange metadata between functions @wraps(funcdef pn(*args**kwargs)print(func __name__return func(*args**kwargsreturn pn def printnamearg(prefix="")def printname(func)func is the function to be wrapped wrap is used to exchange metadata between functions @wraps(funcdef pn(*args**kwargs)print(prefix func __name__return func(*args**kwargsreturn pn return printname nowmodify the math py as belowmathex py from debugex import printnameprintnamearg @printnamearg('**'def add num(xy)(continues on next page decorators |
4,507 | (continued from previous page'''add two numbers''return( + @printname def diff num(xy)'''subtract two integers only''return( -yprint(add num( )print(diff num( )help(add numnext execute the codepython mathex py **add num diff num - dry decorator with arguments in previous codewe repeated the same code two time for creating the decorator with and without arguments butthere is better way to combine both the functionality in one decorator using partial function as shown belowdebugex py from functools import wrapspartial def printname(func=none*prefix="")if func is nonereturn partial(printnameprefix=prefixwrap is used to exchange metadata between functions @wraps(funcdef pn(*args**kwargs)print(prefix func __name__return func(*args**kwargsreturn pn nowmodify the mathex py remove printnamearg decorator from the codeas belowmathex py from debugex import printname @printname(prefix='**'def add num(xy)'''add two numbers''return( + @printname def diff num(xy)'''subtract two integers only''return( -yprint(add num( )print(diff num( )help(add numnextrun the code and it will display following results decorators |
4,508 | python mathex py **add num diff num - partial function is required becausewhen we pass argument to the decorator @printname(prifix='**')then decorator will not find any function argument at first placehence return func(*arg**kwargswill generate error as there is no 'functo solve this problempartial is used which returns the an new functionwith modified parameters newfunc(func printnameprefix prefixdecorators inside the class in previous sectionsdecorators are defined as functions in this sectiondecorators will be defined as class methods class method and instance method decorator in the following codetwo types of decorators are defined inside the class using class method and instance method clsdecorator py from datetime import datetime class datedecorator(object)instance method decorator def instantmethoddecorator(selffunc)def printdate(*args**kwargs)print("instance method decorator at time \ "datetime today()return func(*args**kwargsreturn printdate class method decorator @classmethod def classmethoddecorator(selffunc)def printdate(*args**kwargs)print("class method decorator at time \ "datetime today()return func(*args**kwargsreturn printdate decoratorinstance method datedecorator(@ instantmethoddecorator def add(ab)return + decoratorclass method @datedecorator classmethoddecorator def sub(ab)return - sum add( instance method decorator at time : : diff sub( (continues on next page decorators |
4,509 | (continued from previous page class method decorator at time : : note thatwe need to instantiate the instance mehtod decorator before using it as shown at line whereas class decorator can be used as classname decoratorname conclusion in this sectionwe saw the relation between 'function inside the functionand decorator thendecorator with and without arguments are discussed lastlyclass decorators are shown with examples descriptors descriptor gives us the fine control over the attribute access it allows us to write reusable code that can be shared between the classes as shown in this tutorial problems with @property before beginning the descriptorslet' look at the @property decorator and it' usage along with the problem then we will see the descriptors in next section square py class square(object)def __init__(selfside)self side side def aget(self)return self side * def aset(selfvalue)print("can not set area"def adel(self)print("can not delete area"area property(agetasetadeldoc="area of sqare" square( print( area area can not set area del area can not delete area note that in above codeno bracket is used for calculating the area ' areais usedinstead of area()because area is defined as propertynot as method above code can be rewritten using @property decorator as belowsquare py class square(object)"" square using property with decorator""def __init__(selfside)(continues on next page descriptors |
4,510 | (continued from previous pageself side side @property def area(self)"""calculate the area of the square""return self side * name for setter and deleter ( @areamust be same as the method for which @property is used area here @area setter def area(selfvalue)""do not allow set area directly""print("can not set area"@area deleter def area(self)"""do not allow deleting""print("can not delete area" square( print( area area can not set area del area can not delete area note that@area setter and @area deleter are optional here we can stop writing the code after defining the @property in thatcase setter and deleter option will generate standard exception attribute error here if we want to perform some operationsthen setter and deleter options are required furthercode is repetitive because @propertysetter and deleter are the part of same method here area we can merge all three methods inside one method as shown next but before looking at that examplelet' understand two python features first **kwargs and locals(**kwargs **kwargs converts the keyword arguments into dictionary as shown belowdef func(**kwargs)print(kwargsfunc( = = {' ' ' ' locals(locals return the dictionary of local variablesas shown belowdef mathex(ab)add diff print(locals()mathex( {' ' 'add' ' ' 'diff' nowwe can implement all the getset and del method inside one method as shown below descriptors |
4,511 | square py def nested_property(func)""nest gettersetter and deleter""names func(names['doc'func __doc__ return property(**namesclass square(object)"" square using property with decorator""def __init__(selfside)self side side @nested_property def area()"""calculate the area of the square""def fget(self)""calculate area ""return self side * def fset(selfvalue)""do not allow set area directly""print("can not set area"def fdel(self)"""do not allow deleting""print("can not delete area"return locals( square( print( area area can not set area del area can not delete area note@propery is good for performing certain operations before getset and delete operation butwe need to implement it for all the functions separately and code becomes repetitive for larger number of methods in such casesdescriptors can be useful data descriptors data_descriptor py class datadescriptor(object)""descriptor example ""def __init__(self)self value def __get__(selfinstancecls)print("data descriptor __get__"return self value def __set__(selfinstancevalue)(continues on next page descriptors |
4,512 | (continued from previous pageprint("data descriptor __set__"tryself value value upper(except attributeerrorself value value def __delete__(selfinstance)print("can not delete"class (object)attr datadescriptor( datadescriptor(print( value (print( attrdata descriptor __get__ attr is equivalent to below code print(type(a__dict__['attr'__get__(atype( ))data descriptor __get__ set will upper case the string attr lazy loadingabove / will not display if below line is uncommented attr 'tigertiger print( __dict__{following are the outputs of above three commands data descriptor __set__ data descriptor __set__ {data descriptor __get__ data descriptor __get__ tiger notenote that object 'ddoes not print the 'data descriptor __get__but object of other class prints the message in the other wordsdescriptor can not use there methods by itsown other' class-attributes can use descriptor' methods as shown in above example alsosee the outputs of last three commands we will notice thatnotethe set values are not store in the instance dictionary print( __dict__results in empty dictionary furthera attr and attr 'tigerperforms the set operation immediately (see the __set__ message at outputs)but __get__ operations are performed at the end of the codei first print( __dict__outputs are shown and then get operations is performed lastlyset operation stores only last executed valuei only tiger is printed at the endbut not descriptors |
4,513 | non-data descriptor non-data descriptor stores the assigned values in the dictionary as shown belownon_data_descriptor py class nondatadescriptor(object)""descriptor example ""def __init__(self)self value def __get__(selfinstancecls)print("non-data descriptor __get__"return self value class (object)attr nondatadescriptor( (print( attrnon-data descriptor __get__ attr attr print( __dict__{'attr' importantin non-data descriptorthe assigned values are stored in instance dictionary (and only last assigned value is stored in dictionary)whereas data descriptor assigned values are stored in descriptor dictionary because the set method of descriptor is invoked __getattribute__ breaks the descriptor usage in below code__getattribute__ method is overridden in class overriden theninstance of class overriden is created and finally the descriptor is called at line in this case__getattribute__ method is invoked first and does not give access to descriptor non_data_descriptor py class nondatadescriptor(object)""descriptor example ""def __init__(self)self value def __get__(selfinstancecls)print("non-data descriptor __get__"return self value class overriden(object)attr nondatadescriptor(def __getattribute__(selfname)print("sorryno way to reach to descriptor!" overriden( attr sorryno way to reach to descriptor descriptors |
4,514 | notedescriptors can not be invoked if __getattribute__ method is used in the class as shown in above example we need to find some other ways in such cases use more than one instance for testing following is the good examplewhich shows that test must be performed on more than one object of classes as following codewill work fine for one objectbut error can be caught with two or more objects only examples py class descriptorclassstorage(object)""descriptor example ""def __init__(selfdefault none)self value default def __get__(selfinstancecls)return self value def __set__(selfinstancevalue)self value value class storeclass(object)attr descriptorclassstorage( store store storeclass(storeclass(print(store attrstore attr store attr print(store attrstore attr in above codeonly store attr is set to but value of store attr is also changes this is happening becausein data-descriptors values are stored in descriptors only (not in instance dictionary as mentioned in previous sectionexamples write descriptor which allows only positive values following is the code to test the positive number using descriptorpositivevaluedescriptor py class positivevalueonly(object)""allows only positive values ""def __init__(self)self value def __get__(selfinstancecls)return self value def __set__(selfinstancevalue)if value raise valueerror ('only positive values can be used'else(continues on next page descriptors |
4,515 | (continued from previous pageself value value class number(object)""sample class that uses positivevalueonly descriptor""value positivevalueonly(test number(print(test value test value print(test value test value - valueerroronly positive values can be used passing arguments to decorator in previous codesno arguments were passed in the decorator in this exampletaxrate is passed in the decorator and total price is calculated based on tax rate taxrate py class total(object)""calculate total values ""def __init__(selftaxrate )self rate taxrate def __get__(selfinstancecls)net_price rate return instance net self rate override __set__so that there will be no way to set the value def __set__(selfinstancevalue)raise noimplementationerror("can not change value"class pricenz(object)total total( def __init__(selfnetcomment="")self net net self comment comment class priceaustralia(object)total total( def __init__(selfnet)self net net pricenz pricenz( "nzd"print(pricenz total priceaustralia priceaustralia( print(priceaustralia total descriptors |
4,516 | notein above examplelook for the pricenz classwhere init function takes two arguments and one of which is used by descriptor using 'instance netcommand furtherinit function in class total need one argument taxratewhich is passed by individual class which creating the object of the descriptor conclusion in this sectionwe discussed data-descriptors and non-data-descriptors alsowe saw the way values are stored in these two types of descriptors furtherwe saw that __getattribute__ method breaks the descriptor calls descriptors |
4,517 | more examples this contains several examples of different topics which we learned in previous generalized attribute validation in this 'functions''@property''decoratorsand 'descriptorsare described alsothese techniques are used together in final example for attribute validation attribute validation is defined in section section function various features are provided in python for better usage of the function in this section'help featureand 'argument featureare added to functions help feature in listing anything which is written between quotation marks after the function declaration ( line - )will be displayed as the output of 'helpcommand as shown in line noteour aim is to write the function which adds the integers onlybut currently it is generating the output for the 'stringsas well as shown in line thereforewe need 'attribute validationso that inputs will be verified before performing the operations on them listing help feature addintex py line - will be displayedwhen help command is used for addintex as shown in line def addintex( , )'''add two variables (xy)xinteger yinteger returntypeinteger ''return ( + help(addintexline - will be displayed as output #adding numbersdesired result (continues on next page |
4,518 | (continued from previous page intadd addintex( , print("intadd ="intadd adding stringsundesired result attribute validation is used for avoiding such errors stradd addintex("meher ""krishna"print("stradd ="straddmeher krishna keyword argument in listing 'addkeywordarg( * )is python featurein which all the arguments after '*are considered as positional argument hence'xand 'yare the 'positionaland 'keywordargument respectively keyword arguments must be defined using the variable name ' = as shown in lines and if name of the variable is not explicitly usedthen python will generate error as shown in line furtherkeyword argument must be defined after all the positional argumentsotherwise error will be generated as shown in line lastlyin line the definition 'addkeywordarg(xint*yint-intis presenting that inputs ( and yand return values are of integer types these help features can be viewed using metaclass commandi __annotations__'as shown in lines and note thatthis listing is not validating input types in next sectioninput validation is applied for the functions listing keyword argument addkeywordarg py def addkeywordarg( :int* :int-int'''add two numbersxintegerpostional argument yintegerkeyword argument returntypeinteger ''return ( + add addkeywordarg( = xpositional arg and ykeyword arg print(add add addkeywordarg( = = and as keyword argument print(add #it' wrongbecause is not defined as keyword argument #add addpositionalarg( should be keyword argument = #keyword arg should come after positional arg #add addpositionalarg( = correct ( = help(addkeywordarglines - will be displayed as output print(addkeywordarg __annotations__#{'return'' '' ' #line is only help (not validation) string addition will still unchecked stradd addkeywordarg("meher " "krishna"print("stradd ="stradd input validation in previous sectionhelp features are added to functionsso that the information about the functions can be viewed by the users in this sectionvalidation is applied to input argumentsso that any invalid input will not be process by the function and corresponding error be displayed to the user generalized attribute validation |
4,519 | in listing lines - are used to verify the type of input variable 'xline checks whether the input is integer or notif it is not integer that error will be raised by line as shown in lines - similarlylines - are used to verify the type of variable 'ylisting input validation addintvalidation py def addintvalidation( :int* :int)->int'''add two variables (xy)xintegerpostional argument yintegerkeyword argument returntypeinteger ''if type(xis not intvalidate input 'xas integer type raise typeerror("please enter integer value for " if type(yis not intvalidate input 'yas integer type raise typeerror("please enter integer value for " return ( + intadd=addintvalidation( = = print("intadd ="intadd #stradd=addintvalidation("meher " "krishna"#following error will be generated for above command#raise typeerror("please enter integer value for "#typeerrorplease enter integer value for help(addintvalidationlines - will be displayed as output print(addintvalidation __annotations__#{'return'' '' 'decorators decorators are used to add additional functionalities to functions in section section 'xand 'yare validated individuallyhecceif there are large number of inputsthen the method will not be efficient decorator will be used in section section to write the generalized validation which can validate any kind of input add decorators and problems listing is the decoratorwhich prints the name of the function whenever the function is calledthe decorator will be executed first and print the name of the function and then actual function will be executed the decorator defined above the function declaration as shown in line of listing listing decorator which prints the name of function funcnamedecorator py def funcnamedecorator(func)function as input def printfuncname(*args**kwargs)#take all arguments of function as input print("function name:"func __name__print function name return func(*args**kwargsreturn function with all arguments return printfuncname in listing first decorator 'funcnamedecoratoris imported to the listing in line thendecorator is applied to function 'addintdecoratorin line when line calls the function 'addintdecorator'the decorator is executed first and name of function is printedafter that print command at line is executed generalized attribute validation |
4,520 | warningin the listingwe can see that help function is not working properly now as shown in listing alsodecorator removes the metaclass features 'annotationwill not workas shown in line listing decorator applied to function #addintdecorator py from funcnamedecorator import funcnamedecorator @funcnamedecorator def addintdecorator( :int* :int-int'''add two variables (xy)xintegerpostional argument yintegerkeyword argument returntypeinteger ''return ( + #decorator will be executed when function is called#and function name will be displayed as output as shown belowintadd=addintdecorator( = function nameaddintdecorator print("intadd ="intadd ##problem with decoratorhelp features are not displayed as shown below help(addintdecoratorfollowing are the outputs of help command #help on function wrapper in module funcnamedecorator#wrapper(*args**kwargs #problem with decoratorno output is displayed print(addintdecorator __annotations__{noteit is recommonded to define the decorators in the separate files 'funcnamedecorator pyfile is used here it' not good practice to define decorator in the same fileit may give some undesired results remove problems using functools the above problem can be removed by using two additional lines in listing the listing is saved as listing and lines and are addedwhich solves the problems completely in line 'wrapsis imported from 'functoolslibrary and then it is applied inside the decorator at line listing is same as listing except new decorator which is defined in listing is called at line listing decorator with 'wrapdecorator funcnamedecoratorfunctool py from functools import wraps def funcnamedecoratorfunctool(func)function as input #func is the function to be wrapped @wraps(funcdef printfuncname(*args**kwargs)#take all arguments of function as input print("function name:"func __name__print function name return func(*args**kwargsreturn function with all arguments return printfuncname generalized attribute validation |
4,521 | listing help features are visible again addintdecoratorfunctool py from funcnamedecoratorfunctool import funcnamedecoratorfunctool @funcnamedecoratorfunctool def addintdecorator( :int* :int-int'''add two variables (xy)xintegerpostional argument yintegerkeyword argument returntypeinteger ''return ( + intadd=addintdecorator( = function nameaddintdecorator print("intadd ="intadd help(addintdecoratorlines - will be displaed print(addintdecorator __annotations__##{'return'' '' '@property in this sectionarea and perimeter of the rectangle is calculated and '@propertyis used to validate the inputs before calculation furtherthis example is extended in the next sections for adding more functionality for 'attribute validationexplanation listing in line of the listing@property is used for 'lengthattribute of the class rectangle since@property is usedtherefore 'getterand 'settercan be used to validate the type of length note thatin setter parti lines - self _length (see '_before lengthis used for setting the valid value in 'lengthattribute in the setter part validation is performed at line using 'isinstancen line the value of length is passed as floattherefore error will be raised as shown in line nowwhenever 'lengthis accessed by the codeit' value will be return by getter method as shown in lines - in the other wordsthis block will be executed every time we use 'lengthvalue to demonstrate thisprint statement is used in line for exampleline print the length valuetherefore line printed first and then length is printed as shown in lines - also@property is used for the method 'areaas well thereforeoutput of this method can be directly obtained as shown in lines - furtherfor calculating areathe 'lengthvariable is required therefore line will be printed as outputwhich is explained in previous paragraph notein this listingthe type-check applied to 'lengthusing @property butthe problem with this method is that we need to write it for each attribute length and width in this case which is not the efficient way to do the validation we will remove this problem using descriptor in next section listing attribute validation using @property rectproperty py class rectangle''-calculate area and perimeter of rectangle -getter and setter are used to displaying and setting the length value -width is set by init function '' (continues on next page generalized attribute validation |
4,522 | (continued from previous page self length is used in below linesbut length is not initialized by __init__initialization is done by setter at lines due to @property at line also value is displayed by getter (@propetyat line - whereas `widthis get and set as simple python code and without validation def __init__(selflengthwidth)#if self _length is usedthen it will not validate through setter self length length self width width @property def area(self)'''calculates arealength*width''return self length self width def perimeter(self)'''calculates perimeter *(length+width)''return (self length self width @property def length(self)'''displaying length''print("getting length value through getter"return self _length @length setter def length(selfvalue)'''setting length''print("saving value through setter"valueif not isinstance(valueint)validating length as integer raise typeerror("only integers are allowed"self _length value rectangle( , following output will be displayed #saving value through setter print( lengthfollowing output will be displayed #getting length value through getter # #@property is used for area#therefore it can be accessed directly to display the area print( areafollowing output will be displayed #getting length value through getter # # =rectangle( following error will be generated ##typeerroronly integers are allowed print perimeter of rectangle print(rectangle perimeter( )#getting length value through getter # descriptors descriptor are the classes which implement three core attributes access operation getset and del using '__get__''__set__and '__del__as shown in listing in this sectionvalidation is applied using descriptor to remove the problem with @property generalized attribute validation |
4,523 | explanation listing hereclass integer is used to verify the type of the attributes using '__get__and '__set__at lines and respectively the class 'rectis calling the class 'integerat lines and the name of the attribute is passed in these lineswhose values are set by the integer class in the form of dictionaries at line alsovalue is get from the dictionary from line note thatin this caseonly one line is added for each attributewhich removes the problem of '@propertymethod listing attribute validation using descriptor rectdescriptor py class integerdef __init__(selfparameter)self parameter parameter def __get__(selfinstancecls)if instance is nonerequired if descriptor is return self used as class variable elsein this codeonly following line is required return instance __dict__[self parameter def __set__(selfinstancevalue)print("setting % to % (self parametervalue)if not isinstance(valueint)raise typeerror("interger value is expected"instance __dict__[self parametervalue class rectlength integer('length'width integer('width'def __init__(selflengthwidth)self length length self width width def area(self)'''calculates arealength*width''return self length self width rect( , #setting length to #setting width to print( length print("area:"rect area( )area # rect( #typeerrorinterger value is expected generalized validation in this sectiondecorators and descriptors are combined to create validationwhere attribute-types are defined by the individual class authors notenote thatvarious types '@typeassert(author=strlength=intwidth=float)will be defined by class author for validation explanation listing in this codefirst decorator 'typeassertis applied to class 'rectat line the typeassert contains generalized attribute validation |
4,524 | the name of the attribute along with it' valid type then the decorator (lines - )extracts the 'key-valuepairs 'parameter-expected]_type(see line and pass these to descriptor 'typecheckthrough line if type is not validdescriptor will raise errorotherwise it will set the values to the variables finallythese set values will be used by the class 'rectfor further operations listing generalized attribute validation #rectgeneralized py class typecheckdef __init__(selfparameterexpected_type)self parameter parameter self expected_type expected_type def __get__(selfinstancecls)if instance is nonerequired if descriptor is return self used as class variable elsein this codeonly following line is required return instance __dict__[self parameter def __set__(selfinstancevalue)print("setting % to % (self parametervalue)if not isinstance(valueself expected_type)raise typeerror("% value is expectedself expected_typeinstance __dict__[self parametervalue def typeassert(**kwargs)def decorate(cls)for parameterexpected_type in kwargs items()setattr(clsparametertypecheck(parameterexpected_type)return cls return decorate define attribute types here in the decorator @typeassert(author=strlength intwidth floatclass rectdef __init__(self*lengthwidthauthor "")#require kwargs self length length self width width to accept integer as well self author author rect (length= width= author "meher"#setting length to #setting width to #setting author to meher # rect (length="len"width= author "meher"error shown below #file "rectproperty py"line ##typeerrorvalue is expected summary in this we learn about functions@propertydecorators and descriptors we see that @property is useful for customizing the single attribute whereas descriptor is suitable for multiple attributes furtherwe saw that how decorator and descriptor can be used to enhance the functionality of the code with dry (don' repeat yourselftechnique generalized attribute validation |
4,525 | inheritance with super in this sectioninheritance is discussed using super command in most languagesthe super method calls the parent classwhereas in python it is slightly different it consider the child before parentas shown in this section super child before parent lets understand super with the help of an example firstcreate class pizzawhich inherits the doughfactory for getting the dough as belowpizza py class doughfactory(object)def get_dough(self)return 'white floor doughclass pizza(doughfactory)def order_pizza(self*toppings)print("getting dough"dough doughfactory get_dough(#above line is commented to work with dry principle #use super as belowdough super(get_dough(print("making pie using '% 'doughfor topping in toppingsprint("adding % toppingif __name__ ='__main__'pizza(order_pizza("pepperoni""bell pepper"run the above code and we will get below outputpython - pizza py getting dough making pie using 'white floor doughadding pepperoni adding bell pepper help(pizzahelp on class pizza in module __main__class pizza(doughfactorymethod resolution orderpizza doughfactory builtins object notethe resolution order shows that the way in which python interpretor tries to find the methods it tries to find get_dough in pizza class firstif not found thereit will go to doughfactory nowcreate the another class in separate python file as below inheritance with super |
4,526 | wheatdough py from pizza import pizzadoughfactory class wheatdoughfactory(doughfactory)def get_dough(self)return("wheat floor dough"class wheatpizza(pizzawheatdoughfactory)pass if __name__ ='__main__'wheatpizza(order_pizza('sausage''mushroom'notein pythoninheritance chain is not determine by the parent classbut by the child class if we run the wheatdough pyit will call the super command in class pizza in pizza py will not call his parent class doughfactorybut the parent class of the child class wheatdoughfactory this is called dependency injection importantsuper consider the children before parents it looks methods in child class firstthen it goes for parent class nextit calls the parents in the order of inheritance use keyword arguments for cooperative inheritance for above reasonssuper is super commandas it allows to change the order of inheritance just by modifying the child classas shown in above example notefor better understanding of the super commandsome more short examples are added hereinherit __init__ in the following codeclass rectarea is inheriting the __init__ function of class rectlen in the other wordlength is set by class rectlen and width is set by class rectarea and finally area is calculated by class rectarea rectangle py class rectlen(object)def __init__(selflength)self length length class rectarea(rectlen)def __init__(selflengthwidth)self width width super(__init__(lengthprint("area "self length self widthrectarea( area inheritance with super |
4,527 | in the same waythe other functions of parent class can be called in following codeprintclass method of parent class is used by child class printclass py class (object)def printclassname(self)print(self __class__ __name__class ( )def printname(self)super(printclassname( ( printclassname( ( printclassname( notein above codeprint(self __class__ __name__is used for printing the class nameinstead of print(" "hencewhen child class will inherit this functionthen __class__ will use the name of the child class to print the name of the classtherefore line prints "binstead of inherit __init__ of multiple classes in this sectionvarious problems are discussed along with the solutionswhich usually occurs during multiple inheritance problem super(calls __init__ of one class only in following exampleclass is inheriting the class and butthe super function in class will inherit only one class init function init function of the class which occurs first in the inheritance order #multipleinheritance py class (object)def __init__(self)print(" "class (object)def __init__(self)print(" "class (ab)def __init__(self)super(__init__(init of class is not inherited ( solution following is the first solutionwhere __init__ function of classes are invoked explicitly inheritance with super |
4,528 | #multipleinheritance py class (object)def __init__(self)print(" "class (object)def __init__(self)print(" "class (ab)def __init__(self) __init__(selfb __init__(selfself is required ( correct solution following is the another solution of the problemwhere super(function is added in both the classes note thatthe super(is added in class as wellso that class(bawill also work fine #multipleinheritance py class (object)def __init__(self)print("reached "super(__init__(print(" "class (object)def __init__(self)print("reached "super(__init__(print(" "class (ab)def __init__(self)super(__init__( (reached reached the solution works fine here because in python super consider the child before parentwhich is discussed in section super child before parent please see the order of output as well math problem this section summarizes the above section using math problem herewe want to calculate ( )where inheritance with super |
4,529 | solution this is the first solution__init__ function of two classes are invoked explicitly the only problem here is that the solution does not depend on the order of inheritancebut on the order of invocationi if we exchange the lines and the solution will change mathproblem py class plus (object)def __init__(selfvalue)self value value class multiply (object)def __init__(selfvalue)self value value class solution(multiply plus )def __init__(selfvalue)self value value multiply __init__(selfself valueplus __init__(selfself values solution( print( value problem with super one of the problem with super is thatthe top level super(function does not work if it has some input arguments if we look the output of following code carefullythen we will find that error is generated after reaching to class plus when class plus uses the super()then it calls the metaclass' ( object__init__ functionwhich does not take any argument hence it generates the error 'object __init__(takes no parametersto solve this problemwe need to create another class as shown in next section mathproblem py class plus (object)def __init__(selfvalue)print("plus reached"self value value super(__init__(self valueprint("bye from plus "class multiply (object)def __init__(selfvalue)print("multiply reached"self value value super(__init__(self valueprint("bye from multiply "class solution(multiply plus )def __init__(selfvalue)self value value super(__init__(self value(continues on next page inheritance with super |
4,530 | (continued from previous pages solution( print( valuemultiply reached plus reached typeerrorobject __init__(takes no parameters solution to solve the abovewe need to create another classand inherit it in classes plus and multiply as belowin below codemathclass is createdwhose init function takes one argument sincemathclass does not use super functiontherefore above error will not generate here nextwe need to inherit this class in plus and multiply for proper working of the codeas shown below furtherbelow code depends on order of inheritance now mathproblem py class mathclass(object)def __init__(selfvalue)print("mathclass reached"self value value print("bye from mathclass"class plus (mathclass)def __init__(selfvalue)print("plus reached"self value value super(__init__(self valueprint("bye from plus "class multiply (mathclass)def __init__(selfvalue)print("multiply reached"self value value super(__init__(self valueprint("bye from multiply "class solution(multiply plus )def __init__(selfvalue)self value value super(__init__(self values solution( print( value multiply reached plus reached mathclass reached bye from mathclass bye from plus bye from multiply #uncomment below to see the method resolution order print(help(solution)(continues on next page inheritance with super |
4,531 | (continued from previous pageclass solution(multiply plus method resolution ordersolution multiply plus mathclass builtins object conclusion in this sectionwe saw the functionality of the super(function it is shown that super(consider the child class first and then parent classes in the order of inheritance alsohelp command is used for observing the 'method resolution orderi hierarchy of the inheritance generators any function that uses the 'yieldstatement is the generator each yield temporarily suspends processingremembering the location execution state (including local variables and pending try-statementswhen the generator iterator resumesit picks-up where it left-off (in contrast to functions which start fresh on every invocationfeed iterations typicallyit is used to feed iterations as belowgeneratorex py def countdown( )while ( > )yield - for in countdown( )print( print( countdown( print(next( ) print(next( ) print(next( ) print(next( )traceback (most recent call last)file "rectangle py"line in print(next( )stopiteration if the generator exits without yielding another valuea stopiteration exception is raised receive values 'yieldcan receive value too calling the function creates the generator instancewhich needs to be advance to next yield using 'nextcommand then generator is ready to get the inputsas shown below generators |
4,532 | generatorex py def rxmsg()while trueitem yield print("message "itemmsg rxmsg(print(msgnext(msgsend resumes the execution and "sendsa value into the generator function msg send("hello"msg send("world"send and receive values both send and receive message can be combined together in generator alsogenerator can be closedand next(operation will generate error if it is used after closing the generatoras shown belowgeneratorex py def rxmsg()while trueitem yield yield("message ackitemmsg rxmsg(next(msgm msg send("hello"print( message ackhello next(msgm msg send("world"print( message ackworld msg close(close the generator next(msgtraceback (most recent call last)file "rectangle py"line in next(msgstopiteration return values in generator generator can return values which is displayed with exceptiongeneratorex py def rxmsg()while trueitem yield yield("message ackitemreturn "thanks(continues on next page generators |
4,533 | (continued from previous pagemsg rxmsg(next(msgm msg send("hello"print( message ackhello next(msgtraceback (most recent call last)file "rectangle py"line in next(msgstopiterationthanks msg send("world"print( 'yield fromcommand when yield from is usedit treats the supplied expression as subiterator all values produced by that subiterator are passed directly to the caller of the current generator' methodsgeneratorex py def chain(xy)yield from yield from [ [ for in chain(ab)print(iend=' print(for in chain(chain(aa)chain(ba))print(iend=' generators |
4,534 | unix commands introduction in this we will implement some of the unix commands using 'python 'argparsethe 'argparsemodule is command line interface we will use 'argparsemodule to read the values from the terminal for more detailsplease see the online documentation of the module listing 'argpasemodule argparse_ex py import argparse def mulnum( ) for item in ap *item return parser argparse argumentparser(description="first argparse code" read list of integers parser add_argumenttype=inttype int nargs='+'read multiple values in list dest='integers'name of the attribute returned by argparse help='read list of integer ' parser add_argument'- ''--product'name - or --product dest='multiply'by default 'dest=productaction='store_const'store values const=mulnumcall function 'mulnumhelp='product of integers parser add_argument'--sum'dest='accumulate'(continues on next page |
4,535 | (continued from previous page action='store_const'const=suminbuilt method 'sumto add the values of list help='sum of integers args parser parse_args(save arguments in args if --sum is in command if args accumulatesum args accumulate(args integersprint("sum ="sum if '- or --productis in command if args multiply !noneif args multiply is not nonepass arg integers to arg multiplywhich calls function 'mulnumproduct args multiply(args integersprint("product "product ######execution ################### #######help ###########python argparse_ex py - (or python argparse_ex py --helpusageargparse_ex py [- [- [--sumintegers [integers first argparse code positional argumentsintegers read list of integer optional arguments- --help show this help message and exit - --product product of integers --sum sum of integers ###########results ########python argparse_ex py --sum sum python argparse_ex py - product python argparse_ex py --product product python argparse_ex py - --sum sum product python argparse_ex py - --sum sum product 'argparse |
4,536 | find command details create some files and folders inside directory next go to the directory and run following commands we have following files and folder in the current directorytree box py contributor py csv_format csv datamine py data txt expansion py expansion txt mathematician py methodex py price csv price csv price_missing csv price py pythonic py ring py text_format txt unix_commands argparse_ex py cat py file txt file txt wide_text_format txt (show all items which ends with pyfind -name "py/box py /contributor py /datamine py /expansion py /mathematician py /methodex py /price py /pythonic py /ring py /unix_commands/argparse_ex py /unix_commands/cat py (show all items which contains 'xin itfind -name "* */box py /data txt /expansion py /expansion txt /methodex py /text_format txt /unix_commands /unix_commands/argparse_ex py /unix_commands/file txt /unix_commands/file txt /wide_text_format txt (continues on next page find |
4,537 | (continued from previous page(show all directories which contains 'xin itfind -name "* *-type /unix_commands (show all files which contains 'xin itfind -name "* *-type /box py /data txt /expansion py /expansion txt /methodex py /text_format txt /unix_commands/argparse_ex py /unix_commands/file txt /unix_commands/file txt /wide_text_format txt (for more optionssee man pageman find python implementation firstwe need to write the codewhich can traverse through the directories following is the current directory structuretree argparse_ex py cat py tiger txt file txt file txt find_ex py folder dog txt python code to traverse through each directory is shown belowlisting traverse directories using 'pathlib find_ex py from pathlib import path location of directory path('current directory print("all files and folders in current directory:"all_item [ for in iterdir()for in all_itemprint( files in current folder print("\ "print("files in current folder:"(continues on next page find |
4,538 | (continued from previous page files [ for in iterdir(if is_file()for in filesprint( directories in current folder print("\ "directory [ for in iterdir(if is_dir()print("directories in current folder:"for in directoryprint(dbelow is the output for above codepython find_ex py all files and folders in current directoryargparse_ex py cat py file txt file txt find_ex py folder files in current folderargparse_ex py cat py file txt file txt find_ex py directories in current folderf folder below is code to implement the 'findcommandlisting 'findcommand using python find_ex py import argparse import sys from pathlib import path parser argparse argumentparser(description="find command" positional argument when defined without -nargs='*or '?is required for default-positional-arg values read all command line arguments?read one command line arg parser add_argument('location'type=strnargs="*"default=' optional argument when defined with -no 'nargsi it' str (not list of strparser add_argument('--name'type=strdefault="*" possible values are " ""fand "allparser add_argument('--type',type=str,default="all",choices=[" "" ""all"](continues on next page find |
4,539 | (continued from previous page args parser parse_args(save arguments in args loc path(args location[ ] items=[for in loc rglob(args name)if args type ="dand is_dir()items append(lelif args type ="fand is_file()items append(lelif args type ="all"items append( print output for in itemsprint( (show files which starts with ' 'find -name " *-type " /file txt /file txt /find_ex py python find_ex py --name " *file txt file txt find_ex py --type " (show directories which starts with ' 'python find_ex py --name " *--type "df folder python find_ex py --name " *--type "df folder (show everything which starts with ' 'find -name " */ /file txt /file txt /find_ex py /folder python find_ex py --name " * file txt file txt find_ex py folder (show all directoriesfind -type " / /folder (continues on next page find |
4,540 | (continued from previous pagepython find_ex py --type "df folder (read tfrom different locationpython find_ex py /folder --name " *python find_ex py / --name " * /tiger txt python find_ex py --name " */text_format txt /unix_commands/ /tiger txt grep "grepcommand is used to find the pattern in the filee in below code 'dogis search in the file 'file txtgrep "dogfile txt dog nudged cat below is the implementation of 'grepcommand using python grep_ex py import argparse import re from pathlib import path parser argparse argumentparser(description="grep command"positional argument when defined without -nargs='?is required for default-positional-arg values parser add_argument('pattern'type=strnargs= parser add_argument('location'type=strnargs='*'args parser parse_args(save arguments in args loc path(args location[ ]save location ptrn args pattern[ save pattern lines open(locreadlines()for line in linesif re compile(ptrnsearch(line)print(lineend=""the output of 'grepcommand are shown belowgrep "nudfile txt dog nudged cat python grep_ex py "nudfile txt dog nudged cat grep |
4,541 | cat in this sectionwe will implement the command 'catof unix we will write code to read the name of the files from the command line first create few files 'file txtand 'file txtetc and add some contents to it now read these files as shown belowwhich emulates the functionality of 'unix' cat command'listing read files from command line cat py import argparse parser argparse argumentparser(description="first argparse code" read arguments parser add_argumentnargs='+'read multiple values in list dest='files'name of the attribute returned by argparse help='unix "catoperation' line number parser add_argument'- ''--numbers'default 'dest=numbersaction='store_true'help='print line numbers' args parser parse_args(save arguments in args print( "args{args files}"print argument read by 'dest=filesprint( "first element{args files[ ]}"print first element of arg files open and read each files line_no for file_name in args fileswith open(file_name' 'as wif args numbersprint data with line numbers for data in readlines()start from line_no + print("{ : }\ { }format(line_nodata)end=''elseprint data without line numbers data read(print(databelow are the outputs of above codeactual 'catcommand output cat file txt file txt - this is cat cat is pet this is cat cat is pet this is cat cat is pet dog nudged cat duck is sleeping python code output python cat py file txt file txt - this is cat cat is pet this is cat cat is pet this is cat cat is pet (continues on next page cat |
4,542 | (continued from previous page dog nudged cat duck is sleeping notetry both commands without '-nas well run below command to see more functionalities of 'catcommandand try to add some of those to 'cat pyman cat cat |
4,543 | caffe installation in ubuntu prerequisite for gpu supportwe need to install cuda as well ubuntu library installation sudo apt-get install - --force-yes build-essential autoconf libtool libopenblas-dev libgflags-dev '-libgoogle-glog-dev libopencv-dev protobuf-compiler libleveldb-dev liblmdb-dev libhdf -dev libsnappy'-dev libboost-all-dev libssl-dev sudo apt-get install lsb-core sudo apt-get install libyaml-cpp-dev above should work fine if something went wrong then use belowsudo apt-get install libhdf sudo apt-get install libglogsudo apt install libgoogle-glog-dev sudo apt install libboostsudo apt-get install libleveldbsudo apt-get install liblmdbsudo apt-get install libopenblascuda installation download and install cuda (cuda- can be downloaded from cuda- -download-archive?target_os=linux&target_arch= &target_distro=ubuntu&target_version &target_type=deblocalextract cuda-repo-ubuntu-local_- _amd deb and run the below commands sudo dpkg - cuda-repo-ubuntu-local_- _amd deb (press tab after cuda-repo and then look for pub filesudo apt-key add /var/cuda-repo- - -local/ fa af pub sudo apt-get update sudo apt-get install cuda install cudnndownload cudnn (dec )for cuda cudnn library for linuxwhich is available at below linkextract cudnn- -linux- - tgz and run below commands (do not go inside the extracted folder 'cuda'sudo cp cuda/include/cudnn /usr/local/cuda/include (continues on next page |
4,544 | by mark lutz copyright ( mark lutz all rights reserved printed in the united states of america published by 'reilly mediainc gravenstein highway northsebastopolca 'reilly books may be purchased for educationalbusinessor sales promotional use online editions are also available for most titles (corporate/institutional sales department( - or corporate@oreilly com editorjulie steele production editorteresa elsey proofreaderteresa elsey indexerlucie haskins cover designerkaren montgomery interior designerdavid futato illustratorrobert romano printing historyoctober march august december first edition second edition third edition fourth edition nutshell handbookthe nutshell handbook logoand the 'reilly logo are registered trademarks of 'reilly mediainc programming pythonthe image of an african rock pythonand related trade dress are trademarks of 'reilly mediainc many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks where those designations appear in this bookand 'reilly mediainc was aware of trademark claimthe designations have been printed in caps or initial caps while every precaution has been taken in the preparation of this bookthe publisher and author assume no responsibility for errors or omissionsor for damages resulting from the use of the information contained herein isbn- - [qg |
4,545 | preface xxiii part the beginning sneak preview "programming pythonthe short storythe task step representing records using lists using dictionaries step storing records persistently using formatted files using pickle files using per-record pickle files using shelves step stepping up to oop using classes adding behavior adding inheritance refactoring code adding persistence other database options step adding console interaction console shelve interface step adding gui gui basics using oop for guis getting input from user gui shelve interface step adding web interface cgi basics |
4,546 | using query strings and urllib formatting reply text web-based shelve interface the end of the demo part ii system programming system tools "the os path to knowledgewhy python herethe next five system scripting overview python system modules module documentation sources paging documentation strings custom paging script string method basics other string concepts in python xunicode and bytes file operation basics using programs in two ways python library manuals commercially published references introducing the sys module platforms and versions the module search path the loaded modules table exception details other sys module exports introducing the os module tools in the os module administrative tools portability constants common os path tools running shell commands from scripts other os module exports script execution context " ' like to have an argumentpleasecurrent working directory cwdfilesand import paths cwd and command lines vi table of contents |
4,547 | parsing command-line arguments shell environment variables fetching shell variables changing shell variables shell variable fine pointsparentsputenvand getenv standard streams redirecting streams to files and programs redirected streams and user interaction redirecting streams to python objects the io stringio and io bytesio utility classes capturing the stderr stream redirection syntax in print calls other redirection optionsos popen and subprocess revisited file and directory tools "erase your hard drive in five easy steps!file tools the file object model in python using built-in file objects binary and text files lower-level file tools in the os module file scanners directory tools walking one directory walking directory trees handling unicode filenames in xlistdirwalkglob parallel system tools "telling the monkeys what to doforking processes the fork/exec combination threads the _thread module the threading module the queue module previewguis and threads more on the global interpreter lock program exits sys module exits os module exits shell command exit status codes process exit status and shared state table of contents vii |
4,548 | interprocess communication anonymous pipes named pipes (fifossocketsa first look signals the multiprocessing module why multiprocessingthe basicsprocesses and locks ipc toolspipesshared memoryand queues starting independent programs and much more why multiprocessingthe conclusion other ways to start programs the os spawn calls the os startfile call on windows portable program-launch framework other system tools coverage complete system programs "the greps of wratha quick game of "find the biggest python filescanning the standard library directory scanning the standard library tree scanning the module search path scanning the entire machine printing unicode filenames splitting and joining files splitting files portably joining files portably usage variations generating redirection web pages page template file page generator script regression test script running the test driver copying directory trees comparing directory trees finding directory differences finding tree differences running the script verifying backups reporting differences and other ideas viii table of contents |
4,549 | greps and globs and finds rolling your own find module cleaning up bytecode files python tree searcher visitorwalking directories "++editing files in directory trees (visitorglobal replacements in directory trees (visitorcounting source code lines (visitorrecoding copies with classes (visitorother visitor examples (externalplaying media files the python webbrowser module the python mimetypes module running the script automated program launchers (external part iii gui programming graphical user interfaces "here' looking at youkidgui programming topics running the examples python gui development options tkinter overview tkinter pragmatics tkinter documentation tkinter extensions tkinter structure climbing the gui learning curve "hello worldin four lines (or lesstkinter coding basics making widgets geometry managers running gui programs tkinter coding alternatives widget resizing basics configuring widget options and window titles one more for old timessake packing widgets without saving them adding buttons and callbacks widget resizing revisitedexpansion table of contents ix |
4,550 | lambda callback handlers deferring calls with lambdas and object references callback scope issues bound method callback handlers callable class object callback handlers other tkinter callback protocols binding events adding multiple widgets widget resizing revisitedclipping attaching widgets to frames layoutpacking order and side attachments the packer' expand and fill revisited using anchor to position instead of stretch customizing widgets with classes standardizing behavior and appearance reusable gui components with classes attaching class components extending class components standalone container classes the end of the tutorial python/tkinter for tcl/tk converts tkinter tourpart "widgets and gadgets and guisoh my!this topics configuring widget appearance top-level windows toplevel and tk widgets top-level window protocols dialogs standard (commondialogs the old-style dialog module custom dialogs binding events other bind events message and entry message entry laying out input forms tkinter "variablesand form layout alternatives checkbuttonradiobuttonand scale checkbuttons table of contents |
4,551 | scales (slidersrunning gui code three ways attaching frames independent windows running programs images fun with buttons and pictures viewing and processing images with pil pil basics displaying other image types with pil creating image thumbnails with pil tkinter tourpart "on today' menuspamspamand spammenus top-level window menus frameand menubutton-based menus windows with both menus and toolbars listboxes and scrollbars programming listboxes programming scroll bars packing scroll bars text programming the text widget adding text-editing operations unicode and the text widget advanced text and tag operations canvas basic canvas operations programming the canvas widget scrolling canvases scrollable canvases and image thumbnails using canvas events grids why gridsgrid basicsinput forms revisited comparing grid and pack combining grid and pack making gridded widgets expandable laying out larger tables with grid time toolsthreadsand animation using threads with tkinter guis table of contents xi |
4,552 | simple animation techniques other animation topics the end of the tour other widgets and options gui coding techniques "building better mousetrapguimixincommon tool mixin classes widget builder functions mixin utility classes guimakerautomating menus and toolbars subclass protocols guimaker classes guimaker self-test bigguia client demo program shellguiguis for command-line tools generic shell-tools display application-specific tool set classes adding gui frontends to command lines guistreamsredirecting streams to widgets using redirection for the packing scripts reloading callback handlers dynamically wrapping up top-level window interfaces guisthreadsand queues placing data on queues placing callbacks on queues more ways to add guis to non-gui code popping up gui windows on demand adding gui as separate programsockets ( second lookadding gui as separate programcommand pipes the pydemos and pygadgets launchers pydemos launcher bar (mostly externalpygadgets launcher bar complete gui programs "pythonopen sourceand camarosexamples in other this strategy pyedita text editor program/object running pyedit pyedit changes in version (third editionpyedit changes in version (fourth editionxii table of contents |
4,553 | pyphotoan image viewer and resizer running pyphoto pyphoto source code pyviewan image and notes slideshow running pyview pyview source code pydrawpainting and moving graphics running pydraw pydraw source code pyclockan analog/digital clock widget quick geometry lesson running pyclock pyclock source code pytoea tic-tac-toe game widget running pytoe pytoe source code (externalwhere to go from here part iv internet programming network scripting "tune inlog onand drop outinternet scripting topics running examples in this part of the book python internet development options plumbing the internet the socket layer the protocol layer python' internet library modules socket programming socket basics running socket programs locally running socket programs remotely spawning clients in parallel talking to reserved ports handling multiple clients forking servers threading servers standard library server classes multiplexing servers with select summarychoosing server scheme table of contents xiii |
4,554 | stream redirection utility simple python file server running the file server and clients adding user-interface frontend client-side scripting "socket to me!ftptransferring files over the net transferring files with ftplib using urllib to download files ftp get and put utilities adding user interface transferring directories with ftplib downloading site directories uploading site directories refactoring uploads and downloads for reuse transferring directory trees with ftplib uploading local trees deleting remote trees downloading remote trees processing internet email unicode in python and email tools popfetching email mail configuration module pop mail reader script fetching messages fetching email at the interactive prompt smtpsending email smtp mail sender script sending messages sending email at the interactive prompt emailparsing and composing mail content message objects basic email package interfaces in action unicodeinternationalizationand the python email package console-based email client running the pymail console client the mailtools utility package initialization file mailtool class mailsender class mailfetcher class xiv table of contents |
4,555 | self-test script updating the pymail console client nntpaccessing newsgroups httpaccessing websites the urllib package revisited other urllib interfaces other client-side scripting options the pymailgui client "use the sourcelukesource code modules and size why pymailguirunning pymailgui presentation strategy major pymailgui changes new in version and (third editionnew in version (fourth editiona pymailgui demo getting started loading mail threading model load server interface offline processing with save and open sending email and attachments viewing email and attachments email replies and forwards and recipient options deleting email pop message numbers and synchronization handling html content in email mail content internationalization support alternative configurations and accounts multiple windows and status messages pymailgui implementation pymailguithe main module sharednamesprogram-wide globals listwindowsmessage list windows viewwindowsmessage view windows messagecachemessage cache manager popuputilgeneral-purpose gui pop ups wraplinesline split tools html textextracting text from html (prototypepreviewmailconfiguser configurations table of contents xv |
4,556 | pymailguihelpuser help text and display altconfigsconfiguring for multiple accounts ideas for improvement server-side scripting "ohwhat tangled web we weavewhat' server-side cgi scriptthe script behind the curtain writing cgi scripts in python running server-side examples web server options running local web server the server-side examples root page viewing server-side examples and output climbing the cgi learning curve first web page first cgi script adding pictures and generating tables adding user interaction using tables to lay out forms adding common input devices changing input layouts passing parameters in hardcoded urls passing parameters in hidden form fields saving state information in cgi scripts url query parameters hidden form input fields http "cookiesserver-side databases extensions to the cgi model combining techniques the hello world selector checking for missing and invalid inputs refactoring code for maintainability step sharing objects between pages-- new input form step reusable form mock-up utility step putting it all together-- new reply script more on html and url escapes url escape code conventions python html and url escape tools escaping html code escaping urls xvi table of contents |
4,557 | transferring files to clients and servers displaying arbitrary server files on the client uploading client files to the server more than one way to push bits over the net the pymailcgi server "things to do when visiting chicagothe pymailcgi website implementation overview new in this fourth edition (version new in the prior edition (version presentation overview running this examples the root page configuring pymailcgi sending mail by smtp the message composition page the send mail script error pages common look-and-feel using the send mail script outside browser reading pop email the pop password page the mail selection list page passing state information in url link parameters security protocols the message view page passing state information in html hidden input fields escaping mail text and passwords in html processing fetched mail reply and forward delete deletions and pop message numbers utility modules external components and configuration pop mail interface pop password encryption common utilities module web scripting trade-offs pymailcgi versus pymailgui the web versus the desktop other approaches table of contents xvii |
4,558 | databases and persistence "give me an order of persistencebut hold the picklespersistence options in python dbm files using dbm files dbm detailsfilesportabilityand close pickled objects using object pickling pickling in action pickle detailsprotocolsbinary modesand _pickle shelve files using shelves storing built-in object types in shelves storing class instances in shelves changing classes of objects stored in shelves shelve constraints pickled class constraints other shelve limitations the zodb object-oriented database the mostly missing zodb tutorial sql database interfaces sql interface overview an sql database api tutorial with sqlite building record dictionaries tying the pieces together loading database tables from files sql utility scripts sql resources ormsobject relational mappers pyforma persistent object viewer (external data structures "roses are redviolets are bluelists are mutableand so is set fooimplementing stacks built-in options stack module stack class customizationperformance monitors optimizationtuple tree stacks xviii table of contents |
4,559 | timing the improvements implementing sets built-in options set functions set classes optimizationmoving sets to dictionaries adding relational algebra to sets (externalsubclassing built-in types binary search trees built-in options implementing binary trees trees with both keys and values graph searching implementing graph search moving graphs to classes permuting sequences reversing and sorting sequences implementing reversals implementing sorts data structures versus built-insthe conclusion pytreea generic tree object viewer text and language "see jack hack hackjackhackstrategies for processing text in python string method utilities templating with replacements and formats parsing with splits and joins summing columns in file parsing and unparsing rule strings regular expression pattern matching the re module first examples string operations versus patterns using the re module more pattern examples scanning header files for patterns xml and html parsing xml parsing in action html parsing in action advanced language tools custom language parsers table of contents xix |
4,560 | the parser' code adding parse tree interpreter parse tree structure exploring parse trees with the pytree gui parsers versus python pycalca calculator program/object simple calculator gui pycalc-- "realcalculator gui python/ integration " am lost at cextending and embedding extending python in coverview simple extension module the swig integration code generator simple swig example wrapping environment calls adding wrapper classes to flat libraries wrapping environment calls with swig wrapping +classes with swig simple +extension class wrapping the +class with swig using the +class in python other extending tools embedding python in coverview the embedding api what is embedded codebasic embedding techniques running simple code strings running code strings with results and namespaces calling python objects running strings in dictionaries precompiling strings to bytecode registering callback handler objects registration implementation using python classes in other integration topics xx table of contents |
4,561 | conclusionpython and the development cycle "that' the end of the booknow here' the meaning of life"something' wrong with the way we program computersthe "gilligan factordoing the right thing the static language build cycle artificial complexities one language does not fit all enter python but what about that bottleneckpython provides immediate turnaround python is "executable pseudocodepython is oop done right python fosters hybrid applications on sinking the titanic so what' "pythonthe sequel"in the final analysis index table of contents xxi |
4,562 | "and now for something completely different this book explores ways to apply the python programming language in common application domains and realistically scaled tasks it' about what you can do with the language once you've mastered its fundamentals this book assumes you are relatively new to each of the application domains it covers-guisthe internetdatabasessystems programmingand so on--and presents each from the ground upin tutorial fashion along the wayit focuses on commonly used tools and librariesrather than language fundamentals the net result is resource that provides readers with an in-depth understanding of python' roles in practicalrealworld programming work as subthemethis book also explores python' relevance as software development tool-- role that many would classify as well beyond those typically associated with "scripting in factmany of this book' examples are scaled specifically for this purposeamong thesewe'll incrementally develop email clients that top out at thousands of lines of code programming at this full scale will always be challenging workbut we'll find that it' also substantially quicker and easier when done with python this fourth edition has been updated to present the languagelibrariesand practice of python specificallyits examples use python --the most recent version of python at the time of writing--and its major examples were tested successfully under the third alpha release of python just prior to publicationbut they reflect the version of the language common to the entire line this edition has also been reorganized in ways that both streamline some of its former material and allow for coverage of newly emerged tools and topics because this edition' readership will include both newcomers as well as prior edition veteransi want to use this preface to expand on this book' purpose and scope before we jump into code xxiii |
4,563 | this book is tutorial introduction to using python in common application domains and tasks it teaches how to apply python for system administrationguisand the weband explores its roles in networkingdatabasesfrontend scripting layerstext processingand more although the python language is used along the waythis book' focus is on application to real-world tasks instead of language fundamentals this book' ecosystem because of its scopethis book is designed to work best as the second of two-volume setand to be supplemented by third most importantlythis book is an applications programming follow-up to the core language book learning pythonwhose subjects are officially prerequisite material here here' how the three books are relatedlearning python covers the fundamentals of python programming in depth it focuses on the core python languageand its topics are prerequisite to this book programming pythonthis bookcovers the application of python to real-world programming tasks it focuses on libraries and toolsand it assumes you already know python fundamentals python pocket reference provides quick reference to details not listed exhaustively here it doesn' teach muchbut it allows you to look up details fast in some sensethis book is to application programming what learning python is to the core language-- gradual tutorialwhich makes almost no assumptions about your background and presents each topic from the ground up by studying this book' coverage of web basicsfor exampleyou'll be equipped to build simple websitesand you will be able to make sense of more advanced frameworks and tools as your needs evolve guis are similarly taught incrementallyfrom basic to advanced in additionthis book is designed to be supplemented by the quick-reference book python pocket referencewhich provides the small details finessed here and serves as resource for looking up the fine points that book is reference onlyand is largely void of both examples and narrativebut it serves to augment and complement both learning python' fundamentals and programming python' applications because its current fourth edition gives both python and versions of the tools it coversthat book also serves as resource for readers transitioning between the two python lines (more on this in momentdisclosurei am the author of all three books mentioned in this sectionwhich affords me the luxury of tightly controlling their scopes in order to avoid overlap it also means that as an authori try to avoid commenting on the many other python books availablesome of which are very good and may cover topics not addressed in any of my own books please see the web for other python resources all three of my books reflect my years on the python training trail and stem from the original programming python written back in <insert grizzled prospector photo herexxiv preface |
4,564 | because of the scopes carved out by the related books just mentionedthis book' scope follows two explicit constraintsit does not cover python language fundamentals it is not intended as language reference the former of these constraints reflects the fact that core language topics are the exclusive domain of learning pythonand encourage you to consult that book before tackling this one if you are completely new to the python languageas its topics are assumed here some language techniques are shown by example in this book tooof courseand the larger examples here illustrate how core concepts come together into realistic programs oopfor exampleis often best sampled in the context of the larger programs we'll write here officiallythoughthis book assumes you already know enough python fundamentals to understand its example code our focus here is mostly on libraries and toolsplease see other resources if the basic code we'll use in that role is unclear the latter of the two constraints listed above reflects what has been common misconception about this book over the years (indeedthis book might have been better titled applying python had we been more clairvoyant in want to make this as clear as canthis is not reference book it is tutorial although you can hunt for some details using the index and table of contentsthis book is not designed for that purpose insteadpython pocket reference provides the sort of quick reference to details that you'll find useful once you start writing nontrivial code on your own there are other reference-focused resources availableincluding other books and python' own reference manuals set herethe goal is gradual tutorial that teaches you how to apply python to common tasks but does not document minute details exhaustively about this fourth edition if this is the first edition of this book you've seenyou're probably less interested in recent changesand you should feel free to skip ahead past this section for readers of prior editionsthoughthis fourth edition of this book has changed in three important waysit' been updated to cover python (onlyit' been slimmed down to sharpen its focus and make room for new topics it' been updated for newly emerged topics and tools in the python world the first of these is probably the most significant--this edition employs the python languageits version of the standard libraryand the common practice of its users to better explain how this and the other two changes take shape in this editionthoughi need to fill in few more details preface xxv |
4,565 | because the prior versions of this book were widely readhere is quick rundown of some of the most prominent specific changes in this editionits existing material was shortened to allow for new topics the prior edition of this book was also -page volumewhich didn' allow much room for covering new python topics (python ' unicode orientation alone implies much new materialluckilyrecent changes in the python world have allowed us to pare down some less critical existing material this time aroundin order to free up room for new coverage depth was not sacrificed in the processof courseand this is still just as substantial book as before in generalthoughavoiding new growth was primary goal of this updatemany of the other specific changes and removals 'll mention below were madein partto help accommodate new topics it covers (onlythis book' examples and narrative have been updated to reflect and use the version of python python is no longer supported hereexcept where and pythons overlap although the overlap is large enough to make this of use to readers toothis is now officially -only text this turns out to be major factor behind the lack of growth in this edition by restricting our scope to python --the incompatible successor to the python lineand considered to be python' future--we were able to avoid doubling the coverage size in places where the two python lines differ this version limit is especially important in book like this that is largely about more advanced exampleswhich can be listed in only one version' style for readers who still straddle the and worldsi'll say more about python changes later in this preface probably the most significant -related change described there is the new internationalization support in pyedit and pymailguithough had unicode tooits new prominence in almost forces such systems to rethink their former ascii-only ways inclusion of newly emerged libraries and tools since the prior editiona variety of new libraries and tools have either come online or risen in popularityand they get new mention here this includes new standard library tools such as subprocess (in and and multiprocessing (in )as well as new third-party web frameworks and orm database toolkits most of these are not covered extensively (many popular third-party extensions are complex systems in their own right and are best covered by dedicated books)but they are at the least introduced in summary form here for examplepython ' new tkinter ttk tk themed widget set shows up in nowbut only brieflyas rulethis edition prefers to mention such extensions in passingrather than attempting to show you code without adequate explanation xxvi preface |
4,566 | 've removed all the instructions for using and running program examples insteadplease consult the readme file in the examples distribution for example usage details moreovermost of the original acknowledgments are gone here because they are redundant with those in learning pythonsince that book is now considered prerequisiteduplication of material here is unwarranted description of book contents was also deletedplease see the table of contents for preview of this book' structure the initial python overview is gone 've removed the prior edition' "managerial summarywhich introduced python' strong pointsprominent usersphilosophiesand so on proselytizing does play an important role in field that sometimes asks the "whyquestions less often than it should indeedif advocacy had not been part of the python experiencewe' probably all be using perl or shell languages todayhoweverthis has now grown completely redundant with similar in learning python since that book is precursor to this onei opted to not devote space to restating "pythonistapropaganda here (fun as it may beinsteadthis book assumes you already know why python is worth usingand we jump right into applying it here the conclusion' postscripts are gone this book' conclusion comes from the first editionand it is now years old naturallysome of it reflects the python mindset from that period more than that of today for exampleits focus on python' role in hybrid applications seemed more important in than in in today' much larger python worldmost python users never deal with linked-in code at all in prior editionsi added postscripts for each edition to elaborate on and update the ideas presented in the book' conclusion these postscripts are gone nowreplaced by short note at the start of the conclusion opted to keep the conclusion itselfthoughbecause it' still relevant to many readers and bears some historic value wellthatplus the jokes the forewords are gone for reasons similar to those of the prior two pointsthe accumulated forewords from the prior three editions were also dropped this time around you can read all about python creator guido van rossum' historical rationale for python' evolution in numerous places on the webif you are so inclined if you are interested in how python has changed technically over the yearssee also the "what' newdocuments that are part of the python standard manuals set (available at www python org/docand installed alongside python on windows and other platformsthe integration part has been reduced to just one 've reduced the extending and embedding part' material to one shorter at the end of the tools partwhich briefly introduces the core concepts in this preface xxvii |
4,567 | todayand those who do already have the skills required to read the larger and more compete example of integration present in the source code of python itself there is still enough to hint at possibilities herebut vast amounts of code have been cutin deference to the better examples you'll find in python' own code the systems programming part was condensed and reworked the former two larger system examples have been merged into one shorter onewith new or greatly rewritten examples in factthis part (part iiwas probably overhauled the most of any part in the book it incorporates new tools such as subprocess and multiprocessingintroduces sockets earlierand removes dated topics and examples still lingering from prior editions franklya few of the fileoriented examples here dated back to the sand were overdue for general refresh the initial in this part was also split into two to make its material easier to read (shell contextincluding streamsgets its own now)and few large program listings here (including the auto-configuring launcher scriptsare now external suggested reading some larger examples were removed (but are available in the examples distributionalong the same linestwo of the larger gui examples in the prior editionpytree and pyformhave been removed insteadtheir updated code is available in the book' examples distribution packageas suggested supplemental reading you'll still find many larger examples covered and listed in this edition--including both guiand web-based renderings of full-featured email clientsalong with image viewerscalculatorsclocksunicode-aware text editorsdrawing programsregression test scriptsand more howeverbecause the code of the examples removed doesn' add much to what is already coveredand because they were already largely self-study examples anyhowi've made them optional and external to the printed text in this edition the advanced internet topics was replaced by brief summaries 've cut the advanced internet topics completelyleaving only simple summaries at the start of the internet part (intentionally mirroring the gui option summaries at the start of the gui partthis includes prior coverage for tools such as the zope web frameworkcomwindows active scripting and asphtmlgenpython server pages (psp)jythonand the now very dated grail system some of these systems still receive honorable mention in the summariesbut none are now presented in any sort of detail summaries of new tools (including many of those listed in the following paragraphwere added to this setbut againin brief fashion with no example code despite authorsbest attempts to foresee the futurethe web domain evolves faster than books like this can for instanceweb frameworks like djangogoogle' app engineturbogearspylonsand web py are now popular alternatives to zope similarlythe net framework supersedes much of com on windowsironpython now provides the same type of integration for net as jython did first xxviii preface |
4,568 | frameworks on the client such as flexsilverlightand pyjamas (generally known today as rich internet applicationsriasculture shift asidethe examples formerly presented in this category were by themselves also insufficient to either teach or do justice to the subject tools rather than including incomplete (and nearly uselesscoverage of tools that are prone to both evolution and demise during this edition' expected lifespani now provide only brief overviews of the current hot topics in the web domainand encourage readers to search the web for more details more to the pointthe goal of the book you're reading is to impart the sort of in-depth knowledge of internet and web fundamentals that will allow you to use more advanced systems wellwhen you're ready to take the leap one exception herethe xml material of this prior was spared and relocated in expanded form to the text processing (where it probably belonged all alongin related veinthe coverage of zope' zodb object-oriented database was retainedalthough it was shortened radically to allow new coverage of orms such as sqlobject and sqlalchemy (againin overview formuse of tools available for today at this writingpython is still in its adoption phaseand some of the third-party tools that this book formerly employed in its examples are still available in python form only to work around this temporary fluxi've changed some code to use alternatives that already support today the most notable of these is the sql database section--this now uses the inprocess sqlite librarywhich is standard part of python and already in formrather than the enterprise-level mysql interface which is still at today luckilythe python portable database api allows scripts to work largely the same on bothso this is minor pragmatic sacrifice of special notethe pil extension used to display jpegs in the gui part was ported to just when it was needed for this updatethanks to fredrik lundh it' still not officially released in form as submit the final draft of this book in july but it should be soonand patches are provided in the book examples package as temporary measure advanced core language topics are not covered here more advanced python language tools such as descriptorspropertiesdecoratorsmetaclassesand unicode text processing basics are all part of the core python language because of thatthey are covered in the fourth edition of learning pythonnot here for exampleunicode text and the changes it implies for filesfilenamessocketsand much more are discussed as encountered herebut the fundamentals of unicode itself are not presented in complete depth some of the topics in this category are arguably application-level related too (or at least of interest to tool builders and api developers in general)but their coverage in learning preface xxix |
4,569 | on these subjects other random bits naturallythere were additional smaller changes made along the way for exampletkinter' grid method is used instead of pack for layout of most input formsbecause it yields more consistent layout on platforms where label font sizes don' match up with entry widget height (including on windows netbook laptopthis edition' development machinethere' also new material scattered throughoutincluding new exploration of redirecting streams to sockets in the internet parta new threaded and unicode-aware "grepdialog and process-wide change tests on exit in the pyedit exampleand other things you are probably better off uncovering along the way than reading further about in this preface also finally replaced some remaining "#comment blocks at the top of source files with docstrings (evenfor consistencyin scripts not meant to be importedthough some "#lines are retained in larger examples to offset the text)changed few lingering "while to "while true"use +more oftenand cleaned up few other cases of now-dated coding patterns old habits may die hardbut such updates make the examples both more functional and more representative of common practice today although new topics were addedall toldfour were cut outright (the nontechnical introductionone of the system example advanced internet topicsand one integration some additional examples and material were trimmed (including pyform and pytree)and focus was deliberately restricted to python and application fundamentals to conserve space what' leftthenthe combined effect of all the changes just outlined is that this edition more concisely and sharply reflects its core focus--that of tutorial introduction to ways to apply python in common programming domains neverthelessas you can tell from this book' page countit is still substantial and in-depth bookdesigned to be first step on your path to mastering realistic applications of python contrary to recent trends (and at some risk of being branded heretic) firmly believe that the job of books like this one is to elevate their readersnot pander to them lowering the intellectual bar does disservice both to readers and to the fields in which they hope to work while that means you won' find as many cartoons in this book as in somethis book also won' insult you by emphasizing entertainment at the expense of technical depth insteadthe goal of my books is to impart sophisticated concepts in satisfying and substantive way and to equip you with the tools you'll need in the real world of software development xxx preface |
4,570 | possible audience in factthat' why the original version of this book later became twowith language basics delegated to learning python moreoverone can make case for distinction between programmerswho must acquire deep software development skillsand scripterswho do not for somea rudimentary knowledge of programming may be enough to leverage system or library that solves the problem at hand that isuntil their coding forays start encroaching on the realm of full-scale software engineering-- threshold that can inspire disappointment at worstbut better appreciation of the challenging nature of this field at best no matter which camp you're fromit' important to understand this book' intent upfront if you're looking for shortcut to proficiency that' light on technical contentyou probably won' be happy with this book (or the software field in generalif your goal is to master programming python wellthoughand have some fun along the wayyou'll probably find this book to be an important piece of your learning experience at the end of the daylearning to program well is much more demanding than implied by some contemporary media if you're willing to invest the focus and effort requiredthoughyou'll find that it' also much more rewarding this is especially true for those who equip themselves for the journey with programmer-friendly tool like python while no book or class can turn you into python "master of the universeby itselfthis book' goal is to help you get thereby shortening your start-up time and providing solid foundation in python' most common application domains python impacts on this book as mentionedthis edition now covers python only python is an incompatible version of the language the core language itself is very similar to python xbut there are substantial changes in both the language and its many standard libraries although some readers with no prior background in may be able to bypass the differencesthe changes had big impact on the content of this edition for the still very large existing python user basethis section documents the most noteworthy changes in this category if you're interested in differencesi also suggest finding copy of the fourth edition of the book python pocket reference described earlier that book gives both and versions of core language structuresbuilt-in functions and exceptionsand many of the standard library modules and tools used in this book though not designed to be reference or version translator per sethe fourth edition of learning python similarly covers both and xand as statedis prerequisite material to this book the goal of this -only programming python is not to abandon the current vast user base in favor of still imaginary one for xit is to help readers with the migrationand avoid doubling the size of an already massive book preface xxxi |
4,571 | luckilymany of the / differences that impact this book' presentation are trivial for instancethe tkinter gui toolkitused extensively in this bookis shown under its tkinter name and package structure onlyits tkinter module incarnation is not described this mostly boils down to different import statementsbut only their python versions are given here similarlyto satisfy module naming conventions ' anydbmqueuethreadstringio stringioand urllib open become dbmqueue_threadio stringioand urllib request urlopenrespectivelyin both python and this edition other tools are similarly renamed on the other hand implies broader idiomatic changes which areof coursemore radical for examplepython ' new unicode awareness has inspired fully internationalized versions of the pyedit text editor and the pymailgui email client examples in this edition (more on this in momentfurthermorethe replacement of os popen with the subprocess module required new examplesthe demise of os path walk in favor of os walk allowed some examples to be trimmedthe new unicode and binary dichotomy of files and strings impacted host of additional existing examples and materialand new modules such as multiprocessing offer new options covered in this edition beyond such library changescore language changes in python are also reflected in this book' example code for instancechanges to ' printraw_inputkeyshas_keymapand apply all required changes here in addition ' new packagerelative import model impacted few examples including mailtools and expression parsersand its different flavor of division forced some minor math updates in canvasbased gui examples such as pyclockpydrawand pyphoto of note herei did not change all string formatting expressions to use the new str formatsince both forms are supported in python and it now appears that they will be either indefinitely or forever in factper "grepwe'll build and run in ' pyedit exampleit seems that this expression still appears over , times in python ' own library code since cannot predict python evolution completelysee the first for more on this if it ever requires updates in an unexpected future also because of the scopethis edition is unable to use some third-party packages that are still in form onlyas described earlier this includes the leading mysql interfacezodbpycryptoand othersas also mentionedpil was ported to for use in this bookbut this required special patch and an official release is still presently pending many of these may be available in form by the time you read these wordsassuming the python world can either break some of the current cross dependencies in packages or adopt new -only tools xxxii preface |
4,572 | as book focused on applications instead of core language fundamentalslanguage changes are not always obtrusive here indeedin retrospect the book learning python may have been affected by core language changes more than this book in most cases heremore example changes were probably made in the name of clarity or functionality than in support of itself on the other handpython does impact much codeand the impacts can be subtle at times readers with python backgrounds will find that while core language changes are often simple to applyupdates required for changes in the standard library are sometimes more far reaching chief among thesepython ' unicode strings have had broad ramifications let' be honestto people who have spent their lives in an ascii worldthe impacts of the unicode model can be downright aggravating at timesas we'll see in this bookit affects file contentfile namespipe descriptorssocketstext in guisinternet protocols such as ftp and emailcgi scriptsand even some persistence tools for better or worseonce we reach the world of applications programming as covered in this bookunicode is no longer an optional topic for many or most python programmers of courseunicode arguably never should have been entirely optional for many programmers in the first place indeedwe'll find that things that may have appeared to work in never really did--treating text as raw byte strings can mask issues such as comparison results across encodings (see the grep utility of ' pyedit for prime example of code that should fail in the face of unicode mismatchespython elevates such issues to potentially every programmer' panorama stillporting nontrivial code to is not at all an insurmountable task moreovermany readers of this edition have the luxury of approaching python as their first python and need not deal with existing code if this is your caseyou'll find python to be robust and widely applicable scripting and programming languagewhich addresses head-on many issues that once lurked in the shadows in python limitationsemailcgi there' one exception that should call out here because of its impact on major book examples in order to make its code relevant to the widest possible audiencethis book' major examples are related to internet email and have much new support in this edition for internationalization and unicode in this domain ' pymailgui and ' pymailcgiand all the prior examples they reusefall into this category this includes the pyedit text editor--now unicode-aware for filesdisplayand greps on this frontthere is both proverbial good news and bad the good news is that in the endwe will be able to develop the feature-rich and fully internationalized pymailgui email client in this bookusing the email package as it currently exists this will include support for arbitrary encodings in both text content and message headersfor preface xxxiii |
4,573 | some cost in workaround complexity in python unfortunatelyas we'll learn in the email package in python has number of issues related to str/bytes combinations in python for examplethere' no simple way to guess the encoding needed to convert mail bytes returned by the poplib module to the str expected by the email parser moreoverthe email package is currently broken altogether for some types of messagesand it has uneven or typespecific support for some others this situation appears to be temporary some of the issues encountered in this book are already scheduled to be repaired (in factone such fix in required last-minute patch to one of this book' workarounds in furthermorea new version of email is being developed to accommodate the unicode/bytes dichotomy more accuratelybut it won' materialize until long after this book is publishedand it might be backward-incompatible with the current package' apimuch like python itself because of thatthis book both codes workarounds and makes some assumption along the waybut please watch its website (described aheadfor required updates in future pythons one upside here is that the dilemmas posed neatly reflect those common in realistic programming--an underlying theme of this text these issues in the email package are also inherited by the cgi module for cgi file uploadswhich are in large measure broken in cgi scripts are basic technique eclipsed by many web frameworks todaybut they still serve as an entry-level way to learn web fundamentals and are still at the heart of many larger toolkits future fix seems likely for this flaw as wellbut we have to make do with nonbinary cgi file uploads for this edition in and and limited email attachments in pymailcgi this seems less than ideal nearly two years after ' releasebut such is life in the dynamic worlds of both software development at large and books that aim to lead the curve instead of following it using book examples because this book' examples form much of its contenti want to say few words about them up front where to look for examples and updates as beforeexamplesupdatescorrectionsand supplements for this book will be maintained at the author' websitewhich lives officially at the following urlthis page at my book support website will contain links to all supplemental information related to this version of the book because don' own that domain namethoughif xxxiv preface |
4,574 | fallback optionif neither of those links worktry general web search (whichof courseis what most readers will probably try first anyhowwherever it may livethis website (as well as 'reilly'sdescribed in the next sectionis where you can fetch the book examples distribution package--an archive file containing all of the book' examplesas well as some extras that are mentioned but not listed in the book itself to work along without having to type the examples manuallydownload the packageunpack itand consult its readme txt file for usage details 'll describe how example labels and system prompts in this book imply file locations in the package when we use our first script in the first as for the first three editionsi will also be maintaining an informal "blogon this website that describes python changes over time and provides general book-related notes and updates that you should consider supplemental appendix to this text 'reilly' website for this bookdescribed later in this prefacealso has an errata report systemand you can report issues at either my site or 'reilly' tend to keep my book websites more up to datebut it' not impossible that 'reilly' errata page may supersede mine for this edition in any eventyou should consider the union of these two lists to be the official word on book corrections and updates example portability the examples in this book were all developedtestedand run under windows and python the book' major examples were all tested and ran successfully on the upcoming python too (its alpha release)just before the book went to the printerso most or all of this book applies to python as well in additionthe code of and handful of parallel programming examples were run under cygwin on windows to emulate unix environment although python and its libraries are generally platform neutralsome of this book' code may require minor changes to run on other platformssuch as mac os xlinuxand other unix variants the tkinter gui examplesas well as some systems programming scriptsmay be especially susceptible to platform differences some portability issues are pointed out along the waybut others may not be explicitly noted since had neither time nor budget to test on and accommodate all possible machines that readers might use over the lifespan of this bookupdates for platform-specific behaviors will have to fall into the suggested exercises category if you find platform dependency and wish to submit patch for itthoughplease see the updates site listed earlieri'll be happy to post any platform patches from readers there preface xxxv |
4,575 | the book examples package described earlier also includes portable example demo launcher scripts named pydemos and pygadgetswhich provide quick look at some of this book' major guiand web-based examples these scripts and their launcherslocated at the top of the examples treecan be run to self-configure program and module search pathsand so can generally be run immediately on compatible platformsincluding windows see the package' readme files as well as the overviews near the end of and for more on these scripts code reuse policies we now interrupt this preface for word from the legal department this book is here to help you get your job done in generalyou may use the code in this book in your programs and documentation you do not need to contact us for permission unless you're reproducing significant portion of the code for examplewriting program that uses several chunks of code from this book does not require permission selling or distributing cd-rom of examples from 'reilly books does require permission answering question by citing this book and quoting example code does not require permission incorporating significant amount of example code from this book into your product' documentation does require permission we appreciatebut do not requireattribution an attribution usually includes the titleauthorpublisherand isbn for example"programming pythonfourth editionby mark lutz ( 'reillycopyright mark lutz- - contacting 'reilly described my own examples and updates sites in the prior section in addition to that adviceyou can also address comments and questions about this book to the publishero'reilly mediainc gravenstein highway north sebastopolca (in the united states and canada(international/local(faxas mentionedo'reilly maintains web page for this bookwhich lists errataexamplesand any additional information you can access this page atto comment or ask technical questions about this booksend email tobookquestions@oreilly com xxxvi preface |
4,576 | 'reilly networksee the 'reilly website atconventions used in this book the following font conventions are used in this bookitalic used for file and directory namesto emphasize new terms when first introducedand for some comments within code sections constant width used for code listings and to designate modulesmethodsoptionsclassesfunctionsstatementsprogramsobjectsand html tags constant width bold used in code sections to show user input constant width italic used to mark replaceables this icon designates note related to the nearby text this icon designates warning related to the nearby text acknowledgments acknowledged numerous people in the preface of learning pythonfourth editionless than year agobecause that book is precursor to this oneand because the set is largely the samei won' repeat the list in its entirety here in shortthoughi' grateful too'reillyfor promoting pythonand publishing "meatybooks in the open source domain the python communitywhich has occupied sizeable portions of my world since the thousands of students who attended the python classes 've taught since preface xxxvii |
4,577 | 've written since monty pythonpython' namesakefor so many great bits to draw from (more in the next although writing is ultimately solitary taskthe ideas that spring forth owe much to the input of many ' thankful for all the feedback 've been fortunate to receive over the last yearsboth from classes and from readers students really are the best teachers of teachers on the (overlypersonal fronti' like to thank my brothers and sister for old daysas well as my childrenmichaelsamanthaand roxannefor bragging rights and ' especially thankful for my wifeverawho somehow managed to append very good things to this otherwise immutable object --mark lutzjuly xxxviii preface |
4,578 | as discussedthis book won' devote much space to python fundamentalsand we'll defer an abstract discussion of python roles until the conclusionafter you've had chance to see it in action firsthand if you are looking for concise definition of this book' topicthoughtry thispython is general-purposeopen source computer programming language it is optimized for software qualitydeveloper productivityprogram portabilityand component integration python is used by at least hundreds of thousands of developers around the world in areas such as internet scriptingsystems programminguser interfacesproduct customizationnumeric programmingand more it is generally considered to be among the top four or five most widely-used programming languages in the world today as popular language focused on shrinking development timepython is deployed in wide variety of products and roles counted among its current user base are googleyoutubeindustrial light magicesrithe bittorrent file sharing systemnasa' jet propulsion labthe game eve onlineand the national weather service python' application domains range from system administrationwebsite developmentcell phone scriptingand education to hardware testinginvestment analysiscomputer gamesand spacecraft control among other thingspython sports remarkably simplereadableand maintainable syntaxintegration with external components coded in other languagesa multiparadigm designwith oopfunctionaland modular structuresand vast collection of precoded interfaces and utilities its tool set makes it flexible and agile languageideal for both quick tactical tasks as well as longer-range strategic application development efforts although it is general-purpose languagepython is often called scripting language because it makes it easy to utilize and direct other software components perhaps python' best assetthoughis simply that it makes software development more rapid and enjoyable there is class of people for whom programming is an end in itself they enjoy the challenge they write software for the pure pleasure of doing so and often view commercial or career reward as secondary consequence this is the class that largely invented the internetopen sourceand python this is also the class that has historically been primary audience for this book as they've often relayedwith tool like pythonprogramming can be just plain fun to truly understand howread onthough something of side effectmuch of this book serves as demonstration of python' ideals in action in real-world code as we'll seeespecially when combined with toolkits for guiswebsitessystems programmingand so onpython serves as enabling technology preface xxxix |
4,579 | the beginning this part of the book gets things started by taking us on quick tour that reviews python fundamental prerequisites and introduces some of the most common ways it is applied this kicks things off by using simple example--recording information about people--to briefly introduce some of the major python application domains we'll be studying in this book we'll migrate the same example through multiple steps along the waywe'll meet databasesguiswebsitesand more this is something of demo designed to pique your interest we won' learn the full story herebut we'll have chance to see python in action before digging into the details this also serves as review of some core language ideas you should be familiar with before starting this booksuch as data representation and object-oriented programming (oopthe point of this part of the book is not to give you an in-depth look at pythonbut just to let you sample its application and to provide you with quick look at some of python' broader goals and purposes |
4,580 | sneak preview "programming pythonthe short storyif you are like most peoplewhen you pick up book as large as this oneyou' like to know little about what you're going to be learning before you roll up your sleeves that' what this is for--it provides demonstration of some of the kinds of things you can do with pythonbefore getting into the details you won' learn the full story hereand if you're looking for complete explanations of the tools and techniques applied in this you'll have to read on to later parts of the book the point here is just to whet your appetitereview few python basicsand preview some of the topics to come to do thisi'll pick fairly simple application task--constructing database of records--and migrate it through multiple stepsinteractive codingcommand-line toolsconsole interfacesguisand simple web-based interfaces along the waywe'll also peek at concepts such as data representationobject persistenceand objectoriented programming (oop)explore some alternatives that we'll revisit later in the bookand review some core python ideas that you should be aware of before reading this book ultimatelywe'll wind up with database of python class instanceswhich can be browsed and changed from variety of interfaces 'll cover additional topics in this bookof coursebut the techniques you will see here are representative of some of the domains we'll explore later and againif you don' completely understand the programs in this don' worry because you shouldn' --not yet anyway this is just python demo we'll fill in the rest of the details soon enough for nowlet' start off with bit of fun |
4,581 | aspects of the running example used in this -the characters here are similar in spirit to those in the oop tutorial in that bookand the later class-based examples here are essentially variation on theme despite some redundancyi' revisiting the example here for three reasonsit serves its purpose as review of language fundamentalssome readers of this book haven' read learning pythonand the example receives expanded treatment herewith the addition of gui and web interfaces that isthis picks up where learning python left offpushing this core language example into the realm of realistic applications--whichin nutshellreflects the purpose of this book the task imagineif you willthat you need to keep track of information about people for some reason maybe you want to store an address book on your computeror perhaps you need to keep track of employees in small business for whatever reasonyou want to write program that keeps track of details about these people in other wordsyou want to keep records in database--to permanently store lists of people' attributes on your computer naturallythere are off-the-shelf programs for managing databases like these by writing program for this task yourselfhoweveryou'll have complete control over its operation you can add code for special cases and behaviors that precoded software may not have anticipated you won' have to install and learn to use yet another database product and you won' be at the mercy of software vendor to fix bugs or add new features you decide to write python program to manage your people step representing records if we're going to store records in databasethe first step is probably deciding what those records will look like there are variety of ways to represent information about people in the python language built-in object types such as lists and dictionaries are often sufficientespecially if we don' initially care about processing the data we store using lists listsfor examplecan collect attributes about people in positionally ordered way start up your python interactive interpreter and type the following two statementsbob ['bob smith' 'software'sue ['sue jones' 'hardware' sneak preview |
4,582 | (my apologies if you really are bob or suegenerically or otherwise*each record is list of four propertiesnameagepayand job fields to access these fieldswe simply index by positionthe result is in parentheses here because it is tuple of two resultsbob[ ]sue[ ('bob smith' fetch namepay processing records is easy with this representationwe just use list operations for examplewe can extract last name by splitting the name field on blanks and grabbing the last partand we can give someone raise by changing their list in-placebob[ split()[- what' bob' last name'smithsue[ * give sue raise sue ['sue jones' 'hardware'the last-name expression here proceeds from left to rightwe fetch bob' namesplit it into list of substrings around spacesand index his last name (run it one step at time to see howstart-up pointers since this is the first code in this bookhere are some quick pragmatic pointers for referencethis code may be typed in the idle guiafter typing python at shell prompt (or the full directory path to it if it' not on your system path)and so on the characters are python' prompt (not code you type yourselfthe informational lines that python prints when this prompt starts up are usually omitted in this book to save space ' running all of this book' code under python results in any release should be similar (barring unforeseeable python changesof courseapart from some system and integration codemost of this book' examples are run under windows though thanks to python portabilityit generally doesn' matter unless stated otherwise if you've never run python code this way beforesee an introductory resource such as 'reilly' learning python for help with getting started 'll also have few words to say about running code saved in script files later in this noi' serious in the python classes teachi had for many years regularly used the name "bob smith,age and jobs "developerand "manageras supposedly fictitious database record--until class in chicagowhere met student named bob smithwho was and was developer and manager the world is stranger than it seems step representing records |
4,583 | of coursewhat we've really coded so far is just two variablesnot databaseto collect bob and sue into unitwe might simply stuff them into another listpeople [bobsuefor person in peopleprint(personreference in list of lists ['bob smith' 'software'['sue jones' 'hardware'now the people list represents our database we can fetch specific records by their relative positions and process them one at timein loopspeople[ ][ 'sue jonesfor person in peopleprint(person[ split()[- ]person[ * print last names give each raise smith jones for person in peopleprint(person[ ]check new pay now that we have listwe can also collect values from records using some of python' more powerful iteration toolssuch as list comprehensionsmapsand generator expressionspays [person[ for person in peoplepays [ collect all pay pays map((lambda xx[ ])peoplelist(pays[ ditto (map is generator in xsum(person[ for person in people generator expressionsum built-in to add record to the databasethe usual list operationssuch as append and extendwill sufficepeople append(['tom' none]len(people people[- ][ 'tomlists work for our people databaseand they might be sufficient for some programsbut they suffer from few major flaws for one thingbob and sueat this pointare sneak preview |
4,584 | every time we want to extract last name or give raisewe'll have to repeat the kinds of code we just typedthat could become problem if we ever change the way those operations work--we may have to update many places in our code we'll address these issues in few moments field labels perhaps more fundamentallyaccessing fields by position in list requires us to memorize what each position meansif you see bit of code indexing record on magic position how can you tell it is extracting payin terms of understanding the codeit might be better to associate field name with field value we might try to associate names with relative positions by using the python range builtin functionwhich generates successive integers when used in iteration contexts (such as the sequence assignment used initially here)nameagepay range( bob ['bob smith' bob[name'bob smithpaybob[pay( and this addresses readabilitythe three uppercase variables essentially become field names this makes our code dependent on the field position assignmentsthough-we have to remember to update the range assignments whenever we change record structure because they are not directly associatedthe names and records may become out of sync over time and require maintenance step moreoverbecause the field names are independent variablesthere is no direct mapping from record list back to its field' names raw record listfor instanceprovides no way to label its values with field names in formatted display in the preceding recordwithout additional codethere is no path from value to label agebob index( gives the value of agebut not the name age itself we might also try this by using lists of tupleswhere the tuples record both field name and valuebetter yeta list of lists would allow for updates (tuples are immutablehere' what that idea translates towith slightly simpler recordsbob [['name''bob smith']['age' ]['pay' ]sue [['name''sue jones']['age' ]['pay' ]people [bobsuethis really doesn' fix the problemthoughbecause we still have to index by position in order to fetch fieldsfor person in peopleprint(person[ ][ ]person[ ][ ]namepay step representing records |
4,585 | sue jones [person[ ][ for person in people['bob smith''sue jones'for person in peopleprint(person[ ][ split()[- ]person[ ][ * collect names get last names give raise smith jones for person in peopleprint(person[ ]['pay' ['pay' all we've really done here is add an extra level of positional indexing to do betterwe might inspect field names in loops to find the one we want (the loop uses tuple assignment here to unpack the name/value pairs)for person in peoplefor (namevaluein personif name ='name'print(valuefind specific field bob smith sue jones better yetwe can code fetcher function to do the job for usdef field(recordlabel)for (fnamefvaluein recordif fname =labelreturn fvalue find any field by name field(bob'name''bob smithfield(sue'pay' for rec in peopleprint(field(rec'age')print all ages if we proceed down this pathwe'll eventually wind up with set of record interface functions that generically map field names to field data if you've done any python coding in the pastthoughyou probably already know that there is an easier way to code this sort of associationand you can probably guess where we're headed in the next section sneak preview |
4,586 | the list-based record representations in the prior section workthough not without some cost in terms of performance required to search for field names (assuming you need to care about milliseconds and suchbut if you already know some pythonyou also know that there are more efficient and convenient ways to associate property names and values the built-in dictionary object is naturalbob {'name''bob smith''age' 'pay' 'job''dev'sue {'name''sue jones''age' 'pay' 'job''hdw'nowbob and sue are objects that map field names to values automaticallyand they make our code more understandable and meaningful we don' have to remember what numeric offset meansand we let python search for the value associated with field' name with its efficient dictionary indexingbob['name']sue['pay'('bob smith' not bob[ ]sue[ bob['name'split()[- 'smithsue['pay'* sue['pay' because fields are accessed mnemonically nowthey are more meaningful to those who read your code (including youother ways to make dictionaries dictionaries turn out to be so useful in python programming that there are even more convenient ways to code them than the traditional literal syntax shown earlier-- with keyword arguments and the type constructoras long as the keys are all stringsbob dict(name='bob smith'age= pay= job='dev'sue dict(name='sue jones'age= pay= job='hdw'bob {'pay' 'job''dev''age' 'name''bob smith'sue {'pay' 'job''hdw''age' 'name''sue jones'by filling out dictionary one field at time (recall that dictionary keys are pseudorandomly ordered)sue {sue['name''sue jonessue['age' sue['pay' sue['job''hdwsue {'job''hdw''pay' 'age' 'name''sue jones'step representing records |
4,587 | names ['name''age''pay''job'values ['sue jones' 'hdw'list(zip(namesvalues)[('name''sue jones')('age' )('pay' )('job''hdw')sue dict(zip(namesvalues)sue {'job''hdw''pay' 'age' 'name''sue jones'we can even make dictionaries from sequence of key values and an optional starting value for all the keys (handy to initialize an empty dictionary)fields ('name''age''job''pay'record dict fromkeys(fields'?'record {'job''?''pay''?''age''?''name''?'lists of dictionaries regardless of how we code themwe still need to collect our dictionary-based records into databasea list does the trick againas long as we don' require access by key at the top levelbob {'pay' 'job''dev''age' 'name''bob smith'sue {'job''hdw''pay' 'age' 'name''sue jones'people [bobsuefor person in peopleprint(person['name']person['pay']sep=''reference in list all namepay bob smith sue jones for person in peopleif person['name'='sue jones'print(person['pay']fetch sue' pay iteration tools work just as well herebut we use keys rather than obscure positions (in database termsthe list comprehension and map in the following code project the database on the "namefield column)names [person['name'for person in peoplenames ['bob smith''sue jones'collect names list(map((lambda xx['name'])people)['bob smith''sue jones'dittogenerate sum(person['pay'for person in people sum all pay sneak preview |
4,588 | can even approach the utility of sql queries herealbeit operating on in-memory objects[rec['name'for rec in people if rec['age'> ['sue jones'sql-ish query [(rec['age'* if rec['age'> else rec['age']for rec in people[ (rec['name'for rec in people if rec['age'> next( 'sue jonesg ((rec['age'* if rec['age'> else rec['age']for rec in peopleg __next__( and because dictionaries are normal python objectsthese records can also be accessed and updated with normal python syntaxfor person in peopleprint(person['name'split()[- ]person['pay'* last name raise smith jones for person in peopleprint(person['pay'] nested structures incidentallywe could avoid the last-name extraction code in the prior examples by further structuring our records because all of python' compound datatypes can be nested inside each other and as deeply as we likewe can build up fairly complex information structures easily--simply type the object' syntaxand python does all the work of building the componentslinking memory structuresand later reclaiming their space this is one of the great advantages of scripting language such as python the followingfor instancerepresents more structured record by nesting dictionarylistand tuple inside another dictionarybob {'name'{'first''bob''last''smith'}'age' 'job'['software''writing']'pay'( )step representing records |
4,589 | deepbob ['name'{'last''smith''first''bob'bob ['name']['last''smithbob ['pay'][ bob' full name bob' last name bob' upper pay the name field is another dictionary hereso instead of splitting up stringwe simply index to fetch the last name moreoverpeople can have many jobsas well as minimum and maximum pay limits in factpython becomes sort of query language in such cases--we can fetch or change nested data with the usual object operationsfor job in bob ['job']print(jobsoftware writing all of bob' jobs >bob ['job'][- bob' last job 'writingbob ['job'append('janitor'bob gets new job bob {'job'['software''writing''janitor']'pay'( )'age' 'name'{'last''smith''first''bob'}it' ok to grow the nested list with appendbecause it is really an independent object such nesting can come in handy for more sophisticated applicationsto keep ours simplewe'll stick to the original flat record structure dictionaries of dictionaries one last twist on our people databasewe can get little more mileage out of dictionaries here by using one to represent the database itself that iswe can use dictionary of dictionaries--the outer dictionary is the databaseand the nested dictionaries are the records within it rather than simple list of recordsa dictionary-based database allows us to store and retrieve records by symbolic keybob dict(name='bob smith'age= pay= job='dev'sue dict(name='sue jones'age= pay= job='hdw'bob {'pay' 'job''dev''age' 'name''bob smith'db {db['bob'bob db['sue'sue db['bob']['name''bob smithdb['sue']['pay' db['sue']['pay' sneak preview reference in dict of dicts fetch bob' name change sue' pay fetch sue' pay |
4,590 | it in loop--we get to bob' name immediately by indexing on key bob this really is dictionary of dictionariesthough you won' see all the gory details unless you display the database all at once (the python pprint pretty-printer module can help with legibility here)db {'bob'{'pay' 'job''dev''age' 'name''bob smith'}'sue'{'pay' 'job''hdw''age' 'name''sue jones'}import pprint pprint pprint(db{'bob'{'age' 'job''dev''name''bob smith''pay' }'sue'{'age' 'job''hdw''name''sue jones''pay' }if we still need to step through the database one record at timewe can now rely on dictionary iterators in recent python releasesa dictionary iterator produces one key in for loop each time through (for compatibility with earlier releaseswe can also call the db keys method explicitly in the for loop rather than saying just dbbut since python ' keys result is generatorthe effect is roughly the same)for key in dbprint(key'=>'db[key]['name']bob =bob smith sue =sue jones for key in dbprint(key'=>'db[key]['pay']bob = sue = to visit all recordseither index by key as you gofor key in dbprint(db[key]['name'split()[- ]db[key]['pay'* smith jones or step through the dictionary' values to access records directlyfor record in db values()print(record['pay'] [db[key]['name'for key in dbx ['bob smith''sue jones' [rec['name'for rec in db values()step representing records |
4,591 | ['bob smith''sue jones'and to add new recordsimply assign it to new keythis is just dictionaryafter alldb['tom'dict(name='tom'age= job=nonepay= db['tom'{'pay' 'job'none'age' 'name''tom'db['tom']['name''tomlist(db keys()['bob''sue''tom'len(db [rec['age'for rec in db values()[ [rec['name'for rec in db values(if rec['age'> ['sue jones''tom'sql-ish query although our database is still transient object in memoryit turns out that this dictionary-of-dictionaries format corresponds exactly to system that saves objects permanently--the shelve (yesthis should probably be shelfgrammatically speakingbut the python module name and term is shelveto learn howlet' move on to the next section step storing records persistently so farwe've settled on dictionary-based representation for our database of recordsand we've reviewed some python data structure concepts along the way as mentionedthoughthe objects we've seen so far are temporary--they live in memory and they go away as soon as we exit python or the python program that created them to make our people persistentthey need to be stored in file of some sort using formatted files one way to keep our data around between program runs is to write all the data out to simple text filein formatted way provided the saving and loading tools agree on the format selectedwe're free to use any custom scheme we like test data script so that we don' have to keep working interactivelylet' first write script that initializes the data we are going to store (if you've done any python work in the pastyou know that the interactive prompt tends to become tedious once you leave the realm of simple one-linersexample - creates the sort of records and database dictionary we've been working with so farbut because it is modulewe can import it repeatedly without having to retype the code each time in sensethis module is database itselfbut its program code format doesn' support automatic or end-user updates as is sneak preview |
4,592 | initialize data to be stored in filespicklesshelves records bob {'name''bob smith''age' 'pay' 'job''dev'sue {'name''sue jones''age' 'pay' 'job''hdw'tom {'name''tom''age' 'pay' 'job'nonedatabase db {db['bob'bob db['sue'sue db['tom'tom if __name__ ='__main__'when run as script for key in dbprint(key'=>\ 'db[key]as usualthe __name__ test at the bottom of example - is true only when this file is runnot when it is imported when run as top-level script ( from command linevia an icon clickor within the idle gui)the file' self-test code under this test dumps the database' contents to the standard output stream (rememberthat' what print function-call statements do by defaulthere is the script in action being run from system command line on windows type the following command in command prompt window after cd to the directory where the file is storedand use similar console window on other types of computers\pp \previewpython initdata py bob ={'job''dev''pay' 'age' 'name''bob smith'sue ={'job''hdw''pay' 'age' 'name''sue jones'tom ={'job'none'pay' 'age' 'name''tom'file name conventions since this is our first source file ( "script")here are three usage notes for this book' examplesthe text \pp \previewin the first line of the preceding example listing stands for your operating system' promptwhich can vary per platformyou type just the text that follows this prompt (python initdata pylike all examples in this bookthe system prompt also gives the directory in the downloadable book examples package where this command should be run when running this script using command-line in system shellmake sure the shell' current working directory is pp \preview this can matter for examples that use files in the working directory step storing records persistently |
4,593 | the source file resides in the examples package per the example - listing label shown earlierthis script' full filename is pp \preview\initdata py in the examples tree we'll use these conventions throughout the booksee the preface for more on getting the examples if you wish to work along occasionally give more of the directory path in system prompts when it' useful to provide the extra execution contextespecially in the system part of the book ( " :\prefix from windows or more directory namesscript start-up pointers gave pointers for using the interactive prompt earlier now that we've started running script fileshere are also few quick startup pointers for using python scripts in generalon some platformsyou may need to type the full directory path to the python program on your machineif python isn' on your system path setting on windowsfor examplereplace python in the command with :\python \python (this assumes you're using python on most windows systems you also don' need to type python on the command line at alljust type the file' name to run itsince python is registered to open pyscript files you can also run this file inside python' standard idle gui (open the file and use the run menu in the text edit window)and in similar ways from any of the available third-party python ides ( komodoeclipsenetbeansand the wing ideif you click the program' file icon to launch it on windowsbe sure to add an input(call to the bottom of the script to keep the output window up on other systemsicon clicks may require #line at the top and executable permission via chmod command 'll assume here that you're able to run python code one way or another againif you're stucksee other books such as learning python for the full story on launching python programs data format script nowall we have to do is store all of this in-memory data in file there are variety of ways to accomplish thisone of the most basic is to write one piece of data at timewith separators between each that we can use when reloading to break the data apart example - shows one way to code this idea sneak preview |
4,594 | ""save in-memory database object to file with custom formattingassume 'endrec ''enddb 'and '=>are not used in the dataassume db is dict of dictwarningeval can be dangerous it runs strings as codecould also eval(record dict all at oncecould also dbfile write(key '\ 'vs print(keyfile=dbfile)""dbfilename 'people-fileenddb 'enddb endrec 'endrec recsep '=>def storedbase(dbdbfilename=dbfilename)"formatted dump of database to flat filedbfile open(dbfilename' 'for key in dbprint(keyfile=dbfilefor (namevaluein db[keyitems()print(name recsep repr(value)file=dbfileprint(endrecfile=dbfileprint(enddbfile=dbfiledbfile close(def loaddbase(dbfilename=dbfilename)"parse data to reconstruct databasedbfile open(dbfilenameimport sys sys stdin dbfile db {key input(while key !enddbrec {field input(while field !endrecnamevalue field split(recseprec[nameeval(valuefield input(db[keyrec key input(return db if __name__ ='__main__'from initdata import db storedbase(dbthis is somewhat complex programpartly because it has both saving and loading logic and partly because it does its job the hard wayas we'll see in momentthere are better ways to get objects into files than by manually formatting and parsing them for simple tasksthoughthis does workrunning example - as script writes the database out to flat file it has no printed outputbut we can inspect the database file interactively after this script is runeither within idle or from console window where step storing records persistently |
4,595 | directory)\pp \previewpython make_db_file py \pp \previewpython for line in open('people-file')print(lineend=''bob job=>'devpay=> age=> name=>'bob smithendrec sue job=>'hdwpay=> age=> name=>'sue jonesendrec tom job=>none pay=> age=> name=>'tomendrec enddb this file is simply our database' content with added formatting its data originates from the test data initialization module we wrote in example - because that is the module from which example - ' self-test code imports its data in practiceexample - itself could be imported and used to store variety of databases and files notice how data to be written is formatted with the as-code repr call and is re-created with the eval callwhich treats strings as python code that allows us to store and recreate things like the none objectbut it is potentially unsafeyou shouldn' use eval if you can' be sure that the database won' contain malicious code for our purposeshoweverthere' probably no cause for alarm utility scripts to test furtherexample - reloads the database from file each time it is run example - pp \preview\dump_db_file py from make_db_file import loaddbase db loaddbase(for key in dbprint(key'=>\ 'db[key]print(db['sue']['name']and example - makes changes by loadingupdatingand storing again sneak preview |
4,596 | from make_db_file import loaddbasestoredbase db loaddbase(db['sue']['pay'* db['tom']['name''tom tomstoredbase(dbhere are the dump script and the update script in action at system command lineboth sue' pay and tom' name change between script runs the main point to notice is that the data stays around after each script exits--our objects have become persistent simply because they are mapped to and from text files\pp \previewpython dump_db_file py bob ={'pay' 'job''dev''age' 'name''bob smith'sue ={'pay' 'job''hdw''age' 'name''sue jones'tom ={'pay' 'job'none'age' 'name''tom'sue jones \pp \previewpython update_db_file py \pp \previewpython dump_db_file py bob ={'pay' 'job''dev''age' 'name''bob smith'sue ={'pay' 'job''hdw''age' 'name''sue jones'tom ={'pay' 'job'none'age' 'name''tom tom'sue jones as iswe'll have to write python code in scripts or at the interactive command line for each specific database update we need to perform (later in this we'll do better by providing generalized consoleguiand web-based interfaces insteadbut at basic levelour text file is database of records as we'll learn in the next sectionthoughit turns out that we've just done lot of pointless work using pickle files the formatted text file scheme of the prior section worksbut it has some major limitations for one thingit has to read the entire database from the file just to fetch one recordand it must write the entire database back to the file after each set of updates although storing one record' text per file would work around this limitationit would also complicate the program further for another thingthe text file approach assumes that the data separators it writes out to the file will not appear in the data to be storedif the characters =happen to appear in the datafor examplethe scheme will fail we might work around this by generating xml text to represent records in the text fileusing python' xml parsing toolswhich we'll meet later in this textto reloadxml tags would avoid collisions with actual step storing records persistently |
4,597 | too perhaps worst of allthe formatted text file scheme is already complex without being generalit is tied to the dictionary-of-dictionaries structureand it can' handle anything else without being greatly expanded it would be nice if general tool existed that could translate any sort of python data to format that could be saved in file in single step that is exactly what the python pickle module is designed to do the pickle module translates an in-memory python object into serialized byte stream-- string of bytes that can be written to any file-like object the pickle module also knows how to reconstruct the original object in memorygiven the serialized byte streamwe get back the exact same object in sensethe pickle module replaces proprietary data formats --its serialized format is general and efficient enough for any program with picklethere is no need to manually translate objects to data when storing them persistentlyand no need to manually parse complex format to get them back pickling is similar in spirit to xml representationsbut it' both more python-specificand much simpler to code the net effect is that pickling allows us to store and fetch native python objects as they are and in single step--we use normal python syntax to process pickled records despite what it doesthe pickle module is remarkably easy to use example - shows how to store our records in flat fileusing pickle example - pp \preview\make_db_pickle py from initdata import db import pickle dbfile open('people-pickle''wb'pickle dump(dbdbfiledbfile close(use binary mode files in data is bytesnot str when runthis script stores the entire database (the dictionary of dictionaries defined in example - to flat file named people-pickle in the current working directory the pickle module handles the work of converting the object to string example - shows how to access the pickled database after it has been createdwe simply open the file and pass its content back to pickle to remake the object from its serialized string example - pp \preview\dump_db_pickle py import pickle dbfile open('people-pickle''rb'db pickle load(dbfilefor key in dbprint(key'=>\ 'db[key]print(db['sue']['name']use binary mode files in here are these two scripts at workat the system command line againnaturallythey can also be run in idleand you can open and inspect the pickle file by running the same sort of code interactively as well sneak preview |
4,598 | \pp \previewpython dump_db_pickle py bob ={'pay' 'job''dev''age' 'name''bob smith'sue ={'pay' 'job''hdw''age' 'name''sue jones'tom ={'pay' 'job'none'age' 'name''tom'sue jones updating with pickle file is similar to manually formatted fileexcept that python is doing all of the formatting work for us example - shows how example - pp \preview\update-db-pickle py import pickle dbfile open('people-pickle''rb'db pickle load(dbfiledbfile close(db['sue']['pay'* db['tom']['name''tom tomdbfile open('people-pickle''wb'pickle dump(dbdbfiledbfile close(notice how the entire database is written back to the file after the records are changed in memoryjust as for the manually formatted approachthis might become slow for very large databasesbut we'll ignore this for the moment here are our update and dump scripts in action--as in the prior sectionsue' pay and tom' name change between scripts because they are written back to file (this timea pickle file)\pp \previewpython update_db_pickle py \pp \previewpython dump_db_pickle py bob ={'pay' 'job''dev''age' 'name''bob smith'sue ={'pay' 'job''hdw''age' 'name''sue jones'tom ={'pay' 'job'none'age' 'name''tom tom'sue jones as we'll learn in the python pickling system supports nearly arbitrary object types--listsdictionariesclass instancesnested structuresand more therewe'll also learn about the pickler' text and binary storage protocolsas of python all protocols use bytes objects to represent pickled datawhich in turn requires pickle files to be opened in binary mode for all protocols as we'll see later in this the pickler and its data format also underlie shelves and zodb databasesand pickled class instances provide both data and behavior for objects stored in factpickling is more general than these examples may imply because they accept any object that provides an interface compatible with filespickling and unpickling may step storing records persistently |
4,599 | for instanceallows us to ship pickled python objects across network and provides an alternative to larger protocols such as soap and xml-rpc using per-record pickle files as mentioned earlierone potential disadvantage of this section' examples so far is that they may become slow for very large databasesbecause the entire database must be loaded and rewritten to update single recordthis approach can waste time we could improve on this by storing each record in the database in separate flat file the next three examples show one way to do soexample - stores each record in its own flat fileusing each record' original key as its filename with pkl appended (it creates the files bob pklsue pkland tom pkl in the current working directoryexample - pp \preview\make_db_pickle_recs py from initdata import bobsuetom import pickle for (keyrecordin [('bob'bob)('tom'tom)('sue'sue)]recfile open(key pkl''wb'pickle dump(recordrecfilerecfile close(nextexample - dumps the entire database by using the standard library' glob module to do filename expansion and thus collect all the files in this directory with pkl extension to load single recordwe open its file and deserialize with picklewe must load only one record filethoughnot the entire databaseto fetch one record example - pp \preview\dump_db_pickle_recs py import pickleglob for filename in glob glob('pkl')recfile open(filename'rb'record pickle load(recfileprint(filename'=>\ 'recordsuefile open('sue pkl''rb'print(pickle load(suefile)['name']for 'bob','sue','tomfetch sue' name finallyexample - updates the database by fetching record from its filechanging it in memoryand then writing it back to its pickle file this timewe have to fetch and rewrite only single record filenot the full databaseto update example - pp \preview\update_db_pickle_recs py import pickle suefile open('sue pkl''rb'sue pickle load(suefilesuefile close( sneak preview |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.