id
int64
0
25.6k
text
stringlengths
0
4.59k
8,800
which in the case of the item access operator are __getitem__()__setitem__()and __delitem__(the image class uses html-style hexadecimal strings to represent colors the background color must be set when the image is createdotherwiseit defaults to white the image class saves and loads images in its own custom formatbut it can also export in the xpm format which is understood by many image processing applications the xpm image produced by the code snippet is shown in figure figure the square_eye xpm image we will now review the image class' methodsstarting with the class line and the initializerclass imagedef __init__(selfwidthheightfilename=""background="#ffffff")self filename filename self __background background self __data {self __width width self __height height self __colors {self __backgroundwhen an image is createdthe user ( the class' usermust provide width and heightbut the filename and background color are optional since defaults are provided the self __data dictionary' keys are (xycoordinates and its values are color strings the self __colors set is initialized with the background colorit is used to keep track of the unique colors used by the image all the data attributes are private except for the filenameso we must provide means by which users of the class can access them this is easily done using properties @property def background(self)return self __background in we will see completely different approach to providing attribute accessusing special methods such as __getattr__(and __setattr__()that is useful in some circumstances
8,801
object-oriented programming @property def width(self)return self __width @property def height(self)return self __height @property def colors(self)return set(self __colorscopying collections when returning data attribute from an object we need to be aware of whether the attribute is of an immutable or mutable type it is always safe to return immutable attributes since they can' be changedbut for mutable attributes we must consider some trade-offs returning reference to mutable attribute is very fast and efficient because no copying takes place--but it also means that the caller now has access to the object' internal state and might change it in way that invalidates the object one policy to consider is to always return copy of mutable data attributesunless profiling shows significant negative effect on performance (in this casean alternative to keeping the set of unique colors would be to return set(self __data values(){self __backgroundwhenever the set of colors was neededwe will return to this theme shortly def __getitem__(selfcoordinate)assert len(coordinate= "coordinate should be -tupleif (not ( <coordinate[ self widthor not ( <coordinate[ self height))raise coordinateerror(str(coordinate)return self __data get(tuple(coordinate)self __backgroundthis method returns the color for given coordinate using the item access operator ([]the special methods for the item access operators and some other collection-relevant special methods are listed in table we have chosen to apply two policies for item access the first policy is that precondition for using an item access method is that the coordinate it is passed is sequence of length (usually -tuple)and we use an assertion to ensure this the second policy is that any coordinate values are acceptedbut if either is out of rangewe raise custom exception we have used the dict get(method with default value of the background color to retrieve the color for the given coordinate this ensures that if the color has never been set for the coordinate the background color is correctly returned instead of keyerror exception being raised
8,802
table collection special methods special method usage description __contains__(selfxx in returns true if is in sequence or if is key in mapping __delitem__(selfkdel [kdeletes the -th item of sequence or the item with key in mapping __getitem__(selfky[kreturns the -th item of sequence or the value for key in mapping __iter__(selffor in yreturns an iterator for sequence ' pass items or mapping ' keys __len__(selflen(y__reversed__(selfreversed(yreturns backward iterator for sequence ' items or mapping ' keys __setitem__(selfkvy[kv returns the number of items in sets the -th item of sequence or the value for key in mapping yto def __setitem__(selfcoordinatecolor)assert len(coordinate= "coordinate should be -tupleif (not ( <coordinate[ self widthor not ( <coordinate[ self height))raise coordinateerror(str(coordinate)if color =self __backgroundself __data pop(tuple(coordinate)noneelseself __data[tuple(coordinate)color self __colors add(colorif the user sets coordinate' value to the background color we can simply delete the corresponding dictionary item since any coordinate not in the dictionary is assumed to have the background color we must use dict pop(and give dummy second argument rather than use del because doing so avoids keyerror being raised if the key (coordinateis not in the dictionary if the color is different from the background colorwe set it for the given coordinate and add it to the set of the unique colors used by the image def __delitem__(selfcoordinate)assert len(coordinate= "coordinate should be -tupleif (not ( <coordinate[ self widthor not ( <coordinate[ self height))raise coordinateerror(str(coordinate)self __data pop(tuple(coordinate)none
8,803
object-oriented programming if coordinate' color is deleted the effect is to make that coordinate' color the background color again we use dict pop(to remove the item since it will work correctly whether or not an item with the given coordinate is in the dictionary both __setitem__(and __delitem__(have the potential to make the set of colors contain more colors than the image actually uses for exampleif unique nonbackground color is deleted at certain pixelthe color remains in the color set even though it is no longer used similarlyif pixel has unique nonbackground color and is set to the background colorthe unique color is no longer usedbut remains in the color set this means thatat worstthe color set could contain more colors than are actually used by the image (but never lesswe have chosen to accept the trade-off of potentially having more colors in the color set than are actually used for the sake of better performancethat isto make setting and deleting color as fast as possible--especially since storing few more colors isn' usually problem of courseif we wanted to ensure that the set of colors was in sync we could either create an additional method that could be called whenever we wantedor accept the overhead and do the computation automatically when it was needed in either casethe code is very simple (and is used when new image is loaded)self __colors (set(self __data values(){self __background}this simply overwrites the set of colors with the set of colors actually used in the image unioned with the background color we have not provided __len__(implementation since it does not make sense for two-dimensional object alsowe cannot provide representational form since an image cannot be created fully formed just by calling image()so we do not provide __repr__((or __str__()implementations either if user calls repr(or str(on an image objectthe object __repr__(base class implementation will return suitable stringfor example'<image image object at ac>this is standard format used for non-eval()-able objects the hexadecimal number is the object' id--this is unique (normally it is the object' address in memory)but transient we want users of the image class to be able to save and load their image dataso we have provided two methodssave(and load()to carry out these tasks we have chosen to save the data by pickling it in python-speak pickling is way of serializing (converting into sequence of bytesor into stringa python object what is so powerful about pickling is that the pickled object can be collection data typesuch as list or dictionaryand even if the pickled object has other objects inside it (including other collectionswhich
8,804
object-oriented programming we had to open the file in binary mode when reading pickles no protocol is specified--the pickle load(function is smart enough to work out the protocol for itself def load(selffilename=none)if filename is not noneself filename filename if not self filenameraise nofilenameerror(fh none tryfh open(self filename"rb"data pickle load(fh(self __widthself __heightself __backgroundself __datadata self __colors (set(self __data values(){self __background}except (environmenterrorpickle unpicklingerroras errraise loaderror(str(err)finallyif fh is not nonefh close(this function starts off the same as the save(function to get the filename of the file to load the file must be opened in read binary modeand the data is read using the single statementdata pickle load(fhthe data object is an exact reconstruction of the one we savedso in this case it is list with the width and height integersthe background color stringand the dictionary of coordinate-color items we use tuple unpacking to assign each of the data list' items to the appropriate variableso any previously held image data is (correctlylost the set of unique colors is reconstructed by making set of all the colors in the coordinate-color dictionary and then adding the background color def export(selffilename)if filename lower(endswith(xpm")self __export_xpm(filenameelseraise exporterror("unsupported export formatos path splitext(filename)[ ]we have provided one generic export method that uses the file extension to determine which private method to call--or raises an exception for file formats that cannot be exported in this case we only support saving to xpm files (and then only for images with fewer than colorswe haven' quoted the
8,805
__export_xpm(method because it isn' really relevant to this themebut it is in the book' source codeof course we have now completed our coverage of the custom image class this class is typical of those used to hold program-specific dataproviding access to the data items it containsthe ability to save and load all its data to and from diskand with only the essential methods it needs provided in the next two subsections we will see how to create two generic custom collection types that offer complete apis creating collection classes using aggregation |in this subsection we will develop complete custom collection data typesortedlistthat holds list of items in sorted order the items are sorted using their less than operator (<)provided by the __lt__(special methodor by using key function if one is given the class tries to match the api of the builtin list class to make it as easy to learn and use as possiblebut some methods cannot sensibly be provided--for exampleusing the concatenation operator (+could result in items being out of orderso we do not implement it as always when creating custom classeswe are faced with the choices of inheriting class that is similar to the one we want to makeor creating class from scratch and aggregating instances of any other classes we need inside itor doing mixture of both for this subsection' sortedlist we use aggregation (and implicitly inherit objectof course)and for the following subsection' sorteddict we will use both aggregation and inheritance (inheriting dictin we will see that classes can make promises about the api they offer for examplea list provides the mutablesequence api which means that it supports the in operatorthe iter(and len(built-in functionsand the item access operator ([]for gettingsettingand deleting itemsand an insert(method the sortedlist class implemented here does not support item setting and does not have an insert(methodso it does not provide mutablesequence api if we were to create sortedlist by inheriting listthe resultant class would claim to be mutable sequence but would not have the complete api in view of this the sortedlist does not inherit list and so makes no promises about its api on the other handthe next subsection' sorteddict class supports the complete mutablemapping api that the dict class providesso we can make it dict subclass here are some basic examples of using sortedlistletters sortedlist sortedlist((" "" "" "" "" ")str lowerstr(letters="[' '' '' '' '' ']letters add(" "letters add(" "letters add(" "
8,806
object-oriented programming str(letters="[' '' '' '' '' '' '' '' ']letters[ returns'ca sortedlist object aggregates (is composed oftwo private attributesa functionself __key((held as object reference self __key)and listself __list lambda functions the key function is passed as the second argument (or using the key keyword argument if no initial sequence is givenif no key function is specified the following private module function is used_identity lambda xx this is the identity functionit simply returns its argument unchangedso when it is used as sortedlist' key function it means that the sort key for each object in the list is the object itself the sortedlist type does not allow the item access operator ([]to change an item (so it does not implement the __setitem__(special method)nor does it provide the append(or extend(method since these might invalidate the ordering the only way to add items is to pass sequence when the sortedlist is created or to add them later using the sortedlist add(method on the other handwe can safely use the item access operator for getting or deleting the item at given index position since neither operation affects the orderingso both the __getitem__(and __delitem__(special methods are implemented we will now review the class method by methodstarting as usual with the class line and the initializerclass sortedlistdef __init__(selfsequence=nonekey=none)self __key key or _identity assert hasattr(self __key"__call__"if sequence is noneself __list [elif (isinstance(sequencesortedlistand sequence key =self __key)self __list sequence __list[:elseself __list sorted(list(sequence)key=self __keysince function' name is an object reference (to its function)we can hold functions in variables just like any other object reference here the private self __key variable holds reference to the key function that was passed inor to the identity function the method' first statement relies on the fact that the or operator returns its first operand if it is true in boolean context (which not-none key function is)or its second operand otherwise slightly longer but
8,807
more obvious alternative would have been self __key key if key is not none else _identity once we have the key functionwe use an assert to ensure that it is callable the built-in hasattr(function returns true if the object passed as its first argument has the attribute whose name is passed as its second argument there are corresponding setattr(and delattr(functions--these functions are covered in all callable objectsfor examplefunctions and methodshave __call__ attribute to make the creation of sortedlists as similar as possible to the creation of lists we have an optional sequence argument that corresponds to the single optional argument that list(accepts the sortedlist class aggregates list collection in the private variable self __list and keeps the items in the aggregated list in sorted order using the given key function the elif clause uses type testing to see whether the given sequence is sortedlist and if that is the case whether it has the same key function as this sorted list if these conditions are met we simply shallow-copy the sequence' list without needing to sort it if most key functions are created on the fly using lambdaeven though two may have the same code they will not compare as equalso the efficiency gain may not be realized in practice @property def key(self)return self __key once sorted list is created its key function is fixedso we keep it as private variable to prevent users from changing it but some users may want to get reference to the key function (as we will see in the next subsection)and so we have made it accessible by providing the read-only key property def add(selfvalue)index self __bisect_left(valueif index =len(self __list)self __list append(valueelseself __list insert(indexvaluewhen this method is called the given value must be inserted into the private self __list in the correct position to preserve the list' order the private sortedlist __bisect_left(method returns the required index position as we will see in moment if the new value is larger than any other value in the list it must go at the endso the index position will be equal to the list' length (list index positions go from to len( )--if this is the case we append the new value otherwisewe insert the new value at the given index position--which will be at index position if the new value is smaller than any other value in the list
8,808
object-oriented programming def __bisect_left(selfvalue)key self __key(valueleftright len(self __listwhile left rightmiddle (left right/ if self __key(self __list[middle]keyleft middle elseright middle return left this private method calculates the index position where the given value belongs in the listthat isthe index position where the value is (if it is in the list)or where it should go (if it isn' in the listit computes the comparison key for the given value using the sorted list' key functionand compares the comparison key with the computed comparison keys of the items that the method examines the algorithm used is binary search (also called binary chop)which has excellent performance even on very large lists--for exampleat most comparisons are required to find value' position in list of items compare this with plain unsorted list which uses linear search and needs an average of comparisonsand at worst comparisonsto find value in list of items def remove(selfvalue)index self __bisect_left(valueif index len(self __listand self __list[index=valuedel self __list[indexelseraise valueerror("{ remove( ) not in listformatself __class__ __name__)this method is used to remove the first occurrence of the given value it uses the sortedlist __bisect_left(method to find the index position where the value belongs and then tests to see whether that index position is within the list and that the item at that position is the same as the given value if the conditions are met the item is removedotherwisea valueerror exception is raised (which is what list remove(does in the same circumstancesdef remove_every(selfvalue)count index self __bisect_left(valuewhile (index len(self __listand self __list[index=value)python' bisect module provides the bisect bisect_left(function and some othersbut at the time of this writing none of the bisect module' functions can work with key function
8,809
del self __list[indexcount + return count this method is similar to the sortedlist remove(methodand is an extension of the list api it starts off by finding the index position where the first occurrence of the value belongs in the listand then loops as long as the index position is within the list and the item at the index position is the same as the given value the code is slightly subtle since at each iteration the matching item is deletedand as consequenceafter each deletion the item at the index position is the item that followed the deleted item def count(selfvalue)count index self __bisect_left(valuewhile (index len(self __listand self __list[index=value)index + count + return count this method returns the number of times the given value occurs in the list (which could be it uses very similar algorithm to sortedlist remove_ every()only here we must increment the index position in each iteration def index(selfvalue)index self __bisect_left(valueif index len(self __listand self __list[index=valuereturn index raise valueerror("{ index( ) not in listformatself __class__ __name__)since sortedlist is ordered we can use fast binary search to find (or not findthe value in the list def __delitem__(selfindex)del self __list[indexthe __delitem__(special method provides support for the del [nsyntaxwhere is sorted list and is an integer index position we don' test for an out-of-range index since if one is given the self __list[indexcall will raise an indexerror exceptionwhich is the behavior we want def __getitem__(selfindex)return self __list[indexthis method provides support for the [nsyntaxwhere is sorted list and is an integer index position
8,810
object-oriented programming def __setitem__(selfindexvalue)raise typeerror("use add(to insert value and rely on "the list to put it in the right place"we don' want the user to change an item at given index position (so [nx is disallowed)otherwisethe sorted list' order might be invalidated the typeerror exception is the one used to signify that an operation is not supported by particular data type def __iter__(self)return iter(self __listthis method is easy to implement since we can just return an iterator to the private list using the built-in iter(function this method is used to support the for value in iterable syntax note that if sequence is required it is this method that is used so to convert sortedlistlto plain list we can call list( )and behind the scenes python will call sortedlist __iter__(lto provide the sequence that the list(function requires def __reversed__(self)return reversed(self __listthis provides support for the built-in reversed(function so that we can writefor examplefor value in reversed(iterabledef __contains__(selfvalue)index self __bisect_left(valuereturn (index len(self __listand self __list[index=valuethe __contains__(method provides support for the in operator once again we are able to use fast binary search rather than the slow linear search used by plain list def clear(self)self __list [def pop(selfindex=- )return self __list pop(indexdef __len__(self)return len(self __listdef __str__(self)return str(self __list
8,811
the sortedlist clear(method discards the existing list and replaces it with new empty list the sortedlist pop(method removes and returns the item at the given index positionor raises an indexerror exception if the index is out of range for the pop()__len__()and __str__(methodswe simply pass on the work to the aggregated self __list object we do not reimplement the __repr__(special methodso the base class object __repr__(will be called when the user writes repr(land is sortedlist this will produce string such as '<sortedlist sortedlist object at cec>'although the hexadecimal id will varyof course we cannot provide sensible __repr__(implementation because we would need to give the key function and we cannot represent function object reference as an eval()-able string we have not implemented the insert()reverse()or sort(method because none of them is appropriate if any of them are called an attributeerror exception will be raised if we copy sorted list using the [:idiom we will get plain list objectrather than sortedlist the easiest way to get copy is to import the copy module and use the copy copy(function--this is smart enough to copy sorted list (and instances of most other custom classeswithout any help howeverwe have decided to provide an explicit copy(methoddef copy(self)return sortedlist(selfself __keyby passing self as the first argument we ensure that self __list is simply shallow-copied rather than being copied and re-sorted (this is thanks to the __init__(method' type-testing elif clause the theoretical performance advantage of copying this way is not available to the copy copy(functionbut we can easily make it available by adding this line__copy__ copy when copy copy(is called it tries to use the object' __copy__(special methodfalling back to its own code if one isn' provided with this line in place copy copy(will now use the sortedlist copy(method for sorted lists (it is also possible to provide __deepcopy__(special methodbut this is slightly more involved--the copy module' online documentation has the details we have now completed the implementation of the sortedlist class in the next subsection we will make use of sortedlist to provide sorted list of keys for the sorteddict class
8,812
object-oriented programming creating collection classes using inheritance collections ordereddict |the sorteddict class shown in this subsection attempts to mimic dict as closely as possible the major difference is that sorteddict' keys are always ordered based on specified key function or on the identity function sorteddict provides the same api as dict (except for having non-eval()-able repr())plus two extra methods that make sense only for an ordered collection (note that python introduced the collections ordereddict class--this class is different from sorteddict since it is insertion-ordered rather than key-ordered here are few examples of use to give flavor of how sorteddict worksd sorteddict sorteddict(dict( = = = )str lowerd[" " [" " del [" " [" " [" " str(dreturns"{' ' ' ' ' ' ' ' ' ' }the sorteddict implementation uses both aggregation and inheritance the sorted list of keys is aggregated as an instance variablewhereas the sorteddict class itself inherits the dict class we will start our code review by looking at the class line and the initializerand then we will look at all of the other methods in turn class sorteddict(dict)def __init__(selfdictionary=nonekey=none**kwargs)dictionary dictionary or {super(__init__(dictionaryif kwargssuper(update(kwargsself __keys sortedlist sortedlist(super(keys()keythe dict base class is specified in the class line the initializer tries to mimic the dict(functionbut adds second argument for the key function the super(__init__(call is used to initialize the sorteddict using the base class dict __init__(method similarlyif keyword arguments have been usedwe use the base class dict update(method to add them to the dictionary (note that only one occurrence of any keyword argument is acceptedso none of the keys in the kwargs keyword arguments can be "dictionaryor "keythe sorteddict class presented here is different from the one in rapid gui programming with python and qt by this authorisbn and from the one in the python package index
8,813
we keep copy of all the dictionary' keys in sorted list stored in the self __keys variable we pass the dictionary' keys to initialize the sorted list using the base class' dict keys(method--we must not use sorteddict keys(because that relies on the self __keys variable which will exist only after the sortedlist of keys has been created def update(selfdictionary=none**kwargs)if dictionary is nonepass elif isinstance(dictionarydict)super(update(dictionaryelsefor keyvalue in dictionary items()super(__setitem__(keyvalueif kwargssuper(update(kwargsself __keys sortedlist sortedlist(super(keys()self __keys keythis method is used to update one dictionary' items with another dictionary' itemsor with keyword argumentsor both items which exist only in the other dictionary are added to this oneand for items whose keys appear in both dictionariesthe other dictionary' value replaces the original value we have had to extend the behavior slightly in that we keep the original dictionary' key functioneven if the other dictionary is sorteddict the updating is done in two phases first we update the dictionary' items if the given dictionary is dict subclass (which includes sorteddictof course)we use the base class dict update(to perform the update--using the base class version is essential to avoid calling sorteddict update(recursively and going into an infinite loop if the dictionary is not dict we iterate over the dictionary' items and set each key-value pair individually (if the dictionary object is not dict and does not have an items(method an attributeerror exception will quite rightly be raised if keyword arguments have been used we again call the base class update(method to incorporate them consequence of the updating is that the self __keys list becomes out of dateso we replace it with new sortedlist with the dictionary' keys (again obtained from the base classsince the sorteddict keys(method relies on the self __keys list which we are in the process of updating)and with the original sorted list' key function @classmethod def fromkeys(clsiterablevalue=nonekey=none)return cls({kvalue for in iterable}key
8,814
object-oriented programming the dict api includes the dict fromkeys(class method this method is used to create new dictionary based on an iterable each element in the iterable becomes keyand each key' value is either none or the specified value because this is class method the first argument is provided automatically by python and is the class for dict the class will be dictand for sorteddict it is sorteddict the return value is dictionary of the given class for exampleclass mydict(sorteddict sorteddict)pass mydict fromkeys("veins" str(dreturns"{' ' ' ' ' ' ' ' ' ' } __class__ __name__ returns'mydictso when inherited class methods are calledtheir cls variable is set to the correct classjust like when normal methods are called and their self variable is set to the current object this is different from and better than using static method because static method is tied to particular class and does not know whether it is being executed in the context of its original class or that of subclass def __setitem__(selfkeyvalue)if key not in selfself __keys add(keyreturn super(__setitem__(keyvaluethis method implements the [keyvalue syntax if the key isn' in the dictionary we add it to the list of keysrelying on the sortedlist to put it in the right place then we call the base class methodand return its result to the caller to support chainingfor examplex [keyvalue notice that in the if statement we check to see whether the key already exists in the sorteddict by using not in self because sorteddict inherits dicta sorteddict can be used wherever dict is expectedand in this case self is sorteddict when we reimplement dict methods in sorteddictif we need to call the base class implementation to get it to do some of the work for uswe must be careful to call the method using super()as we do in this method' last statementdoing so prevents the reimplementation of the method from calling itself and going into infinite recursion we do not reimplement the __getitem__(method since the base class version works fine and has no effect on the ordering of the keys def __delitem__(selfkey)tryself __keys remove(keyexcept valueerrorraise keyerror(keyreturn super(__delitem__(key
8,815
generator functions generator function or generator method is one which contains yield expression when generator function is called it returns an iterator values are extracted from the iterator one at time by calling its __next__(method at each call to __next__(the generator function' yield expression' value (none if none is specifiedis returned if the generator function finishes or executes return stopiteration exception is raised in practice we rarely call __next__(or catch stopiteration insteadwe just use generator like any other iterable here are two almost equivalent functions the one on the left returns list and the one on the right returns generator build and return list def letter_range(az)result [while ord(aord( )result append(aa chr(ord( return result return each value on demand def letter_range(az)while ord(aord( )yield chr(ord( we can iterate over the result produced by either function using for loopfor examplefor letter in letter_range(" "" ")but if we want list of the resultant lettersalthough calling letter_range(" "" "is sufficient for the left-hand functionfor the right-hand generator function we must use list(letter_range(" "" ")generator functions and methods (and generator expressionsare covered more fully in this method provides the del [keysyntax if the key is not present the sortedlist remove(call will raise valueerror exception if this occurs we catch the exception and raise keyerror exception instead so as to match the dict class' api otherwisewe return the result of calling the base class implementation to delete the item with the given key from the dictionary itself def setdefault(selfkeyvalue=none)if key not in selfself __keys add(keyreturn super(setdefault(keyvaluethis method returns the value for the given key if the key is in the dictionaryotherwiseit creates new item with the given key and value and returns the value for the sorteddict we must make sure that the key is added to the keys list if the key is not already in the dictionary
8,816
object-oriented programming def pop(selfkey*args)if key not in selfif len(args= raise keyerror(keyreturn args[ self __keys remove(keyreturn super(pop(keyargsif the given key is in the dictionary this method returns the corresponding value and removes the key-value item from the dictionary the key must also be removed from the keys list the implementation is quite subtle because the pop(method must support two different behaviors to match dict pop(the first is pop( )here the value for key is returnedor if there is no key ka keyerror is raised the second is pop(kvalue)here the value for key is returnedor if there is no key kvalue (which could be noneis returned in all casesif key existsthe corresponding item is removed def popitem(self)item super(popitem(self __keys remove(item[ ]return item the dict popitem(method removes and returns random key-value item from the dictionary we must call the base class version first since we don' know in advance which item will be removed we remove the item' key from the keys listand then return the item def clear(self)super(clear(self __keys clear(here we clear all the dictionary' items and all the keys list' items def values(self)for key in self __keysyield self[keydef items(self)for key in self __keysyield (keyself[key]def __iter__(self)return iter(self __keyskeys __iter__
8,817
dictionaries have four methods that return iteratorsdict values(for the dictionary' valuesdict items(for the dictionary' key-value itemsdict keys(for the keysand the __iter__(special method that provides support for the iter(dsyntaxand operates on the keys (actuallythe base class versions of these methods return dictionary viewsbut for most purposes the behavior of the iterators implemented here is the same since the __iter__(method and the keys(method have identical behaviorinstead of implementing keys()we simply create an object reference called keys and set it to refer to the __iter__(method with this in placeusers of sorteddict can call keys(or iter(dto get an iterator over dictionary' keysjust the same as they can call values(to get an iterator over the dictionary' values the values(and items(methods are generator methods--see the sidebar "generator functions( for brief explanation of generator methods in both cases they iterate over the sorted keys listso they always return iterators that iterate in key order (with the key order depending on the key function given to the initializerfor the items(and values(methodsthe values are looked up using the [ksyntax (which uses dict __getitem__(under the hood)since we can treat self as dict def __repr__(self)return object __repr__(selfdef __str__(self)return ("{"join(["{ ! }{ ! }format(kvfor kv in self items()]"}"we cannot provide an eval()-able representation of sorteddict because we can' produce an eval()-able representation of the key function so for the __repr__(reimplementation we bypass dict __repr__()and instead call the ultimate base class versionobject __repr__(this produces string of the kind used for non-eval()-able representationsfor example'we have implemented the sorteddict __str__(method ourselves because we want the output to show the items in key sorted order the method could have been written like this insteaditems [for keyvalue in self items()items append("{ ! }{ ! }format(keyvalue)return "{"join(items"}using list comprehension is shorter and avoids the need for the temporary items variable generators
8,818
object-oriented programming the base class methods dict get()dict __getitem__((for the [ksyntax)dict __len__((for len( ))and dict __contains__((for in dall work fine as they are and don' affect the key orderingso we have not needed to reimplement them the last dict method that we must reimplement is copy(def copy(self) sorteddict(super(sorteddictdupdate(selfd __keys self __keys copy(return the easiest reimplementation is simply def copy(self)return sorteddictselfwe've chosen slightly more complicated solution that avoids re-sorting the already sorted keys we create an empty sorted dictionarythen update it with the items in the original sorted dictionary using the base class dict update(to avoid the sorteddict update(reimplementationand replace the dictionary' self __keys sortedlist with shallow copy of the original one when super(is called with no arguments it works on the base class and the self object but we can make it work on any class and any object by passing in class and an object explicitly using this syntaxthe super(call works on the immediate base class of the class it is givenso in this case the code has the same effect as (and could be written asdict update(dselfin view of the fact that python' sort algorithm is very fastand is particularly well optimized for partially sorted liststhe efficiency gain is likely to be little or nothing except for huge dictionaries howeverthe implementation shows that at least in principlea custom copy(method can be more efficient than using the copy_of_x classofx(xidiom that python' built-in types support and just as we did for sortedlistwe have set __copy__ copy so that the copy copy(function uses our custom copy method rather than its own code def value_at(selfindex)return self[self __keys[index]def set_value_at(selfindexvalue)self[self __keys[index]value these two methods represent an extension to the dict api sinceunlike plain dicta sorteddict is orderedit follows that the concept of key index positions is applicable for examplethe first item in the dictionary is at index position and the last at position len( both of these methods operate on the dictionary item whose key is at the index-th position in the sorted keys list thanks to inheritancewe can look up values in the sorteddict using the item access op
8,819
erator ([]applied directly to selfsince self is dict if an out-of-range index is given the methods raise an indexerror exception we have now completed the implementation of the sorteddict class it is not often that we need to create complete generic collection classes like thisbut when we dopython' special methods allow us to fully integrate our class so that its users can treat it like any of the built-in or standard library classes summary ||this covered all the fundamentals of python' support for object-oriented programming we began by showing some of the disadvantages of purely procedural approach and how these could be avoided by using object orientation we then described some of the most common terminology used in objectoriented programmingincluding many "duplicateterms such as base class and super class we saw how to create simple classes with data attributes and custom methods we also saw how to inherit classes and how to add additional data attributes and additional methodsand how methods can be "unimplementedunimplementing is needed when we inherit class but want to restrict the methods that our subclass providesbut it should be used with care since it breaks the expectation that subclass can be used wherever one of its base classes can be usedthat isit breaks polymorphism custom classes can be seamlessly integrated so that they support the same syntaxes as python' built-in and library classes this is achieved by implementing special methods we saw how to implement special methods to support comparisonshow to provide representational and string formsand how to provide conversions to other types such as int and float when it makes sense to do so we also saw how to implement the __hash__(method to make custom class' instances usable as dictionary keys or as members of set data attributes by themselves provide no mechanism for ensuring that they are set to valid values we saw how easy it is to replace data attributes with properties--this allows us to create read-only propertiesand for writable properties makes it easy to provide validation most of the classes we create are "incompletesince we tend to provide only the methods that we actually need this works fine in pythonbut in addition it is possible to create complete custom classes that provide every relevant method we saw how to do this for single valued classesboth by using aggregation and more compactly by using inheritance we also saw how to do this for multivalued (collectionclasses custom collection classes can provide the same facilities as the built-in collection classesincluding support for inlen()iter()reversed()and the item access operator ([]
8,820
object-oriented programming we learned that object creation and initialization are separate operations and that python allows us to control bothalthough in almost every case we only need to customize initialization we also learned that although it is always safe to return an object' immutable data attributeswe should normally only ever return copies of an object' mutable data attributes to avoid the object' internal state leaking out and being accidentally invalidated python provides normal methodsstatic methodsclass methodsand module functions we saw that most methods are normal methodswith class methods being occasionally useful static methods are rarely usedsince class methods or module functions are almost always better alternatives the built-in repr(method calls an object' __repr__(special method where possibleeval(repr( )=xand we saw how to support this when an eval()-able representation string cannot be produced we use the base class object __repr__(method to produce non-eval()-able representation in standard format type testing using the built-in isinstance(function can provide some efficiency benefitsalthough object-oriented purists would almost certainly avoid its use accessing base class methods is achieved by calling the built-in super(functionand is essential to avoid infinite recursion when we need to call base class method inside subclass' reimplementation of that method generator functions and methods do lazy evaluationreturning (via the yield expressioneach value one at time on request and raising stopiteration when (and ifthey run out of values generators can be used wherever an iterator is expectedand for finite generatorsall their values can be extracted into tuple or list by passing the iterator returned by the generator to tuple(or list(the object-oriented approach almost invariably simplifies code compared with purely procedural approach with custom classes we can guarantee that only valid operations are available (since we implement only appropriate methods)and that no operation can put an object into an invalid state ( by using properties to apply validationonce we start using object orientation our style of programming is likely to change from being about global data structures and the global functions that are applied to the datato creating classes and implementing the methods that are applicable to them object orientation makes it possible to package up data and those methods that make sense for the data this helps us avoid mixing up all our data and functions togetherand makes it easier to produce maintainable programs since functionality is kept separated out into individual classes
8,821
exercises ||the first two exercises involve modifying classes we covered in this and the last two exercises involve creating new classes from scratch modify the point class (from shape py or shapealt py)to support the following operationswhere pqand are points and is numberp + - * / / // point __add__(point __iadd__(point __sub__(point __isub__(point __mul__(point __imul__(point __truediv__(point __itruediv__(point __floordiv__(point __ifloordiv__(the in-place methods are all four lines longincluding the def lineand the other methods are each just two lines longincluding the def lineand of course they are all very similar and quite simple with minimal description and doctest for each it adds up to around one hundred thirty new lines model solution is provided in shape_ans pythe same code is also in shapealt_ans py modify the image py class to provide resize(widthheightmethod if the new width or height is smaller than the current valueany colors outside the new boundaries must be deleted if either width or height is none then use the existing width or height at the endmake sure you regenerate the self __colors set return boolean to indicate whether change was made or not the method can be implemented in fewer than lines (fewer than including docstring with simple doctesta solution is provided in image_ans py implement transaction class that takes an amounta datea currency (default "usd"-- dollars) usd conversion rate (default )and description (default noneall of the data attributes must be private provide the following read-only propertiesamountdatecurrencyusd_conversion_ratedescriptionand usd (calculated from amount usd_conversion_ratethis class can be implemented in about sixty lines including some simple doctests model solution for this exercise (and the next oneis in file account py implement an account class that holds an account numberan account nameand list of transactions the number should be read-only prop
8,822
object-oriented programming ertythe name should be read-write property with an assertion to ensure that the name is at least four characters long the class should support the built-in len(function (returning the number of transactions)and should provide two calculated read-only propertiesbalance which should return the account' balance in usd and all_usd which should return true if all the transactions are in usd and false otherwise three other methods should be providedapply(to apply (adda transactionsave()and load(the save(and load(methods should use binary pickle with the filename being the account number with extension accthey should save and load the account numberthe nameand all the transactions this class can be implemented in about ninety lines with some simple doctests that include saving and loading--use code such as name os path join(tempfile gettempdir()account_nameto provide suitable temporary filenameand make sure you delete the temporary file after the tests have finished model solution is in file account py
8,823
writing and reading binary data writing and parsing text files writing and parsing xml files random access binary files |||file handling most programs need to save and load informationsuch as data or state informationto and from files python provides many different ways of doing this we already briefly discussed handling text files in and pickles in the preceding in this we will cover file handling in much more depth all the techniques presented in this are platform-independent this means that file saved using one of the example programs on one operating system/processor architecture combination can be loaded by the same program on machine with different operating system/processor architecture combination and this can be true of your programs too if you use the same techniques as the example programs the first three sections cover the common case of saving and loading an entire data collection to and from disk the first section shows how to do this using binary file formatswith one subsection using (optionally compressedpicklesand the other subsection showing how to do the work manually the second section shows how to handle text files writing text is easybut reading it back can be tricky if we need to handle nontextual data such as numbers and dates we show two approaches to parsing textdoing it manually and using regular expressions the third section shows how to read and write xml files this section covers writing and parsing using element treeswriting and parsing using the dom (document object model)and writing manually and parsing using sax (simple api for xmlthe fourth section shows how to handle random access binary files this is useful when each data item is the same size and where we have more items than we want in (or can fit intomemory which is the best file format to use for holding entire collections--binarytextor xmlwhich is the best way to handle each formatthese questions are too context-dependent to have single definitive answerespecially since there are
8,824
file handling name data type notes minimum length and no whitespace report_id str date datetime date airport str nonempty and no newlines aircraft_id str nonempty and no newlines aircraft_type str nonempty and no newlines pilot_percent_hours_on_type float range to pilot_total_hours int positive and nonzero midair bool narrative str multiline figure aircraft incident record pros and cons for each format and for each way of handling them we show all of them to help you make an informed decision on case-by-case basis binary formats are usually very fast to save and load and they can be very compact binary data doesn' need parsing since each data type is stored using its natural representation binary data is not human readable or editableand without knowing the format in detail it is not possible to create separate tools to work with binary data text formats are human readable and editableand this can make text files easier to process with separate tools or to change using text editor text formats can be tricky to parse and it is not always easy to give good error messages if text file' format is broken ( by careless editingxml formats are human readable and editablealthough they tend to be verbose and create large files like text formatsxml formats can be processed using separate tools parsing xml is straightforward (providing we use an xml parser rather than do it manually)and some parsers have good error reporting xml parsers can be slowso reading very large xml files can take lot more time than reading an equivalent binary or text file xml includes metadata such as the character encoding (either implicitly or explicitlythat is not often provided in text filesand this can make xml more portable than text files text formats are usually the most convenient for end-usersbut sometimes performance issues are such that binary format is the only reasonable choice howeverit is always useful to provide import/export for xml since this makes it possible to process the file format with third-party tools without preventing the most optimal text or binary format being used by the program for normal processing
8,825
format reader/writer reader writer lines of code total lines of code output file size (~kbbinary pickle (gzip compressed binary pickle binary manual (gzip compressed binary manual plain text regex reader/manual writer plain text manual xml element tree xml dom xml sax reader/manual writer figure aircraft incident file format reader/writer comparison this first three sections all use the same data collectiona set of aircraft incident records figure shows the namesdata typesand validation constraints that apply to aircraft incident records it doesn' really matter what data we are processing the important thing is that we learn to process the fundamental data types including stringsintegersfloating-point numbersbooleansand datessince if we can handle these we can handle any other kind of data by using the same set of aircraft incident data for binarytextand xml formatsit makes it possible to compare and contrast the different formats and the code necessary for handling them figure shows the number of lines of code for reading and writing each formatand the totals the file sizes are approximate and based on particular sample of aircraft incident records compressed binary file sizes for the same data saved under different filenames may vary by few bytes since the filename is included in the compressed data and filename lengths vary similarlythe xml file sizes vary slightly since some xml writers use entities (&quotfor and &aposfor 'for quotes inside text dataand others don' the first three sections all quote code from the same programconvert-incidents py this program is used to read aircraft incident data in one format and to write it in another format here is the program' console help text (we have reformatted the output slightly to fit the book' page width usageconvert-incidents py [optionsinfile outfile the data we used is based on real aircraft incident data available from the faa ( government' federal aviation administrationwww faa gov
8,826
file handling reads aircraft incident data from infile and writes the data to outfile the data formats used depend on the file extensionsaix is xmlait is text (utf- encoding)aib is binaryaip is pickleand html is html (only allowed for the outfileall formats are platform-independent options- --help show this help message and exit - --force write the outfile even if it exists [defaultoff- --verbose report results [defaultoff- reader--reader=reader reader (xml)'dom'' ''etree'' ''sax''sreader (text)'manual'' ''regex'' [defaultetree for xmlmanual for text- writer--writer=writer writer (xml)'dom'' ''etree'' ''manual'' [defaultmanual- --compress compress aibaip outfile [defaultoff- --test execute doctests and exit (use with - for verbosethe options are more complex than would normally be required since an end-user will not care which reader or writer we use for any particular format in more realistic version of the program the reader and writer options would not exist and we would implement just one reader and one writer for each format similarlythe test option exists to help us test the code and would not be present in production version the program defines one custom exceptionclass incidenterror(exception)pass aircraft incidents are held as incident objects here is the class line and the initializerclass incidentdef __init__(selfreport_iddateairportaircraft_idaircraft_typepilot_percent_hours_on_typepilot_total_hoursmidairnarrative="")assert len(report_id> and len(report_id split()= "invalid report idself __report_id report_id self date date self airport airport self aircraft_id aircraft_id self aircraft_type aircraft_type self pilot_percent_hours_on_type pilot_percent_hours_on_type
8,827
self pilot_total_hours pilot_total_hours self midair midair self narrative narrative the report id is validated when the incident is created and is available as the read-only report_id property all the other data attributes are read/write properties for examplehere is the date property' code@property def date(self)return self __date @date setter def date(selfdate)assert isinstance(datedatetime date)"invalid dateself __date date all the other properties follow the same patterndiffering only in the details of their assertionsso we won' reproduce them here since we have used assertionsthe program will fail if an attempt is made to create an incident with invalid dataor to set one of an existing incident' read/write properties to an invalid value we have chosen this uncompromising approach because we want to be sure that the data we save and load is always validand if it isn' we want the program to terminate and complain rather than silently continue the collection of incidents is held as an incidentcollection this class is dict subclassso we get lot of functionalitysuch as support for the item access operator ([]to getsetand delete incidentsby inheritance here is the class line and few of the class' methodsclass incidentcollection(dict)def values(self)for report_id in self keys()yield self[report_iddef items(self)for report_id in self keys()yield (report_idself[report_id]def __iter__(self)for report_id in sorted(super(keys())yield report_id keys __iter__ we have not needed to reimplement the initializer since dict __init__(is sufficient the keys are report ids and the values are incidents we have reimplemented the values()items()and keys(methods so that their iterators
8,828
the bytes and bytearray data types python provides two data types for handling raw bytesbytes which is immutableand bytearray which is mutable both types hold sequence of zero or more -bit unsigned integers (byteswith each byte in the range str translate( both types are very similar to strings and provide many of the same methodsincluding support for slicing in additionbytearrays also provide some mutating list-like methods all their methods are listed in tables and whereas slice of bytes or bytearray returns an object of the same typeaccessing single byte using the item access operator ([]returns an int--the value of the specified byte for exampleword "animalx "aword[ = returnsfalse word[: = returnstrue word[ = [ returnstrue word[ = = "aword[: = " " = "aword[ = [ = here are some other bytes and bytearray examplesdata " hills \ \ \ \ \ \ \ data upper(returnsb' hills hillsdata replace( "ill" "at"returnsb' hats hatsbytes fromhex(" "returnsb' hillsbytes fromhex(" "returnsb' hillsdata bytearray(datadata is now bytearray data pop( returns (ord(" ")data insert( ord(" ")data = ' hills billsmethods that make sense only for stringssuch as bytes upper()assume that the bytes are encoded using ascii the bytes fromhex(class method ignores whitespace and interprets each two-digit substring as hexadecimal numberso " is taken to be byte of value and so on pickle dump(selffhpickle highest_protocolreturn true except (environmenterrorpickle picklingerroras errprint("{ }export error{ }formatos path basename(sys argv[ ])err)return false finallyif fh is not nonefh close(
8,829
file handling if compression has been requestedwe use the gzip module' gzip open(function to open the fileotherwisewe use the built-in open(function we must use "write binarymode ("wb"when pickling data in binary format in python and pickle highest_protocol is protocol compact binary pickle format this is the best protocol to use for data shared among python programs for error handling we have chosen to report errors to the user as soon as they occurand to return boolean to the caller indicating success or failure and we have used finally block to ensure that the file is closed at the endwhether there was an error or not in we will use more compact idiom to ensure that files are closed that avoids the need for finally block context managers this code is very similar to what we saw in the preceding but there is one subtle point to note the pickled data is selfa dict but the dictionary' values are incident objectsthat isobjects of custom class the pickle module is smart enough to be able to save objects of most custom classes without us needing to intervene in generalbooleansnumbersand strings can be pickledas can instances of classes including custom classesproviding their private __dict__ is picklable in additionany built-in collection types (tupleslistssetsdictionariescan be pickledproviding they contain only picklable objects (including collection typesso recursive structures are supportedit is also possible to pickle other kinds of objects or instances of custom classes that can' normally be pickled ( because they have nonpicklable attribute)either by giving some help to the pickle module or by implementing custom pickle and unpickle functions all the relevant details are provided in the pickle module' online documentation __dict__ to read back the pickled data we need to distinguish between compressed and an uncompressed pickle any file that is compressed using gzip compression begins with particular magic number magic number is sequence of one or more bytes at the beginning of file that is used to indicate the file' type for gzip files the magic number is the two bytes bwhich we store in bytes variablegzip_magic "\ \ bfor more about the bytes data typesee the sidebar "the bytes and bytearray data types( )and tables and - )which list their methods here is the code for reading an incidents pickle fileprotocol is python -specific if we want pickles that are readable and writable by both python and python programswe must use protocol instead notethoughthat protocol files written by python can be read by python and python xbut not by python
8,830
def import_pickle(selffilename)fh none tryfh open(filename"rb"magic fh read(len(gzip_magic)if magic =gzip_magicfh close(fh gzip open(filename"rb"elsefh seek( self clear(self update(pickle load(fh)return true except (environmenterrorpickle unpicklingerroras errprint("{ }import error{ }formatos path basename(sys argv[ ])err)return false finallyif fh is not nonefh close(we don' know whether the given file is compressed in either case we begin by opening the file in "read binarymodeand then we read the first two bytes if these bytes are the same as the gzip magic number we close the file and create new file object using the gzip open(function and if the file is not compressed we use the file object returned by open()calling its seek(method to restore the file pointer to the beginning so that the next read (made inside the pickle load(functionwill be from the start we can' assign to self since that would wipe out the incidentcollection object that is in useso instead we clear all the incidents to make the dictionary empty and then use dict update(to populate the dictionary with all the incidents from the incidentcollection dictionary loaded from the pickle note that it does not matter whether the processor' byte ordering is bigor little-endianbecause for the magic number we read individual bytesand for the data the pickle module handles endianness for us raw binary data with optional compression |writing our own code to handle raw binary data gives us complete control over our file format it should also be safer than using picklessince maliciously invalid data will be handled by our code rather than executed by the interpreter
8,831
file handling when creating custom binary file formats it is wise to create magic number to identify your file typeand version number to identify the version of the file format in use here are the definitions used in the convert-incidents py programmagic "aib\ format_version "\ \ we have used four bytes for the magic number and two for the version endianness is not an issue because these will be written as individual bytesnot as the byte representations of integersso they will always be the same on any processor architecture to write and read raw binary data we must have some means of converting python objects to and from suitable binary representations most of the functionality we need is provided by the struct modulebriefly described in the sidebar "the struct module )and by the bytes and bytearray data typesbriefly described in the sidebar "the bytes and bytearray data types( the bytes and bytearray classesmethods are listed in tables and unfortunatelythe struct module can handle strings only of specified lengthand we need variable length strings for the report and aircraft idsas well as for the airportthe aircraft typeand the narrative texts to meet this need we have created functionpack_string()which takes string and returns bytes object which contains two componentsthe first is an integer length countand the second is sequence of length count utf- encoded bytes representing the string' text since the only place the pack_string(function is needed is inside the export_binary(functionwe have put the definition of pack_string(inside the export_binary(function this means that pack_string(is not visible outside the export_binary(functionand makes clear that it is just local helper function here is the start of the export_binary(functionand the complete nested pack_string(functiondef export_binary(selffilenamecompress=false)def pack_string(string)data string encode("utf "format "< { }sformat(len(data)return struct pack(formatlen(data)datacharacter encodings the str encode(method returns bytes object with the string encoded according to the specified encoding utf- is very convenient encoding because it can represent any unicode character and is especially compact when representing ascii characters (just one byte eachthe format variable is set to hold struct format based on the string' length for examplegiven the string local functions
8,832
the struct module the struct module provides struct pack()struct unpack()and some other functionsand the struct struct(class the struct pack(function takes struct format string and one or more values and returns bytes object that holds all the values represented in accordance with the format the struct unpack(function takes format and bytes or bytearray object and returns tuple of the values that were originally packed using the format for exampledata struct pack("< " - items struct unpack("< "datadata = '\ \ \xf \xffitems =( - format strings consist of one or more characters most characters represent value of particular type if we need more than one value of type we can either write the character as many times as there are values of the type ("hh")or precede the character with count as we have done here (" "many format characters are described in the struct module' online documentationincluding " ( -bit signed integer)" ( -bit unsigned integer)" ( -bit signed integer--used in the examples here)" ( -bit unsigned integer)" ( -bit signed integer)" ( -bit unsigned integer)" ( -bit signed integer)" ( -bit unsigned integer)" ( -bit float)" ( -bit float--this corresponds to python' float type)"?(boolean)" (bytes or bytearray object--byte strings)and many others for some data types such as multibyte integersthe processor' endianness makes difference to the byte order we can force particular byte order to be used regardless of the processor architecture by starting the format string with an endianness character in this book we always use "<"which means little-endian since that' the native endianness for the widely used intel and amd processors big-endian (also called network byte orderis signified by ">(or by "!"if no endianness is specified the machine' endianness is used we recommend always specifying the endianness even if it is the same as the machine being used since doing so keeps the data portable the struct calcsize(function takes format and returns how many bytes struct using the format will occupy format can also be stored by creating struct struct(object giving it the format as its argumentwith the size of the struct struct(object given by its size attribute for exampletwo_shorts struct struct("< "data two_shorts pack( - items two_shorts unpack(datadata = '\ \ \xf \xffitems =( - in both examples is bbut this is transformed into the bytes because we have used little-endian byte ordering
8,833
file handling "en wikipedia org"the format will be "< (little-endian byte order -byte unsigned integer -byte byte string)and the bytes object that is returned will be '\ \ en wikipedia orgconvenientlypython shows bytes objects in compact form using printable ascii characters where possibleand hexadecimal escapes (and some special escapes like \ and \notherwise the pack_string(function can handle strings of up to utf- characters we could easily switch to using different kind of integer for the byte countfor examplea -byte signed integer (format " "would allow for strings of up to - (more than billioncharacters the struct module does provide similar built-in format" "that stores single byte as character count followed by up to characters for packingthe code using "pformat is slightly simpler than doing all the work ourselves but "pformat restricts us to maximum of utf- characters and provides almost no benefit when unpacking (for the sake of comparisonversions of pack_string(and unpack_string(that use "pformat are included in the convert-incidents py source file we can now turn our attention to the rest of the code in the export_binary(method fh none tryif compressfh gzip open(filename"wb"elsefh open(filename"wb"fh write(magicfh write(format_versionfor incident in self values()data bytearray(data extend(pack_string(incident report_id)data extend(pack_string(incident airport)data extend(pack_string(incident aircraft_id)data extend(pack_string(incident aircraft_type)data extend(pack_string(incident narrative strip())data extend(numbersstruct packincident date toordinal()incident pilot_percent_hours_on_typeincident pilot_total_hoursincident midair)fh write(datareturn true
8,834
table bytes and bytearray methods # syntax description ba append(iappends int (in range to bytearray ba capitalize(returns copy of bytes/bytearray with the first character capitalized (if it is an ascii letterb center(widthbytereturns copy of centered in length width padded with spaces or optionally with the given byte count(xstartendreturns the number of occurrences of bytes/bytearray in bytesbytearray (or in the start:end slice of bcharacter encodings decodeencodingerrorreturns str object that represents the bytes using the utf- encoding or using the specified encoding and handling errors according to the optional error argument endswith(xstartendreturns true if (or the start:end slice of bends with bytesbytearray or with any of the bytes/bytearrays in tuple xotherwisereturns false expandtabssizereturns copy of bytes/bytearray with tabs replaced with spaces in multiples of or of size if specified ba extend(seqextends bytearray ba with all the ints in sequence seqall the ints must be in the range find(xstartendreturns the leftmost position of bytes/bytearray in (or in the start:end slice of bor - if not found use the rfind(method to find the rightmost position fromhex(hreturns bytes object with bytes corresponding to the hexadecimal integers in str index(xstartendreturns the leftmost position of in (or in the start:end slice of bor raises valueerror if not found use the rindex(method to find the rightmost position ba insert(piinserts integer (in range at position in ba isalnum(returns true if bytes/bytearray is nonempty and every character in is an ascii alphanumeric character isalpha(returns true if bytes/bytearray is nonempty and every character in is an ascii alphabetic character isdigit(returns true if bytes/bytearray is nonempty and every character in is an ascii digit islower(returns true if bytes/bytearray has at least one lowercaseable ascii character and all its lowercaseable characters are lowercase returns true if bytes/bytearray is nonempty and every character in is an ascii whitespace character isspace(
8,835
file handling table bytes and bytearray methods # syntax description istitle(returns true if is nonempty and title-cased isupper(returns true if has at least one uppercaseable ascii character and all its uppercaseable characters are uppercase join(seqreturns the concatenation of every bytes/bytearray in sequence seqwith (which may be emptybetween each one ljustwidthbytereturns copy of bytes/bytearray left-aligned in length width padded with spaces or optionally with the given byte use the rjust(method to right-align lower(returns an ascii-lowercased copy of bytes/bytearray partitionsepreturns tuple of three bytes objects--the part of before the leftmost bytes/bytearray sepsep itselfand the part of after sepor if sep isn' in returns and two empty bytes objects use the rpartition(method to partition on the rightmost occurrence of sep ba pop(premoves and returns the int at index position in ba ba remove(iremoves the first occurrence of int from bytearray ba replace(xynreturns copy of with every (or maximum of if givenoccurrence of bytes/bytearray replaced with ba reverse(reverses bytearray ba' bytes in-place split(xnreturns list of bytes splitting at most times on if isn' givensplits everywhere possibleif isn' givensplits on whitespace use rsplit(to split from the right splitlinesfreturns the list of lines produced by splitting on line terminatorsstripping the terminators unless is true startswithxstartendreturns true if bytes/bytearray (or the start:end slice of bstarts with bytes/bytearray or with any of the bytesbytearrays in tuple xotherwisereturns false strip(xreturns copy of with leading and trailing whitespace (or the bytes in bytes/bytearray xremovedlstrip(strips only at the startand rstrip(strips only at the end swapcase(returns copy of with uppercase ascii characters lowercased and lowercase ascii characters uppercased title(returns copy of where the first ascii letter of each word is uppercased and all other ascii letters are lowercased translatebtdreturns copy of that has no bytes from dand where each other byte is replaced by the byte-th byte from bytes bt
8,836
table bytes and bytearray methods # syntax description upper(returns an ascii-uppercased copy of bytes/bytearray zfill(wreturns copy of bwhich if shorter than is padded with leading zeros ( charactersto make it bytes long we have omitted the except and finally blocks since they are the same as the ones shown in the preceding subsectionapart from the particular exceptions that the except block catches we begin by opening the file in "write binarymodeeither normal file or gzip compressed file depending on the compress flag we then write the -byte magic number that is (hopefullyunique to our programand the -byte version number using version number makes it easier to change the format in the future--when we read the version number we can use it to determine which code to use for reading next we iterate over all the incidentsand for each one we create bytearray we add each item of data to the byte arraystarting with the variable length strings the date toordinal(method returns single integer representing the stored datethe date can be restored by passing this integer to the datetime date fromordinal(method the numbersstruct is defined earlier in the program with this statementnumbersstruct struct struct("<idi?"this format specifies little-endian byte orderan unsigned -bit integer (for the date ordinal) -bit float (for the percentage hours on type) -bit integer (for the total hours flown)and boolean (for whether the incident was midairthe structure of an entire aircraft incident record is shown schematically in figure once the bytearray has all the data for one incidentwe write it to disk and once all the incidents have been written we return true (assuming no error occurredthe finally block ensures that the file is closed just before we return reading back the data is not as straightforward as writing it--for one thing we have more error checking to do alsoreading back variable length strings is slightly tricky here is the start of the import_binary(method and the complete nested unpack_string(function that we use to read back the variable length stringsthere is no central repository for magic numbers like there is for domain namesso we can never guarantee uniqueness
8,837
nar dat pil hou t_pe rs_ rce on_ nt_ typ pil hou t_to tal rs mid string string string string uint float int bool ive typ rat ft_ cra por uint air air cra ft_ id string air file handling rep ort _id utf- encoded bytes figure the structure of binary aircraft incident record def import_binary(selffilename)def unpack_string(fheof_is_error=true)uint struct struct("< "length_data fh read(uint sizeif not length_dataif eof_is_errorraise valueerror("missing or corrupt string size"return none length uint unpack(length_data)[ if length = return "data fh read(lengthif not data or len(data!lengthraise valueerror("missing or corrupt string"format "<{ }sformat(lengthreturn struct unpack(formatdata)[ decode("utf "since each incident record begins with its report id stringwhen we attempt to read this string and we succeedwe are at the start of new record but if we failwe've reached the end of the file and can finish we set the eof_is_error flag to false when attempting to read report id since if there is no datait just means we have finished for all other strings we accept the default of true because if any other string has no datait is an error (even an empty string will be preceded by -bit unsigned integer length we begin by attempting to read the string' length if this fails we return none to signify end of file (if we are attempting to read new incident)or we raise valueerror exception to indicate corrupt or missing data the struct unpack(function and the struct struct unpack(method always return tupleeven if it contains only single value we unpack the length data and store the number it represents in the length variable now we know how many bytes we
8,838
must read to get the string if the length is zero we simply return an empty string otherwisewe attempt to read the specified number of bytes if we don' get any data or if the data is not the size we expected ( it is too little)we raise valueerror exception if we have the right number of bytes we create suitable format string for the struct unpack(functionand we return the string that results from unpacking the data and decoding the bytes as utf- (in theorywe could replace the last two lines with return data decode("utf ")but we prefer to go through the unpacking process since it is possible--though unlikely--that the "sformat performs some transformation on our data which must be reversed when reading back we will now look at the rest of the import_binary(methodbreaking it into two parts for ease of explanation fh none tryfh open(filename"rb"magic fh read(len(gzip_magic)if magic =gzip_magicfh close(fh gzip open(filename"rb"elsefh seek( magic fh read(len(magic)if magic !magicraise valueerror("invalid aib file format"version fh read(len(format_version)if version format_versionraise valueerror("unrecognized aib file version"self clear(the file may or may not be compressedso we use the same technique that we used for reading pickles to open the file using gzip open(or the built-in open(function once the file is open and we are at the beginningwe read the first four bytes (len(magic)if these don' match our magic number we know that it isn' binary aircraft incident data file and so we raise valueerror exception next we read in the -byte version number it is at this point that we would use different reading code depending on the version here we just check that the version isn' later one than this program is able to read if the magic number is correct and the version is one we can handlewe are ready to read in the dataso we begin by clearing out all the existing incidents so that the dictionary is empty
8,839
file handling while truereport_id unpack_string(fhfalseif report_id is nonebreak data {data["report_id"report_id for name in ("airport""aircraft_id""aircraft_type""narrative")data[nameunpack_string(fhother_data fh read(numbersstruct sizenumbers numbersstruct unpack(other_datadata["date"datetime date fromordinal(numbers[ ]data["pilot_percent_hours_on_type"numbers[ data["pilot_total_hours"numbers[ data["midair"numbers[ incident incident(**dataself[incident report_idincident return true the while block loops until we run out of data we start by trying to get report id if we get none we've reached the end of the file and can break out of the loop otherwisewe create dictionary called data to hold the data for one incident and attempt to get the rest of the incident' data for the strings we use the unpack_string(methodand for the other data we read it all in one go using the numbersstruct struct since we stored the date as an ordinal we must do the reverse conversion to get date back but for the other itemswe can just use the unpacked data--no validation or conversion is required since we wrote the correct data types in the first place and have read back the same data types using the format held in the numbersstruct struct if any error occursfor exampleif we fail to unpack all the numbersan exception will be raised and will be handled in the except block (we haven' shown the except and finally blocks because they are structurally the same as those shown in the preceding subsection for the import_pickle(method mapping unpacking toward the end we make use of the convenient mapping unpacking syntax to create an incident object which we then store in the incidents dictionary apart from the handling of variable length stringsthe struct module makes it very easy to save and load data in binary format and for variable length strings the pack_string(and unpack_string(methods shown here should serve most purposes perfectly well
8,840
writing and parsing text files ||writing text is easybut reading it back can be problematicso we need to choose the structure carefully so that it is not too difficult to parse figure shows an example aircraft incident record in the text format we are going to use when we write the incident records to file we will follow each one with blank linebut when we parse the file we will accept zero or more blank lines between incident records writing text |each incident record begins with the report id enclosed in brackets ([]this is followed by all the one-line data items written in key=value form for the multiline narrative text we precede the text with start marker narrative_start and follow it with an end marker narrative_end )and we indent all the text in between to ensure that no line of text could be confused with start or end marker [ cdateaircraft_id= aircraft_type=dhc- -mk airport=merle (mudholesmith pilot_percent_hours_on_type= pilot_total_hours= midair= narrative_start according to the pilotthe drag link failed due to an oversized tail wheel tire landing on hard surface narrative_end figure an example text format aircraft incident record here is the code for the export_text(functionbut excluding the except and finally blocks since they are the same as ones we have seen beforeexcept for the exceptions handleddef export_text(selffilename)wrapper textwrap textwrapper(initial_indent="subsequent_indent=" introduces various parsing techniquesincluding two third-party open source parsing modules that make parsing tasks much easier
8,841
file handling fh none tryfh open(filename" "encoding="utf "for incident in self values()narrative "\njoin(wrapper wrapincident narrative strip())fh write("[{ report_id}]\ "date={ date! }\ "aircraft_id={ aircraft_id}\ "aircraft_type={ aircraft_type}\ "airport={airport}\ "pilot_percent_hours_on_type="{ pilot_percent_hours_on_type}\ "pilot_total_hours={ pilot_total_hours}\ "midair={ midair: }\nnarrative_start \ {narrative}\nnarrative_end \ \nformat(incidentairport=incident airport strip()narrative=narrative)return true the line breaks in the narrative text are not significantso we can wrap the text as we like normally we would use the textwrap module' textwrap wrap(functionbut here we need to both indent and wrapso we begin by creating textwrap textwrap objectinitialized with the indentation we want to use (four spaces for the first and subsequent linesby defaultthe object will wrap lines to width of charactersalthough we can change this by passing another keyword argument datetime module str format( __format__( we could have written this using triple quoted stringbut we prefer to put in the newlines manually the textwrap textwrapper object provides wrap(method that takes string as inputin this case the narrative textand returns list of strings with suitable indentation and each no longer than the wrap width we then join this list of lines into single string using newline as the separator the incident date is held as datetime date objectwe have forced str format(to use the string representation when writing the date--this very conveniently produces the date in iso yyyy-mm-dd format we have told str format(to write the midair bool as an integer--this produces for true and for false in generalusing str format(makes writing text very easy because it handles all of python' data types (and custom types if we implement the __str__(or __format__(special methodautomatically
8,842
parsing text |the method for reading and parsing text format aircraft incident records is longer and more involved than the one used for writing when reading the file we could be in one of several states we could be in the middle of reading narrative lineswe could be at key=value lineor we could be at report id line at the start of new incident we will look at the import_text_manual(method in five parts def import_text_manual(selffilename)fh none tryfh open(filenameencoding="utf "self clear(data {narrative none the method begins by opening the file in "read textmode then we clear the dictionary of incidents and create the data dictionary to hold the data for single incident in the same way as we did when reading binary incident records the narrative variable is used for two purposesas state indicator and to store the current incident' narrative text if narrative is none it means that we are not currently reading narrativebut if it is string (even an empty oneit means we are in the process of reading narrative lines for linoline in enumerate(fhstart= )line line rstrip(if not line and narrative is nonecontinue if narrative is not noneif line =narrative_end "data["narrative"textwrap dedentnarrativestrip(if len(data! raise incidenterror("missing data on "line { }format(lino)incident incident(**dataself[incident report_idincident data {narrative none elsenarrative +line "\nsince we are reading line by line we can keep track of the current line number and use this to provide more informative error messages than is possible when reading binary files we begin by stripping off any trailing whitespace from
8,843
file handling the lineand if this leaves us with an empty line (and providing we are not in the middle of narrative)we simply skip to the next line this means that the number of blank lines between incidents doesn' matterbut that we preserve any blank lines that are in narrative texts if the narrative is not none we know that we are in narrative if the line is the narrative end marker we know that we have not only finished reading the narrativebut also finished reading all the data for the current incident in this case we put the narrative text into the data dictionary (having removed the indentation with the textwrap dedent(function)and providing we have the nine pieces of data we needwe create new incident and store it in the dictionary then we clear the data dictionary and reset the narrative variable ready for the next record on the other handif the line isn' the narrative end markerwe append it to the narrative--including the newline that was stripped off at the beginning elif (not data and line[ ="[and line[- ="]")data["report_id"line[ :- if the narrative is none then we are at either new report id or are reading some other data we could be at new report id only if the data dictionary is empty (because it starts that way and because we clear it after reading each incident)and if the line begins with and ends with if this is the case we put the report id into the data dictionary this means that this elif condition will not be true again until the data dictionary is next cleared elif "=in linekeyvalue line split("=" if key ="date"data[keydatetime datetime strptime(value"% -% -% "date(elif key ="pilot_percent_hours_on_type"data[keyfloat(valueelif key ="pilot_total_hours"data[keyint(valueelif key ="midair"data[keybool(int(value)elsedata[keyvalue elif line =narrative_start "narrative "elseraise keyerror("parsing error on line { }formatlino)
8,844
if we are not in narrative and are not reading new report id there are only three more possibilitieswe are reading key=value itemswe are at narrative start markeror something has gone wrong in the case of reading line of key=value datawe split the line on the first characterspecifying maximum of one split--this means that the value can safely include characters all the data read is in the form of unicode stringsso for datenumericand boolean data types we must convert the value string accordingly for dates we use the datetime datetime strptime(function ("string parse time"which takes format string and returns datetime datetime object we have used format string that matches the iso date formatand we use datetime datetime date(to retrieve datetime date object from the resultant datetime datetime objectsince we want only date and not date/time we rely on python' built-in type functionsfloat(and int()for the numeric conversions notethough thatfor exampleint(" "will raise valueerrorif we want to be more liberal in accepting integerswe could use int(float(" "))or if we wanted to round rather than truncateround(float(" ")to get bool is slightly subtler--for examplebool(" "returns true ( nonempty string is true)so we must first convert the string to an int invalidmissingor out-of-range values will always cause an exception to be raised if any of the conversions fail they raise valueerror exception and if any values are out of range an incidenterror exception will be raised when the data is used to create corresponding incident object if the line doesn' contain an characterwe check to see whether we've read the narrative start marker if we havewe set the narrative variable to be an empty string this means that the first if condition will be true for subsequent linesat least until the narrative end marker is read if none of the if or elif conditions is true then an error has occurredso in the final else clause we raise keyerror exception to signify this return true except (environmenterrorvalueerrorkeyerrorincidenterroras errprint("{ }import error{ }formatos path basename(sys argv[ ])err)return false finallyif fh is not nonefh close(after reading all the lineswe return true to the caller--unless an exception occurredin which case the except block catches the exceptionprints an error
8,845
file handling message for the userand returns false and no matter whatif the file was openedit is closed at the end parsing text using regular expressions |readers unfamiliar with regular expressions ("regexes"are recommended to read before reading this section--or to skip ahead to the following section )and return here later if desired using regular expressions to parse text files can often produce shorter code than doing everything by hand as we did in the previous subsectionbut it can be more difficult to provide good error reporting we will look at the import_text_regex(method in two partsfirst looking at the regular expressions and then at the parsing--but omitting the except and finally blocks since they have nothing new to teach us def import_text_regex(selffilename)incident_re re compiler"\[(? [^]]+)\](? +?) "^narrative_start$(? *?) "^narrative_end$"re dotall|re multilinekey_value_re re compile( "^\ *(? [^=]+?)\ *=\ * "(? +?)\ *$"re multilineraw strings the regular expressions are written as raw strings this saves us from having to double each backslash (writing each as \\)--for examplewithout using raw strings the second regular expression would have to be written as "^\\ *(? [^=]+?)\\ *=\\ *(? +?)\\ *$in this book we always use raw strings for regular expressions the first regular expressionincident_reis used to capture an entire incident record one effect of this is that any spurious text between records will not be noticed this regular expression really has two parts the first is \[(? [^]]+)\](? +?which matches [then matches and captures into the id match group as many non-characters as it canthen matches (so this gives us the report id)and then matches as few--but at least one--of any characters (including newlines because of the re dotall flag)into the keyvalues match group the characters matched for the keyvalues match group are the minimum necessary to take us to the second part of the regular expression the second part of the first regular expression is ^narrative_start(? *?)^narrative_endand this matches the literal text narrative_start then as few characters as possible which are captured into the narrative match groupand then the literal text narrative_end at the end of
8,846
the incident record the re multiline flag means that in this regular expression matches at the start of every line (rather than just at the start of the string)and matches at the end of every line (rather than just at the end of the string)so the narrative start and end markers are matched only at the start of lines the second regular expressionkey_value_reis used to capture key=value linesand it matches at the start of every line in the text it is given to match againstwhere the line begins with any amount of whitespace (including none)followed by non-characters which are captured into the key match groupfollowed by an characterfollowed by all the remaining characters in the line (excluding any leading or trailing whitespace)and captures them into the value match group the fundamental logic used to parse the file is the same as we used for the manual text parser that we covered in the previous subsectiononly this time we extract incident records and incident data within those records using regular expressions rather than reading line by line fh none tryfh open(filenameencoding="utf "self clear(for incident_match in incident_re finditer(fh read())data {data["report_id"incident_match group("id"data["narrative"textwrap dedentincident_match group("narrative")strip(keyvalues incident_match group("keyvalues"for match in key_value_re finditer(keyvalues)data[match group("key")match group("value"data["date"datetime datetime strptimedata["date"]"% -% -% "date(data["pilot_percent_hours_on_type"float(data["pilot_percent_hours_on_type"])data["pilot_total_hours"intdata["pilot_total_hours"]data["midair"bool(int(data["midair"])if len(data! raise incidenterror("missing data"incident incident(**dataself[incident report_idincident return true the re finditer(method returns an iterator which produces each nonoverlapping match in turn we create data dictionary to hold one incident' data as we have done beforebut this time we get the report id and narrative text
8,847
file handling from each match of the incident_re regular expression we then extract all the key=value strings in one go using the keyvalues match groupand apply the key_value_re regular expression' re finditer(method to iterate over each individual key=value line for each (keyvaluepair foundwe put them in the data dictionary--so all the values go in as strings thenfor those values which should not be stringswe replace them with value of the appropriate type using the same string conversions that we used when parsing the text manually we have added check to ensure that the data dictionary has nine items because if an incident record is corruptthe key_value finditer(iterator might match too many or too few key=value lines the end is the same as before--we create new incident object and put it in the incidents dictionarythen return true if anything went wrongthe except suite will issue suitable error message and return falseand the finally suite will close the file one of the things that makes both the manual and the regular expression text parsers as short and straightforward as they are is python' exceptionhandling the parsers don' have to check any of the conversions of strings to datesnumbersor booleansand they don' have to do any range checking (the incident class does thatif any of these things failan exception will be raisedand we handle all the exceptions neatly in one place at the end another benefit of using exception-handling rather than explicit checking is that the code scales well--even if the record format changes to include more data itemsthe error handling code doesn' need to grow any larger writing and parsing xml files ||some programs use an xml file format for all the data they handlewhereas others use xml as convenient import/export format the ability to import and export xml is useful and is always worth considering even if program' main format is text or binary format out of the boxpython offers three ways of writing xml filesmanually writing the xmlcreating an element tree and using its write(methodand creating dom and using its write(method similarlyfor reading and parsing xml files there are four out-of-the-box approaches that can be usedmanually reading and parsing the xml (not recommended and not covered here--it can be quite difficult to handle some of the more obscure and advanced details correctly)or using an element treedomor sax parser in additionthere are also third-party xml libraries availablesuch as the lxml library mentioned in ( )that are well worth investigating the aircraft incident xml format is shown in figure in this section we will show how to write this format manually and how to write it using an element tree and domas well as how to read and parse this format using the element
8,848
<incident report_id=" gdate="aircraft_id=" aircraft_type="ce- -mpilot_percent_hours_on_type=" pilot_total_hours=" midair=" "bowerman on go-around from night crosswind landing attempt the aircraft hit runway edge light damaging one propeller figure an example xml format aircraft incident record in context treedomand sax parsers if you don' care which approach is used to read or write the xmlyou could just read the element trees subsection that followsand then skip to the final section (random access binary files element trees |writing the data using an element tree is done in two phasesfirst an element tree representing the data must be createdand second the tree must be written to file some programs might use the element tree as their data structurein which case they already have the tree and can simply write out the data we will look at the export_xml_etree(method in two partsdef export_xml_etree(selffilename)root xml etree elementtree element("incidents"for incident in self values()element xml etree elementtree element("incident"report_id=incident report_iddate=incident date isoformat()aircraft_id=incident aircraft_idaircraft_type=incident aircraft_typepilot_percent_hours_on_type=strincident pilot_percent_hours_on_type)pilot_total_hours=str(incident pilot_total_hours)
8,849
file handling midair=str(int(incident midair))airport xml etree elementtree subelement(element"airport"airport text incident airport strip(narrative xml etree elementtree subelement(element"narrative"narrative text incident narrative strip(root append(elementtree xml etree elementtree elementtree(rootwe begin by creating the root element (then we iterate over all the incident records for each one we create an element (to hold the data for the incidentand use keyword arguments to provide the attributes all the attributes must be textso we convert the datenumericand boolean data items accordingly we don' have to worry about escaping "&""(or about quotes in attribute values)since the element tree module (and the dom and sax modulesautomatically take care of these details each has two subelementsone holding the airport name and the other the narrative text when subelements are created we must provide the parent element and the tag name an element' read/write text attribute is used to hold its text once the has been created with all its attributes and its and subelementswe add the incident to the hierarchy' root (element at the end we have hierarchy of elements that contains all the incident record datawhich we then trivially convert into an element tree trytree write(filename"utf- "except environmenterror as errprint("{ }import error{ }formatos path basename(sys argv[ ])err)return false return true writing the xml to represent an entire element tree is simply matter of telling the tree to write itself to the given file using the given encoding up to now when we have specified an encoding we have almost always used the string "utf this works fine for python' built-in open(function which can accept wide range of encodings and variety of names for themsuch as "utf- ""utf ""utf- "and "utf but for xml files the encoding name can be only one of the official namesso "utf is not acceptablewhich is why we have used "utf- see www org/tr/ /rec-xml - /#nt-encodingdecl and www iana org/assignments/character-sets for information about xml encodings
8,850
reading an xml file using an element tree is not much harder than writing one again there are two phasesfirst we read and parse the xml fileand then we traverse the resultant element tree to read off the data to populate the incidents dictionary again this second phase is not necessary if the element tree itself is being used as the in-memory data store here is the import_xml_etree(methodsplit into two parts def import_xml_etree(selffilename)trytree xml etree elementtree parse(filenameexcept (environmenterrorxml parsers expat expaterroras errprint("{ }import error{ }formatos path basename(sys argv[ ])err)return false by defaultthe element tree parser uses the expat xml parser under the hood which is why we must be ready to catch expat exceptions self clear(for element in tree findall("incident")trydata {for attribute in ("report_id""date""aircraft_id""aircraft_type""pilot_percent_hours_on_type""pilot_total_hours""midair")data[attributeelement get(attributedata["date"datetime datetime strptimedata["date"]"% -% -% "date(data["pilot_percent_hours_on_type"float(data["pilot_percent_hours_on_type"])data["pilot_total_hours"intdata["pilot_total_hours"]data["midair"bool(int(data["midair"])data["airport"element find("airport"text strip(narrative element find("narrative"text data["narrative"(narrative strip(if narrative is not none else ""incident incident(**dataself[incident report_idincident except (valueerrorlookuperrorincidenterroras errprint("{ }import error{ }formatos path basename(sys argv[ ])err)return false return true
8,851
file handling once we have the element tree we can iterate over every using the xml etree elementtree findall(method each incident is returned as an xml etree element object we use the same technique for handling the element attributes as we did in the previous section' import_text_regex(method--first we store all the values in the data dictionaryand then we convert those values which are datesnumbersor booleans to the correct type for the airport and narrative subelements we use the xml etree element find(method to find them and read their text attributes if text element has no text its text attribute will be noneso we must account for this when reading the narrative text element since it might be empty in all casesthe attribute values and text returned to us do not contain xml escapes since they are automatically unescaped as with all the xml parsers used to process aircraft incident dataan exception will occur if the aircraft or narrative element is missingor if one of the attributes is missingor if one of the conversions failsor if any of the numeric data is out of range--this ensures that invalid data will cause parsing to stop and for an error message to be output the code at the end for creating and storing incidents and for handling exceptions is the same as we have seen before dom (document object model|the dom is standard api for representing and manipulating an xml document in memory the code for creating dom and writing it to fileand for parsing an xml file using domis structurally very similar to the element tree codeonly slightly longer we will begin by reviewing the export_xml_dom(method in two parts this method works in two phasesfirst dom is created to reflect the incident dataand then the dom is written out to file just as with an element treesome programs might use the dom as their data structurein which case they can simply write out the data def export_xml_dom(selffilename)dom xml dom minidom getdomimplementation(tree dom createdocument(none"incidents"noneroot tree documentelement for incident in self values()element tree createelement("incident"for attributevalue in ("report_id"incident report_id)("date"incident date isoformat())("aircraft_id"incident aircraft_id)("aircraft_type"incident aircraft_type)("pilot_percent_hours_on_type"str(incident pilot_percent_hours_on_type))
8,852
("pilot_total_hours"str(incident pilot_total_hours))("midair"str(int(incident midair))))element setattribute(attributevaluefor nametext in (("airport"incident airport)("narrative"incident narrative))text_element tree createtextnode(textname_element tree createelement(namename_element appendchild(text_elementelement appendchild(name_elementroot appendchild(elementthe method begins by getting dom implementation by defaultthe implementation is provided by the expat xml parser the xml dom minidom module provides simpler and smaller dom implementation than that provided by the xml dom modulealthough the objects it uses are from the xml dom module once we have dom implementation we can create document the first argument to xml dom domimplementation createdocument(is the namespace uri which we don' needso we pass nonethe second argument is qualified name (the tag name for the root element)and the third argument is the document typeand again we pass none since we don' have document type having gotten the tree that represents the documentwe retrieve the root element and then proceed to iterate over all the incidents for each incident we create an elementand for each attribute we want the incident to have we call setattribute(with the attribute' name and value just as with the element treewe don' have to worry about escaping "&""(or about quotes in attribute valuesfor the airport and narrative text elements we must create text element to hold the text and normal element (with the appropriate tag nameas the text element' parent--we then add the normal element (and the text element it containsto the current incident element with the incident element completewe add it to the root fh none tryfh open(filename" "encoding="utf "tree writexml(fhencoding="utf- "return true xml encoding we have omitted the except and finally blocks since they are the same as ones we have already seen what this piece of code makes clear is the difference between the encoding string used for the built-in open(function and the encoding string used for xml filesas we discussed earlier importing an xml document into dom is similar to importing into an element treebut like exportingit requires more code we will look at the im
8,853
file handling port_xml_dom(function in three partsstarting with the def line and the nested get_text(function def import_xml_dom(selffilename)def get_text(node_list)text [for node in node_listif node nodetype =node text_nodetext append(node datareturn "join(textstrip(the get_text(function iterates over list of nodes ( node' child nodes)and for each one that is text nodeit extracts the node' text and appends it to list of texts at the end the function returns all the text it has gathered as single stringwith whitespace stripped from both ends trydom xml dom minidom parse(filenameexcept (environmenterrorxml parsers expat expaterroras errprint("{ }import error{ }formatos path basename(sys argv[ ])err)return false parsing an xml file into dom is easy since the module does all the hard work for usbut we must be ready to handle expat errors since just like an element treethe expat xml parser is the default parser used by the dom classes under the hood self clear(for element in dom getelementsbytagname("incident")trydata {for attribute in ("report_id""date""aircraft_id""aircraft_type""pilot_percent_hours_on_type""pilot_total_hours""midair")data[attributeelement getattribute(attributedata["date"datetime datetime strptimedata["date"]"% -% -% "date(data["pilot_percent_hours_on_type"float(data["pilot_percent_hours_on_type"])data["pilot_total_hours"intdata["pilot_total_hours"]data["midair"bool(int(data["midair"])airport element getelementsbytagname("airport")[
8,854
data["airport"get_text(airport childnodesnarrative element getelementsbytagname"narrative")[ data["narrative"get_text(narrative childnodesincident incident(**dataself[incident report_idincident except (valueerrorlookuperrorincidenterroras errprint("{ }import error{ }formatos path basename(sys argv[ ])err)return false return true once the dom exists we clear the current incidents data and iterate over all the incident tags for each one we extract the attributesand for datenumericand booleans we convert them to the correct types in exactly the same way as we did when using an element tree the only really significant difference between using dom and an element tree is in the handling of text nodes we use the xml dom element getelementsbytagname(method to get the child elements with the given tag name--in the cases of and we know there is always one of eachso we take the first (and onlychild element of each type then we use the nested get_text(function to iterate over these tagschild nodes to extract their texts as usualif any error occurs we catch the relevant exceptionprint an error message for the userand return false the differences in approach between dom and element tree are not greatand since they both use the same expat parser under the hoodthey're both reasonably fast manually writing xml |writing preexisting element tree or dom as an xml document can be done with single method call but if our data is not already in one of these forms we must create an element tree or dom firstin which case it may be more convenient to simply write out our data directly when writing xml files we must make sure that we properly escape text and attribute valuesand that we write well-formed xml document here is the export_xml_manual(method for writing out the incidents in xmldef export_xml_manual(selffilename)fh none tryfh open(filename" "encoding="utf "fh write('\ 'fh write("\ "local functions
8,855
file handling for incident in self values()fh write('<incident report_id={report_id'date="{ date! }'aircraft_id={aircraft_id'aircraft_type={aircraft_type'pilot_percent_hours_on_type='"{ pilot_percent_hours_on_type}'pilot_total_hours="{ pilot_total_hours}'midair="{ midair: }">\ '{airport}\ '\ {narrative}\ \ '\nformat(incidentreport_id=xml sax saxutils quoteattrincident report_id)aircraft_id=xml sax saxutils quoteattrincident aircraft_id)aircraft_type=xml sax saxutils quoteattrincident aircraft_type)airport=xml sax saxutils escape(incident airport)narrative="\njoin(textwrap wrapxml sax saxutils escapeincident narrative strip()) )))fh write("\ "return true as we have often done in this we have omitted the except and finally blocks we write the file using the utf- encoding and must specify this to the built-in open(function strictly speakingwe don' have to specify the encoding in the declaration since utf- is the default encodingbut we prefer to be explicit we have chosen to quote all the attribute values using double quotes (")and so for convenience have used single quotes to quote the string we put the incidents in to avoid the need to escape the quotes the sax saxutils quoteattr(function is similar to the sax saxutils escape(function we use for xml text in that it properly escapes "&""characters in additionit escapes quotes (if necessary)and returns string that has quotes around it ready for use this is why we have not needed to put quotes around the report id and other string attribute values the newlines we have inserted and the text wrapping for the narrative are purely cosmetic they are designed to make the file easier for humans to read and editbut they could just as easily be omitted writing the data in html format is not much different from writing xml the convert-incidents py program includes the export_html(function as simple
8,856
example of thisalthough we won' review it here because it doesn' really show anything new parsing xml with sax (simple api for xml|unlike the element tree and domwhich represent an entire xml document in memorysax parsers work incrementallywhich can potentially be both faster and less memory-hungry performance advantage cannot be assumedhoweverespecially since both the element tree and dom use the fast expat parser sax parsers work by announcing "parsing eventswhen they encounter start tagsend tagsand other xml elements to be able to handle those events that we are interested in we must create suitable handler classand provide certain predefined methods which are called when matching parsing events take place the most commonly implemented handler is content handleralthough it is possible to provide error handlers and other handlers if we want finer control here is the complete import_xml_sax(method it is very short because most of the work is done by the custom incidentsaxhandler classdef import_xml_sax(selffilename)fh none tryhandler incidentsaxhandler(selfparser xml sax make_parser(parser setcontenthandler(handlerparser parse(filenamereturn true except (environmenterrorvalueerrorincidenterrorxml sax saxparseexceptionas errprint("{ }import error{ }formatos path basename(sys argv[ ])err)return false we create the one handler we want to use and then we create sax parser and set its content handler to be the one we have created then we give the filename to the parser' parse(method and return true if no parsing errors occurred we pass self ( this incidentcollection dict subclassto the custom incidentsaxhandler class' initializer the handler clears the old incidents away and then builds up dictionary of incidents as the file is parsed once the parse is complete the dictionary contains all the incidents that have been read
8,857
file handling class incidentsaxhandler(xml sax handler contenthandler)def __init__(selfincidents)super(__init__(self __data {self __text "self __incidents incidents self __incidents clear(custom sax handler classes must inherit the appropriate base class this ensures that for any methods we don' reimplement (because we are not interested in the parsing events they handle)the base class version will be called--and will safely do nothing we start by calling the base class' initializer this is generally good practice for all subclassesalthough it is not necessary (though harmlessfor direct object subclasses the self __data dictionary is used to keep one incident' datathe self __text string is used to keep the text of an airport name or of narrative depending on which we are readingand the self __incidents dictionary is an object reference to the incidentcollection dictionary which the handler updates directly (an alternative design would be to have an independent dictionary inside the handler and to copy it to the incidentcollection at the end using dict clear(and then dict update(def startelement(selfnameattributes)if name ="incident"self __data {for keyvalue in attributes items()if key ="date"self __data[keydatetime datetime strptimevalue"% -% -% "date(elif key ="pilot_percent_hours_on_type"self __data[keyfloat(valueelif key ="pilot_total_hours"self __data[keyint(valueelif key ="midair"self __data[keybool(int(value)elseself __data[keyvalue self __text "whenever start tag and its attributes are read the xml sax handler contenthandler startelement(method is called with the tag name and the tag' attributes in the case of an aircraft incidents xml filethe start tags are which we ignorewhose attributes we use to populate some of the self __data dictionaryand and both of
8,858
which we ignore we always clear the self __text string when we get start tag because no text tags are nested in the aircraft incident xml file format we don' do any exception-handling in the incidentsaxhandler class if an exception occurs it will be passed up to the callerin this case the import_xml_sax(methodwhich will catch it and output suitable error message def endelement(selfname)if name ="incident"if len(self __data! raise incidenterror("missing data"incident incident(**self __dataself __incidents[incident report_idincident elif name in frozenset({"airport""narrative"})self __data[nameself __text strip(self __text "when an end tag is read the xml sax handler contenthandler endelement(method is called if we have reached the end of an incident we should have all the necessary dataso we create new incident object and add it to the incidents dictionary if we have reached the end of text elementwe add an item to the self __data dictionary with the text that has been accumulated so far at the end we clear the self __text string ready for its next use (strictly speakingwe don' have to clear itsince we clear it when we get start tagbut clearing it could make difference in some xml formatsfor examplewhere tags can be nested def characters(selftext)self __text +text when the sax parser reads text it calls the xml sax handler contenthandler characters(method there is no guarantee that this method will be called just once with all the textthe text might come in chunks this is why we simply use the method to accumulate textand actually put the text into the dictionary only when the relevant end tag is reached ( more efficient implementation would have self __text be list with the body of this method being self __text append(text)and with the other methods adapted accordingly using the sax api is very different from using element tree or dombut it is just as effective we can provide other handlersand can reimplement additional methods in the content handler to get as much control as we like the sax parser itself does not maintain any representation of the xml document--this makes sax ideal for reading xml into our own custom data collectionsand also means that there is no sax "documentto write out as xmlso for writing xml we must use one of the approaches described earlier in this section
8,859
file handling random access binary files ||in the earlier sections we worked on the basis that all of program' data was read into memory in one goprocessedand then all written out in one go modern computers have so much ram that this is perfectly viable approacheven for large data sets howeverin some situations holding the data on disk and just reading the bits we need and writing back changes might be better solution the disk-based random access approach is most easily done using key-value database ( "dbm")or full sql database--both are covered in --but in this section we will show how to handle random access files by hand we will first present the binaryrecordfile binaryrecordfile class instances of this class represent generic readable/writable binary filestructured as sequence of fixed length records we will then look at the bikestock bikestock class which holds collection of bikestock bike objects as records in binaryrecordfile binaryrecordfile to see how to make use of binary random access files generic binaryrecordfile class |the binaryrecordfile binaryrecordfile class' api is similar to list in that we can get/set/delete record at given index position when record is deletedit is simply marked "deleted"this saves having to move all the records that follow it up to fill the gapand also means that after deletion all the original index positions remain valid another benefit is that record can be undeleted simply by unmarking it the price we pay for this is that deleting records doesn' save any disk space we will solve this by providing methods to "compactthe fileeliminating deleted records (and invalidating index positionsbefore reviewing the implementationlet' look at some basic usagecontact struct struct("< si"contacts binaryrecordfile binaryrecordfile(filenamecontact sizehere we create struct (little-endian byte ordera -byte byte stringand -byte signed integerthat we will use to represent each record then we create binaryrecordfile binaryrecordfile instance with filename and with record size to match the struct we are using if the file exists it will be opened with its contents left intactotherwiseit will be created in either case it will be opened in binary read/write modeand once openwe can write data to itcontacts[ contact pack("abe bakerencode("utf ") contacts[ contact pack("cindy doveencode("utf ")
8,860
table file object attributes and methods # syntax description close(closes file object and sets attribute closed to true closed returns true if the file is closed encoding the encoding used for bytes str conversions fileno(returns the underlying file' file descriptor (available only for file objects that have file descriptors flush(flushes the file object isatty(returns true if the file object is associated with console (available only for file objects that refer to actual files mode the mode file object was opened with name file object ' filename (if it has onef newlines the kinds of newline strings encountered in text file __next__(returns the next line from file object in most casesthis method is used implicitlyfor examplefor line in peek(nreturns bytes without moving the file pointer position read(countreads at most count bytes from file object if count is not specified then every byte is read from the current file position to the end returns bytes object when reading in binary mode and str when reading in text mode if there is no more to read (end of file)an empty bytes or str is returned returns true if was opened for reading readable( readintobareads at most len(babytes into bytearray ba and returns the number of bytes read--this is at end of file (available only in binary mode readlinecountreads the next line (or up to count bytes if count is specified and reached before the \ character)including the \ readlinessizehintreads all the lines to the end of the file and returns them as list if sizehint is giventhen reads approximately up to sizehint bytes if the underlying file object supports this seekoffsetwhencemoves the file pointer position (where the next read or write will take placeto the given offset if whence is not given or is os seek_set moves the file pointer to the given offset (which may be negativerelative to the current position if whence is os seek_cur or relative to the end if whence is os seek_end writes are always done at the end in append "amode no matter where the file pointer is in text mode only the return value of tell(method calls should be used as offsets
8,861
file handling table file object attributes and methods # syntax description seekable(returns true if supports random access tell( truncatesizereturns the current file pointer position relative to the start of the file truncates the file to the current file pointer positionor to the given size if size is specified writable(returns true if was opened for writing write(swrites bytes/bytearray object to the file if opened in binary mode or str object to the file if opened in text mode writelinesseqwrites the sequence of objects (strings for text filesbyte strings for binary filesto the file we can treat the file like list using the item access operator ([])here we assign two byte strings (bytes objectseach containing an encoded string and an integerat two record index positions in the file these assignments will overwrite any existing contentand if the file doesn' already have six recordsthe earlier records will be created with every byte set to contact_data contact unpack(contacts[ ]contact_data[ decode("utf "rstrip(chr( )returns'cindy dovesince the string "cindy doveis shorter than the utf- characters in the structwhen it is packed it is padded with bytes at the end so when we retrieve the recordthe contact_data will hold the -tuple ( 'cindy dove\ \ \ \ \ ' to get the namewe must decode the utf- to produce unicode stringand strip off the padding bytes now that we've had glimpse of the class in actionwe are ready to review the code the binaryrecordfile binaryrecordfile class is in file binaryrecordfile py after the usual preliminaries the file begins with the definitions of couple of private byte values_deleted "\ _okay "\ each record starts with "statebyte which is either _deleted or _okay (or "\ in the case of blank recordshere is the class line and the initializerclass binaryrecordfiledef __init__(selffilenamerecord_sizeauto_flush=true)self __record_size record_size
8,862
mode " +bif not os path exists(filenameelse " +bself __fh open(filenamemodeself auto_flush auto_flush there are two different record sizes the binaryrecordfile record_size is the one set by the user and is the record size from the user' point of view the private binaryrecordfile __record_size is the real record size and includes the state byte we are careful not to truncate the file when we open it if it already exists (by using mode of " + ")and to create it if it does not exist (by using mode of " + ")--the "+part of the mode string is what signifies reading and writing if the binaryrecordfile auto_flush boolean is truethe file is flushed before every read and after every write @property def record_size(self)return self __record_size @property def name(self)return self __fh name def flush(self)self __fh flush(def close(self)self __fh close(we have made the record size and filename into read-only properties the record size we report to the user is the one they requested and matches their records the flush and close methods simply delegate to the file object def __setitem__(selfindexrecord)assert isinstance(record(bytesbytearray))"binary data requiredassert len(record=self record_size"record must be exactly { bytesformatself record_size)self __fh seek(index self __record_sizeself __fh write(_okayself __fh write(recordif self auto_flushself __fh flush(this method supports the brf[idata syntax where brf is binary record filei record index positionand data byte string notice that the record must be the same size as the size is specified when the binary record file was created
8,863
file handling if the arguments are okaywe move the file position pointer to the first byte of the record--notice that here we use the real record sizethat iswe account for the state byte the seek(method moves the file pointer to an absolute byte position by default second argument can be given to make the movement relative to the current position or to the end (the attributes and methods provided by file objects are listed in tables and since the item is being set it obviously hasn' been deletedso we write the _okay state byteand then we write the user' binary record data the binary record file does not know or care about the record structure that is being used--only that records are of the right size we do not check whether the index is in range if the index is beyond the end of the file the record will be written in the correct position and every byte between the previous end of the file and the new record will automatically be set to "\ such blank records are neither _okay nor _deletedso we can distinguish them when we need to def __getitem__(selfindex)self __seek_to_index(indexstate self __fh read( if state !_okayreturn none return self __fh read(self record_sizewhen retrieving record there are four cases that we must account forthe record doesn' existthat isthe given index is beyond the endthe record is blankthe record has been deletedand the record is okay if the record doesn' exist the private __seek_to_index(method will raise an indexerror exception otherwiseit will seek to the byte where the record begins and we can read the state byte if the state is not _okay the record must either be blank or be deletedin which case we return noneotherwisewe read and return the record (another strategy would be to raise custom exception for blank or deleted recordssayblankrecorderror or deletedrecorderrorinstead of returning none def __seek_to_index(selfindex)if self auto_flushself __fh flush(self __fh seek( os seek_endend self __fh tell(offset index self __record_size if offset >endraise indexerror("no record at index position { }formatindex)self __fh seek(offset
8,864
this is private supporting method used by some of the other methods to move the file position pointer to the first byte of the record at the given index position we begin by checking to see whether the given index is in range we do this by seeking to the end of the file (byte offset of from the end)and using the tell(method to retrieve the byte position we have seeked to if the record' offset (index position real record sizeis at or after the end then the index is out of range and we raise suitable exception otherwisewe seek to the offset position ready for the next read or write def __delitem__(selfindex)self __seek_to_index(indexstate self __fh read( if state !_okayreturn self __fh seek(index self __record_sizeself __fh write(_deletedif self auto_flushself __fh flush(first we move the file position pointer to the right place if the index is in range ( if no indexerror exception has occurred)and providing the record isn' blank or already deletedwe delete the record by overwriting its state byte with _deleted def undelete(selfindex)self __seek_to_index(indexstate self __fh read( if state =_deletedself __fh seek(index self __record_sizeself __fh write(_okayif self auto_flushself __fh flush(return true return false this method begins by finding the record and reading its state byte if the record is deleted we overwrite the state byte with _okay and return true to the caller to indicate successotherwise (for blank or nondeleted records)we return false def __len__(self)if self auto_flushself __fh flush(self __fh seek( os seek_endboth python and have the seek constants os seek_setos seek_curand os seek_end for conveniencepython also has these constants in its io module ( io seek_set
8,865
file handling end self __fh tell(return end /self __record_size this method reports how many records are in the binary record file it does this by dividing the end byte position ( how many bytes are in the fileby the size of record we have now covered all the basic functionality offered by the binaryrecordfile binaryrecordfile class there is one last matter to considercompacting the file to eliminate blank and deleted records there are essentially two approaches we can take to this one approach is to overwrite blank or deleted records with records that have higher record index positions so that there are no gapsand truncating the file if there are any blank or deleted records at the end the inplace_compact(method does this the other approach is to copy the nonblank nondeleted records to temporary file and then to rename the temporary to the original using temporary file is particularly convenient if we also want to make backup the compact(method does this we will start by looking at the inplace_compact(methodin two parts def inplace_compact(self)index length len(selfwhile index lengthself __seek_to_index(indexstate self __fh read( if state !_okayfor next in range(index length)self __seek_to_index(nextstate self __fh read( if state =_okayself[indexself[nextdel self[nextbreak elsebreak index + we iterate over every recordreading the state of each one in turn if we find blank or deleted record we look for the next nonblank nondeleted record in the file if we find one we replace the blank or deleted record with the nonblank nondeleted one and delete the original nonblank nondeleted oneotherwisewe break out of the while loop entirely since we have run out of nonblank nondeleted records self __seek_to_index( state self __fh read(
8,866
if state !_okayself __fh truncate( elselimit none for index in range(len(self - )self __seek_to_index(indexstate self __fh read( if state !_okaylimit index elsebreak if limit is not noneself __fh truncate(limit self __record_sizeself __fh flush(if the first record is blank or deletedthen they must all be blank or deleted since the previous code moved all nonblank nondeleted records to the beginning of the file and blank and deleted ones to the end in this case we can simply truncate the file to bytes if there is at least one nonblank nondeleted record we iterate from the last record backward toward the first since we know that blank and deleted records have been moved to the end the limit variable is set to the earliest blank or deleted record (or left as none if there are no blank or deleted records)and the file is truncated accordingly an alternative to doing the compacting in-place is to do it by copying to another file--this is useful if we want to make backupas the compact(method that we will review next shows def compact(selfkeep_backup=false)compactfile self __fh name $$$backupfile self __fh name bakself __fh flush(self __fh seek( fh open(compactfile"wb"while truedata self __fh read(self __record_sizeif not databreak if data[: =_okayfh write(datafh close(self __fh close(os rename(self __fh namebackupfileos rename(compactfileself __fh name
8,867
file handling if not keep_backupos remove(backupfileself __fh open(self __fh name" + "this method creates two filesa compacted file and backup copy of the original file the compacted file starts out with the same name as the original but with $$tacked on to the end of the filenameand similarly the backup file has the original filename with bak tacked on to the end we read the existing file record by recordand for those records that are nonblank and nondeleted we write them to the compacted file (notice that we write the real recordthat isthe state byte plus the user recordeach time bytes and bytearray sidebar the line if data[: =_okayis quite subtle both the data object and the _okay object are of type bytes we want to compare the first byte of the data object to the ( byte_okay object if we take slice of bytes objectwe get bytes objectbut if we take single bytesaydata[ ]we get an int--the byte' value so here we compare the byte slice of data (its first bytethe state bytewith the byte _okay object (another way of doing it would be to write if data[ =_okay[ ]which would compare the two int values at the end we rename the original file as the backup and rename the compacted file as the original we then remove the backup if keep_backup is false (the defaultfinallywe open the compacted file (which now has the original filename)ready to be read or written the binaryrecordfile binaryrecordfile class is quite low-levelbut it can serve as the basis of higher-level classes that need random access to files of fixed-size recordsas we will see in the next subsection examplethe bikestock module' classes |the bikestock module uses binaryrecordfile binaryrecordfile to provide simple stock control class the stock items are bicycleseach represented by bikestock bike instanceand the entire stock of bikes is held in bikestock bikestock instance the bikestock bikestock class aggregates dictionary whose keys are bike ids and whose values are record index positionsinto binaryrecordfile binaryrecordfile here is brief example of use to get feel for how these classes workbicycles bikestock bikestock(bike_filevalue for bike in bicyclesvalue +bike value bicycles increase_stock("gekko" for bike in bicyclesif bike identity startswith(" ")
8,868
if not bicycles increase_stock(bike identity )print("stock movement failed for"bike identitythis snippet opens bike stock file and iterates over all the bicycle records it contains to find the total value (sum of price quantityof the bikes held it then increases the number of "gekkobikes in stock by two and increments the stock held for all bikes whose bike id begins with " uby one all of these actions take place on diskso any other process that reads the bike stock file will always get the most current data although the binaryrecordfile binaryrecordfile works in terms of indexesthe bikestock bikestock class works in terms of bike ids this is managed by the bikestock bikestock instance holding dictionary that relates bike ids to indexes we will begin by looking at the bikestock bike class' class line and initializerthen we will look at few selected bikestock bikestock methodsand finally we will look at the code that provides the bridge between bikestock bike objects and the binary records used to represent them in binaryrecordfile binaryrecordfile (all the code is in the bikestock py file class bikedef __init__(selfidentitynamequantityprice)assert len(identity ("invalid bike identity '{ }'format(identity)self __identity identity self name name self quantity quantity self price price all of bike' attributes are available as properties--the bike id (self __identityas the read-only bike identity property and the others as read/write properties with some assertions for validation in additionthe bike value read-only property returns the quantity multiplied by the price (we have not shown the implementation of the properties since we have seen similar code before the bikestock bikestock class provides its own methods for manipulating bike objectsand they in turn use the writable bike properties class bikestockdef __init__(selffilename)self __file binaryrecordfile binaryrecordfile(filename_bike_struct sizeself __index_from_identity {for index in range(len(self __file))record self __file[indexif record is not none
8,869
file handling bike _bike_from_record(recordself __index_from_identity[bike identityindex the bikestock bikestock class is custom collection class that aggregates binary record file (self __fileand dictionary (self __index_from_identitywhose keys are bike ids and whose values are record index positions once the file has been opened (and created if it didn' already exist)we iterate over its contents (if anyeach bike is retrieved and converted from bytes object to bikestock bike using the private _bike_from_record(functionand the bike' identity and index are added to the self __index_from_identity dictionary def append(selfbike)index len(self __fileself __file[index_record_from_bike(bikeself __index_from_identity[bike identityindex appending new bike is matter of finding suitable index position and setting the record at that position to the bike' binary representation we also take care to update the self __index_from_identity dictionary def __delitem__(selfidentity)del self __file[self __index_from_identity[identity]deleting bike record is easywe just find its record index position from its identity and delete the record at that index position in the case of the bikestock bikestock class we have not made use of the binaryrecordfile binaryrecordfile' undeletion capability def __getitem__(selfidentity)record self __file[self __index_from_identity[identity]return none if record is none else _bike_from_record(recordbike records are retrieved by bike id if there is no such id the lookup in the self __index_from_identity dictionary will raise keyerror exceptionand if the record is blank or deleted the binaryrecordfile binaryrecordfile will return none but if record is retrieved we return it as bikestock bike object def __change_stock(selfidentityamount)index self __index_from_identity[identityrecord self __file[indexif record is nonereturn false bike _bike_from_record(recordbike quantity +amount self __file[index_record_from_bike(bikereturn true
8,870
increase_stock (lambda selfidentityamountself __change_stock(identityamount)decrease_stock (lambda selfidentityamountself __change_stock(identity-amount)the private __change_stock(method provides an implementation for the increase_stock(and decrease_stock(methods the bike' index position is found and the raw binary record is retrieved then the data is converted to bikestock bike objectthe change is applied to the bikeand then the record in the file is overwritten with the binary representation of the updated bike object (there is also __change_bike(method that provides an implementation for the change_name(and change_price(methodsbut none of these are shown because they are very similar to what' shown here def __iter__(self)for index in range(len(self __file))record self __file[indexif record is not noneyield _bike_from_record(recordthis method ensures that bikestock bikestock objects can be iterated overjust like listwith bikestock bike object returned at each iterationand skipping blank and deleted records record record record recordn utf- encoded bytes utf- encoded bytes int float identity name quantity price figure the logical structure of bike record file the private _bike_from_record(and _record_from_bike(functions isolate the binary representation of the bikestock bike class from the bikestock bikestock class that holds collection of bikes the logical structure of bike record file is shown in figure the physical structure is slightly different because each record is preceded by state byte _bike_struct struct struct("< sid"def _bike_from_record(record)idnamequantityprice range( parts list(_bike_struct unpack(record)parts[idparts[iddecode("utf "rstrip("\ "parts[nameparts[namedecode("utf "rstrip("\ "
8,871
file handling return bike(*partsdef _record_from_bike(bike)return _bike_struct pack(bike identity encode("utf ")bike name encode("utf ")bike quantitybike pricesequence unpacking when we convert binary record into bikestock bike we first convert the tuple returned by unpack(into list this allows us to modify elementsin this case to convert utf- encoded bytes into strings with padding bytes stripped off we then use the sequence unpacking operator (*to feed the parts to the bikestock bike initializer packing the data is much simplerwe just have to make sure that we encode the strings as utf- bytes for modern desktop systems the need for application programs to use random access binary data decreases as ram sizes and disk speeds increase and when such functionality is neededit is often easiest to use dbm file or an sql database nonethelessthere are systems where the functionality shown here may be usefulfor exampleon embedded and other resource limited systems summary ||this showed the most widely used techniques for saving and loading collections of data to and from files we have seen how easy pickles are to useand how we can handle both compressed and uncompressed files without knowing in advance whether compression has been used we saw how writing and reading binary data requires careand saw that the code can be quite long if we need to handle variable length strings but we also learned that using binary files usually results in the smallest possible file sizes and the fastest writing and reading times we learned too that it is important to use magic number to identify our file type and to use version number to make it practical to change the format later on in this we saw that plain text is the easiest format for users to read and that if the data is structured well it can be straightforward for additional tools to be created to manipulate the data howeverparsing text data can be tricky we saw how to read text data both manually and using regular expressions xml is very popular data interchange format and it is generally useful to be able to at least import and export xml even when the normal format is binary or text one we saw how to write xml manually--including how to correctly escape attribute values and textual data--and how to write it using an element tree and dom we also learned how to parse xml using the element treedomand sax parsers that python' standard library provides
8,872
in the final section we saw how to create generic class to handle random access binary files that hold records of fixed sizeand then how to use the generic class in specific context this brings us to the end of all the fundamentals of python programming it is possible to stop reading right here and to write perfectly good python programs based on everything you have learned so far but it would be shame to stop now--python has so much more to offerfrom neat techniques that can shorten and simplify codeto some mind-bending advanced facilities that are at least nice to know abouteven if they are not often needed in the next we will go further with procedural and object-oriented programmingand we will also get taste of functional programming thenin the following we will focus more on broader programming techniques including threadingnetworkingdatabase programmingregular expressionsand gui (graphical user interfaceprogramming exercises ||the first exercise is to create simpler binary record file module than the one presented in this -one whose record size is exactly the same as what the user specifies the second exercise is to modify the bikestock module to use your new binary record file module the third exercise asks you to create program from scratch--the file handling is quite straightforwardbut some of the output formatting is rather challenging make newsimpler version of the binaryrecordfile module--one that does not use state byte for this version the record size specified by the user is the record size actually used new records must be added using new append(method that simply moves the file pointer to the end and writes the given record the __setitem__(method should only allow existing records to be replacedone easy way of doing this is to use the __seek_to_index(method with no state byte__getitem__(is reduced to mere three lines the __delitem__(method will need to be completely rewritten since it must move all the records up to fill the gapthis can be done in just over half dozen linesbut does require some thought the undelete(method must be removed since it is not supportedand the compact(and inplace_compact(methods must be removed because they are no longer needed all toldthe changes amount to fewer than new or changed lines and at least deleted lines compared with the originaland not counting doctests solution is provided in binaryrecordfile_ans py once you are confident that your simpler binaryrecordfile class workscopy the bikestock py file and modify it to work with your binaryrecordfile
8,873
file handling class this involves changing only handful of lines solution is provided in bikestock_ans py debugging binary formats can be difficultbut tool that can help is one that can do hex dump of binary file' contents create program that has the following console help textusagexdump py [optionsfile [file filen]options- --help show this help message and exit - blocksize--blocksize=blocksize block size ( [default - --decimal decimal block numbers [defaulthexadecimal- encoding--encoding=encoding encoding (ascii utf- [defaultutf- using this programif we have binaryrecordfile that is storing records with the structure "< (little-endian -byte signed integer -byte byte string)by setting the block size to match one record ( bytes including the state byte)we can get clear picture of what' in the file for examplexdump py - test dat block bytes utf- characters alpha bravo charlie delta each byte is represented by two-digit hexadecimal numberthe spacing between each set of four bytes ( between each group of eight hexadecimal digitsis purely to improve readability here we can see that the second record ("bravo"has been deleted since its state byte is rather than the used to indicate nonblank nondeleted records use the optparse module to handle the command-line options (by specifying an option' "typeyou can get optparse to handle the string-to-integer conversion for the block size it can be quite tricky to get the headings to line up correctly for any given block size and to line up the characters correctly for the last blockso make sure you test with various block sizes ( alsodon' forget that in variable length filesthe last block may be short as the example illustratesuse periods to stand for nonprintable characters the program can be written in fewer than lines spread over two functions solution is given in xdump py
8,874
further procedural programming further object-oriented programming functional-style programming advanced programming techniques |||in this we will look at wide variety of different programming techniques and introduce many additionaloften more advancedpython syntaxes some of the material in this is quite challengingbut keep in mind that the most advanced techniques are rarely needed and you can always skim the first time to get an idea of what can be done and read more carefully when the need arises the first section digs more deeply into python' procedural features it starts by showing how to use what we already covered in novel wayand then returns to the theme of generators that we only touched on in the section then introduces dynamic programming--loading modules by name at runtime and executing arbitrary code at runtime the section returns to the theme of local (nestedfunctionsbut in addition covers the use of the nonlocal keyword and recursive functions earlier we saw how to use python' predefined decorators--in this section we learn how to create our own decorators the section concludes with coverage of function annotations the second section covers all new material relating to object-oriented programming it begins by introducing __slots__a mechanism for minimizing the memory used by each object it then shows how to access attributes without using properties the section also introduces functors (objects that can be called like functions)and context managers--these are used in conjunction with the with keywordand in many cases ( file handlingthey can be used to replace try except finally constructs with simpler try except constructs the section also shows how to create custom context managersand introduces additional advanced object-oriented featuresincluding class decoratorsabstract base classesmultiple inheritanceand metaclasses the third section introduces some fundamental concepts of functional programmingand introduces some useful functions from the functoolsitertools
8,875
advanced programming techniques and operator modules this section also shows how to use partial function application to simplify codeand how to create and use coroutines all the previous put together have provided us with the "standard python toolboxthis takes everything that we have already covered and turns it into the "deluxe python toolbox"with all the original tools (techniques and syntaxes)plus many new ones that can make our programming easiershorterand more effective some of the tools can have interchangeable usesfor examplesome jobs can be done using either class decorator or metaclasswhereas otherssuch as descriptorscan be used in multiple ways to achieve different effects some of the tools covered herefor examplecontext managerswe will use all the timeand others will remain ready at hand for those particular situations for which they are the perfect solution ||further procedural programming most of this section deals with additional facilities relating to procedural programming and functionsbut the very first subsection is different in that it presents useful programming technique based on what we already covered without introducing any new syntax |branching using dictionaries as we noted earlierfunctions are objects like everything else in pythonand function' name is an object reference that refers to the function if we write function' name without parenthesespython knows we mean the object referenceand we can pass such object references around just like any others we can use this fact to replace if statements that have lots of elif clauses with single function call in we will review an interactive console program called dvds-dbm pythat has the following menu( )dd ( )dit ( )ist ( )emove ( )mport ( )port ( )uit the program has function that gets the user' choice and which will return only valid choicein this case one of " "" "" "" "" "" "and "qhere are two equivalent code snippets for calling the relevant function based on the user' choiceif action =" "add_dvd(dbelif action =" "edit_dvd(db
8,876
elif action =" "list_dvds(dbelif action =" "remove_dvd(dbelif action =" "import_(dbelif action =" "export(dbelif action =" "quit(db functions dict( =add_dvde=edit_dvdl=list_dvdsr=remove_dvdi=import_x=exportq=quitfunctions[action](dbthe choice is held as one-character string in the action variableand the database to be used is held in the db variable the import_(function has trailing underscore to keep it distinct from the built-in import statement in the right-hand code snippet we create dictionary whose keys are the valid menu choicesand whose values are function references in the second statement we retrieve the function reference corresponding to the given action and call the function referred to using the call operator()and in this examplepassing the db argument not only is the code on the right-hand side much shorter than the code on the leftbut also it can scale (have far more dictionary itemswithout affecting its performanceunlike the left-hand code whose speed depends on how many elifs must be tested to find the appropriate function to call the convert-incidents py program from the preceding uses this technique in its import_(methodas this extract from the method showscall {(aix""dom")self import_xml_dom(aix""etree")self import_xml_etree(aix""sax")self import_xml_sax(ait""manual")self import_text_manual(ait""regex")self import_text_regex(aib"none)self import_binary(aip"none)self import_pickleresult call[extensionreader](filenamethe complete method is lines longthe extension parameter is computed in the methodand the reader is passed in the dictionary keys are -tuplesand the values are methods if we had used if statementsthe code would be lines longand would not scale as well generator expressions and functions generator functions |back in we introduced generator functions and methods it is also possible to create generator expressions these are syntactically almost
8,877
advanced programming techniques identical to list comprehensionsthe difference being that they are enclosed in parentheses rather than brackets here are their syntaxes(expression for item in iterable(expression for item in iterable if conditionin the preceding we created some iterator methods using yield expressions here are two equivalent code snippets that show how simple for in loop containing yield expression can be coded as generatordef items_in_key_order( )for key in sorted( )yield keyd[keydef items_in_key_order( )return ((keyd[key]for key in sorted( )both functions return generator that produces list of key-value items for the given dictionary if we need all the items in one go we can pass the generator returned by the functions to list(or tuple()otherwisewe can iterate over the generator to retrieve items as we need them generators provide means of performing lazy evaluationwhich means that they compute only the values that are actually needed this can be more efficient thansaycomputing very large list in one go some generators produce as many values as we ask for--without any upper limit for exampledef quarters(next_quarter= )while trueyield next_quarter next_quarter + this function will return and so onforever here is how we could use the generatorresult [for in quarters()result append(xif > break the break statement is essential--without it the for in loop will never finish at the end the result list is [ every time we call quarters(we get back generator that starts at and increments by but what if we want to reset the generator' current valueit is possible to pass value into generatoras this new version of the generator function showsdef quarters(next_quarter= )while true
8,878
received (yield next_quarterif received is nonenext_quarter + elsenext_quarter received the yield expression returns each value to the caller in turn in additionif the caller calls the generator' send(methodthe value sent is received in the generator function as the result of the yield expression here is how we can use the new generator functionresult [generator quarters(while len(result next(generatorif abs( sys float_info epsilonx generator send( result append(xwe create variable to refer to the generator and call the built-in next(function which retrieves the next item from the generator it is given (the same effect can be achieved by calling the generator' __next__(special methodin this casex generator __next__(if the value is equal to we send the value into the generator (which immediately yields this value backthis time the result list is [ in the next subsection we will review the magic-numbers py program which processes files given on the command line unfortunatelythe windows shell program (cmd exedoes not provide wildcard expansion (also called file globbing)so if program is run on windows with the argument *the literal text "*will go into the sys argv list instead of all the files in the current directory we solve this problem by creating two different get_files(functionsone for windows and the other for unixboth of which use generators here' the codeif sys platform startswith("win")def get_files(names)for name in namesif os path isfile(name)yield name elsefor file in glob iglob(name)if not os path isfile(file)continue yield file elsedef get_files(names)return (file for file in names if os path isfile(file)
8,879
advanced programming techniques in either case the function is expected to be called with list of filenamesfor examplesys argv[ :]as its argument on windows the function iterates over all the names listed for each filenamethe function yields the namebut for nonfiles (usually directories)the glob module' glob iglob(function is used to return an iterator to the names of the files that the name represents after wildcard expansion for an ordinary name like autoexec bat an iterator that produces one item (the nameis returnedand for name that uses wildcards like txt an iterator that produces all the matching files (in this case those with extension txtis returned (there is also glob glob(function that returns list rather than an iterator on unix the shell does wildcard expansion for usso we just need to return generator for all the files whose names we have been given generator functions can also be used as coroutinesif we structure them correctly coroutines are functions that can be suspended in mid-execution (at the yield expression)waiting for the yield to provide result to work onand once received they continue processing as we will see in the coroutines subsection later in this )coroutines can be used to distribute work and to create processing pipelines dynamic code execution and dynamic imports |there are some occasions when it is easier to write piece of code that generates the code we need than to write the needed code directly and in some contexts it is useful to let users enter code ( functions in spreadsheet)and to let python execute the entered code for us rather than to write parser and handle it ourselves--although executing arbitrary code like this is potential security riskof course another use case for dynamic code execution is to provide plug-ins to extend program' functionality using plug-ins has the disadvantage that all the necessary functionality is not built into the program (which can make the program more difficult to deploy and runs the risk of plug-ins getting lost)but has the advantages that plug-ins can be upgraded individually and can be provided separatelyperhaps to provide enhancements that were not originally envisaged dynamic code execution the easiest way to execute an expression is to use the built-in eval(function we first saw in for examplex eval("( * " = the glob glob(functions are not as powerful assaythe unix bash shellsince although they support the *?and [syntaxesthey don' support the {syntax
8,880
this is fine for user-entered expressionsbut what if we need to create function dynamicallyfor that we can use the built-in exec(function for examplethe user might give us formula such as and the name "area of sphere"which they want turned into function assuming that we replace with math pithe function they want can be created like thisimport math code ''def area_of_sphere( )return math pi * ''context {context["math"math exec(codecontextwe must use proper indentation--after allthe quoted code is standard python (although in this case we could have written it all on single line because the suite is just one line if exec(is called with some code as its only argument there is no way to access any functions or variables that are created as result of the code being executed furthermoreexec(cannot access any imported modules or any of the variablesfunctionsor other objects that are in scope at the point of the call both of these problems can be solved by passing dictionary as the second argument the dictionary provides place where object references can be kept for accessing after the exec(call has finished for examplethe use of the context dictionary means that after the exec(callthe dictionary has an object reference to the area_of_sphere(function that was created by exec(in this example we needed exec(to be able to access the math moduleso we inserted an item into the context dictionary whose key is the module' name and whose value is an object reference to the corresponding module object this ensures that inside the exec(callmath pi is accessible in some cases it is convenient to provide the entire global context to exec(this can be done by passing the dictionary returned by the globals(function one disadvantage of this approach is that any objects created in the exec(call would be added to the global dictionary solution is to copy the global context into dictionaryfor examplecontext globals(copy(this still gives exec(access to imported modules and the variables and other objects that are in scopeand because we have copiedany changes to the context made inside the exec(call are kept in the context dictionary and are not propagated to the global environment (it would appear to be more secure to use copy deepcopy()but if security is concern it is best to avoid exec(altogether we can also pass the local contextfor exampleby passing locals(as third argument--this makes objects in the local scope accessible to the code executed by exec(
8,881
advanced programming techniques after the exec(call the context dictionary contains key called "area_of_ spherewhose value is the area_of_sphere(function here is how we can access and call the functionarea_of_sphere context["area_of_sphere"area area_of_sphere( area = the area_of_sphere object is an object reference to the function we have dynamically created and can be used just like any other function and although we created only single function in the exec(callunlike eval()which can operate on only single expressionexec(can handle as many python statements as we likeincluding entire modulesas we will see in the next subsubsection dynamically importing modules python provides three straightforward mechanisms that can be used to create plug-insall of which involve importing modules by name at runtime and once we have dynamically imported additional moduleswe can use python' introspection functions to check the availability of the functionality we wantand to access it as required in this subsubsection we will review the magic-numbers py program this program reads the first bytes of each file given on the command line and for each one outputs the file' type (or the text "unknown")and the filename here is an example command line and an extract from its outputc:\python \python exe magic-numbers py :\windows\xml :\windows\windowsshell manifest unknown :\windows\windowsupdate log windows executable :\windows\winhelp exe windows executable :\windows\winhlp exe windows bmp image :\windows\winnt bmp the program tries to load in any module that is in the same directory as the program and whose name contains the text "magicsuch modules are expected to provide single public functionget_file_type(two very simple example modulesstandardmagicnumbers py and windowsmagicnumbers pythat each have get_file_type(function are provided with the book' examples we will review the program' main(function in two parts def main()modules load_modules(get_file_type_functions [for module in modules
8,882
get_file_type get_function(module"get_file_type"if get_file_type is not noneget_file_type_functions append(get_file_typein momentwe will look at three different implementations of the load_modules(function which returns (possibly emptylist of module objectsand we will look at the get_function(function further on for each module found we try to retrieve get_file_type(functionand add any we get to list of such functions for file in get_files(sys argv[ :])fh none tryfh open(file"rb"magic fh read( for get_file_type in get_file_type_functionsfiletype get_file_type(magicos path splitext(file)[ ]if filetype is not noneprint("{ < }{ }format(filetypefile)break elseprint("{ < }{ }format("unknown"file)except environmenterror as errprint(errfinallyif fh is not nonefh close(this loop iterates over every file listed on the command line and for each one reads its first bytes it then tries each get_file_type(function in turn to see whether it can determine the current file' type if the file type is determinedthe details are printed and the inner loop is broken out ofwith processing continuing with the next file if no function can determine the file type--or if no get_file_type(functions were found--an "unknownline is printed we will now review three different (but equivalentways of dynamically importing modulesstarting with the longest and most difficult approachsince it shows every step explicitlydef load_modules()modules [for name in os listdir(os path dirname(__file__or ")if name endswith(py"and "magicin name lower()filename name name os path splitext(name)[ if name isidentifier(and name not in sys modules
8,883
advanced programming techniques fh none tryfh open(filename" "encoding="utf "code fh read(module type(sys)(namesys modules[namemodule exec(codemodule __dict__modules append(moduleexcept (environmenterrorsyntaxerroras errsys modules pop(namenoneprint(errfinallyif fh is not nonefh close(return modules we begin by iterating over all the files in the program' directory if this is the current directoryos path dirname(__file__will return an empty string which would cause os listdir(to raise an exceptionso we pass if necessary for each candidate file (ends with py and contains the text "magic")we get the module name by chopping off the file extension if the name is valid identifier it is viable module nameand if it isn' already in the global list of modules maintained in the sys modules dictionary we can try to import it we read the text of the file into the code string the next linemodule type(sys)(name)is quite subtle when we call type(it returns the type object of the object it is given so if we called type( we would get int back if we print the type object we just get something human readable like "int"but if we call the type object as functionwe get an object of that type back for examplewe can get the integer in variable by writing or int( )or type( )( )or int_type type( ) int_type( in this case we've used type(sysand sys is moduleso we get back the module type object (essentially the same as class object)and can use it to create new module with the given name just as with the int example where it didn' matter what integer we used to get the int type objectit doesn' matter what module we use (as long as it is one that existsthat ishas been importedto get the module type object once we have new (emptymodulewe add it to the global list of modules to prevent the module from being accidentally reimported this is done before calling exec(to more closely mimic the behavior of the import statement then we call exec(to execute the code we have read--and we use the module' dictionary as the code' context at the end we add the module to the list of modules we will pass back and if problem ariseswe delete the module from the global modules dictionary if it has been added--it will not have been added to the list of modules if an error occurred notice that exec(can handle any
8,884
table dynamic programming and introspection functions syntax description __import__imports module by namesee text compile(sourcefilemodereturns the code object that results from compiling the source textfile should be the filenameor ""mode must be "single""eval"or "execdelattr(objnamedeletes the attribute called name from object obj dir(objreturns the list of names in the local scopeor if obj is given then obj' names ( its attributes and methodseval(sourceglobalslocalsexec(objglobalslocalsreturns the result of evaluating the single expression in sourceif suppliedglobals is the global context and locals is the local context (as dictionariesevaluates object objwhich can be string or code object from compile()and returns noneif suppliedglobals is the global context and locals is the local context getattr(objnamevalreturns the value of the attribute called name from object objor val if given and there is no such attribute globals(returns dictionary of the current global context hasattr(objnamereturns true if object obj has an attribute called name locals(returns dictionary of the current local context setattr(objnamevalsets the attribute called name to the value val for the object objcreating the attribute if necessary type(objreturns object obj' type object vars(objreturns object obj' context as dictionaryor the local context if obj is not given amount of code (whereas eval(evaluates single expression--see table )and raises syntaxerror exception if there' syntax error here' the second way to dynamically load module at runtime--the code shown here replaces the first approach' try except blocktryexec("import namemodules append(sys modules[name]except syntaxerror as errprint(err
8,885
advanced programming techniques one theoretical problem with this approach is that it is potentially insecure the name variable could begin with sysand be followed by some destructive code and here is the third approachagain just showing the replacement for the first approach' try except blocktrymodule __import__(namemodules append(moduleexcept (importerrorsyntaxerroras errprint(errthis is the easiest way to dynamically import modules and is slightly safer than using exec()although like any dynamic importit is by no means secure because we don' know what is being executed when the module is imported none of the techniques shown here handles packages or modules in different pathsbut it is not difficult to extend the code to accommodate these--although it is worth reading the online documentationespecially for __import__()if more sophistication is required having imported the module we need to be able to access the functionality it provides this can be achieved using python' built-in introspection functionsgetattr(and hasattr(here' how we have used them to implement the get_function(functiondef get_function(modulefunction_name)function get_function cache get((modulefunction_name)noneif function is nonetryfunction getattr(modulefunction_nameif not hasattr(function"__call__")raise attributeerror(get_function cache[modulefunction_namefunction except attributeerrorfunction none return function get_function cache {ignoring the cache-related code for momentwhat the function does is call getattr(on the module object with the name of the function we want if there is no such attribute an attributeerror exception is raisedbut if there is such an attribute we use hasattr(to check that the attribute itself has the __call__ attribute--something that all callables (functions and methodshave (further on we will see nicer way of checking whether an attribute is collections callable
8,886
advanced programming techniques one common use case for local functions is when we want to use recursion in these casesthe enclosing function is calledsets things upand then makes the first call to local recursive function recursive functions (or methodsare ones that call themselves structurallyall directly recursive functions can be seen as having two casesthe base case and the recursive case the base case is used to stop the recursion recursive functions can be computationally expensive because for every recursive call another stack frame is usedhoweversome algorithms are most naturally expressed using recursion most python implementations have fixed limit to how many recursive calls can be made the limit is returned by sys getrecursionlimit(and can be changed by sys setrecursionlimit()although increasing the limit is most often sign that the algorithm being used is inappropriate or that the implementation has bug the classic example of recursive function is one that is used to calculate factorials for examplefactorial( will calculate and return that is def factorial( )if < return return factorial( this is not an efficient solutionbut it does show the two fundamental features of recursive functions if the given numberxis or less is returned and no recursion occurs--this is the base case but if is greater than the value returned is factorial( )and this is the recursive case because here the factorial function calls itself the function is guaranteed to terminate because if the initial is less than or equal to the base case will be used and the function will finish immediatelyand if is greater than each recursive call will be on number one less than before and so will eventually be to see both local functions and recursive functions in meaningful context we will study the indented_list_sort(function from module file indentedlist py this function takes list of strings that use indentation to create hierarchyand string that holds one level of indentand returns list with the same strings but where all the strings are sorted in case-insensitive alphabetical orderwith indented items sorted under their parent itemrecursivelyas the before and after lists shown in figure illustrate given the before listthe after list is produced by this callafter indentedlist indented_list_sort(beforethe default indent value is four spacesthe same as the indent used in the before listso we did not need to set it explicitly python' math module provides much more efficient math factorial(function
8,887
before ["nonmetals"hydrogen"carbon"nitrogen"oxygen""inner transitionals"lanthanides"cerium"europium"actinides"uranium"curium"plutonium""alkali metals"lithium"sodium"potassium" after ["alkali metals"lithium"potassium"sodium""inner transitionals"actinides"curium"plutonium"uranium"lanthanides"cerium"europium""nonmetals"carbon"hydrogen"nitrogen"oxygen"figure before and after sorting an indented list we will begin by looking at the indented_list_sort(function as wholeand then we will look at its two local functions def indented_list_sort(indented_listindent=keyitemchildren range( def add_entry(levelkeyitemchildren)def update_indented_list(entry)entries [for item in indented_listlevel while item startswith(indenti) +len(indentlevel + key item strip(lower(add_entry(levelkeyitementriesindented_list [for entry in sorted(entries)update_indented_list(entryreturn indented_list ")
8,888
advanced programming techniques the code begins by creating three constants that are used to provide names for index positions used by the local functions then we define the two local functions which we will review in moment the sorting algorithm works in two stages in the first stage we create list of entrieseach -tuple consisting of "keythat will be used for sortingthe original stringand list of the string' child entries the key is just lowercased copy of the string with whitespace stripped from both ends the level is the indentation level for top-level items for children of top-level itemsand so on in the second stage we create new indented list and add each string from the sorted entries listand each string' child stringsand so onto produce sorted indented list def add_entry(levelkeyitemchildren)if level = children append((keyitem[])elseadd_entry(level keyitemchildren[- ][children]this function is called for each string in the list the children argument is the list to which new entries must be added when called from the outer function (indented_list_sort())this is the entries list this has the effect of turning list of strings into list of entrieseach of which has top-level (unindentedstring and (possibly emptylist of child entries if the level is (top-level)we add new -tuple to the entries list this holds the key (for sorting)the original item (which will go into the resultant sorted list)and an empty children list this is the base case since no recursion takes place if the level is greater than the item is child (or descendantof the last item in the children list in this case we recursively call add_entry(againreducing the level by and passing the children list' last item' children list as the list to add to if the level is or moremore recursive calls will take placeuntil eventually the level is and the children list is the right one for the entry to be added to for examplewhen the "inner transitionalsstring is reachedthe outer function calls add_entry(with level of key of "inner transitionals"an item of "inner transitionals"and the entries list as the children list since the level is new item will be appended to the children list (entries)with the keyitemand an empty children list the next string is lanthanides"--this is indentedso it is child of the "inner transitionalsstring the add_entry(call this time has level of key of "lanthanides"an item of lanthanides"and the entries list as the children list since the level is the add_entry(function calls itself recursivelythis time with level ( )the same key and itembut with the children list being the children list of the last itemthat isthe "inner transitionalsitem' children list here is what the entries list looks like once all the strings have been addedbut before the sorting has been done
8,889
[('nonmetals''nonmetals'[('hydrogen'hydrogen'[])('carbon'carbon'[])('nitrogen'nitrogen'[])('oxygen'oxygen'[])])('inner transitionals''inner transitionals'[('lanthanides'lanthanides'[('cerium'cerium'[])('europium'europium'[])])('actinides'actinides'[('uranium'uranium'[])('curium'curium'[])('plutonium'plutonium'[])])])('alkali metals''alkali metals'[('lithium'lithium'[])('sodium'sodium'[])('potassium'potassium'[])])the output was produced using the pprint ("pretty print"module' pprint pprint(function notice that the entries list has only three items (all of which are -tuples)and that each -tuple' last element is list of child -tuples (or is an empty listthe add_entry(function is both local function and recursive function like all recursive functionsit has base case (in this functionwhen the level is that ends the recursionand recursive case the function could be written in slightly different waydef add_entry(keyitemchildren)nonlocal level if level = children append((keyitem[])elselevel - add_entry(keyitemchildren[- ][children]hereinstead of passing level as parameterwe use nonlocal statement to access variable in an outer enclosing scope if we did not change level inside the function we would not need the nonlocal statement--in such situationpython would not find it in the local (inner functionscopeand would look at the enclosing scope and find it there but in this version of add_entry(we
8,890
advanced programming techniques need to change level' valueand just as we need to tell python that we want to change global variables using the global statement (to prevent new local variable from being created rather than the global variable updated)the same applies to variables that we want to change but which belong to an outer scope although it is often best to avoid using global altogetherit is also best to use nonlocal with care def update_indented_list(entry)indented_list append(entry[item]for subentry in sorted(entry[children])update_indented_list(subentryin the algorithm' first stage we build up list of entrieseach (keyitemchildren -tuplein the same order as they are in the original list in the algorithm' second stage we begin with new empty indented list and iterate over the sorted entriescalling update_indented_list(for each one to build up the new indented list the update_indented_list(function is recursive for each top-level entry it adds an item to the indented_listand then calls itself for each of the item' child entries each child is added to the indented_listand then the function calls itself for each child' children--and so on the base case (when the recursion stopsis when an itemor childor child of childand so on has no children of its own python looks for indented_list in the local (inner functionscope and doesn' find itso it then looks in the enclosing scope and finds it there but notice that inside the function we append items to the indented_list even though we have not used nonlocal this works because nonlocal (and globalare concerned with object referencesnot with the objects they refer to in the second version of add_entry(we had to use nonlocal for level because the +operator applied to number rebinds the object reference to new object--what really happens is level level so level is set to refer to new integer object but when we call list append(on the indented_listit modifies the list itself and no rebinding takes placeand therefore nonlocal is not necessary (for the same reasonif we have dictionarylistor other global collectionwe can add or remove items from it without using global statement function and method decorators | decorator is function that takes function or method as its sole argument and returns new function or method that incorporates the decorated function or method with some additional functionality added we have already made use of some predefined decoratorsfor example@property and @classmethod in this subsection we will learn how to create our own function decoratorsand later in this we will see how to create class decorators class decorators
8,891
for our first decorator examplelet us suppose that we have many functions that perform calculationsand that some of these must always produce positive result we could add an assertion to each of thesebut using decorator is easier and clearer here' function decorated with the @positive_result decorator that we will create in moment@positive_result def discriminant(abc)return ( * ( cthanks to the decoratorif the result is ever less than an assertionerror exception will be raised and the program will terminate and of coursewe can use the decorator on as many functions as we like here' the decorator' implementationdef positive_result(function)def wrapper(*args**kwargs)result function(*args**kwargsassert result > function __name__ "(result isn' > return result wrapper __name__ function __name__ wrapper __doc__ function __doc__ return wrapper decorators define new local function that calls the original function herethe local function is wrapper()it calls the original function and stores the resultand it uses an assertion to guarantee that the result is positive (or that the program will terminatethe wrapper finishes by returning the result computed by the wrapped function after creating the wrapperwe set its name and docstring to those of the original function this helps with introspectionsince we want error messages to mention the name of the original functionnot the wrapper finallywe return the wrapper function--it is this function that will be used in place of the original def positive_result(function)@functools wraps(functiondef wrapper(*args**kwargs)result function(*args**kwargsassert result > function __name__ "(result isn' > return result return wrapper here is slightly cleaner version of the @positive_result decorator the wrapper itself is wrapped using the functools module' @functools wraps decoratorwhich ensures that the wrapper(function has the name and docstring of the original function
8,892
advanced programming techniques in some cases it would be useful to be able to parameterize decoratorbut at first sight this does not seem possible since decorator takes just one argumenta function or method but there is neat solution to this we can call function with the parameters we want and that returns decorator which can then decorate the function that follows it for example@bounded( def percent(amounttotal)return (amount total herethe bounded(function is called with two argumentsand returns decorator that is used to decorate the percent(function the purpose of the decorator in this case is to guarantee that the number returned is always in the range to inclusive here' the implementation of the bounded(functiondef bounded(minimummaximum)def decorator(function)@functools wraps(functiondef wrapper(*args**kwargs)result function(*args**kwargsif result minimumreturn minimum elif result maximumreturn maximum return result return wrapper return decorator the function creates decorator functionthat itself creates wrapper function the wrapper performs the calculation and returns result that is within the bounded range the decorator(function returns the wrapper(functionand the bounded(function returns the decorator one further point to note is that each time wrapper is created inside the bounded(functionthe particular wrapper uses the minimum and maximum values that were passed to bounded(the last decorator we will create in this subsection is bit more complex it is logging function that records the nameargumentsand result of any function it is used to decorate for example@logged def discounted_price(pricepercentagemake_integer=false)result price (( percentage if not ( result <price)raise valueerror("invalid price"return result if not make_integer else int(round(result)
8,893
if python is run in debug mode (the normal mode)every time the discounted_price(function is called log message will be added to the file logged log in the machine' local temporary directoryas this log file extract illustratescalleddiscounted_price( - calleddiscounted_price( - calleddiscounted_price( make_integer=true- calleddiscounted_price( true- calleddiscounted_price( - invalid price if python is run in optimized mode (using the - command-line option or if the pythonoptimize environment variable is set to - )then no logging will take place here' the code for setting up logging and for the decoratorif __debug__logger logging getlogger("logger"logger setlevel(logging debughandler logging filehandler(os path jointempfile gettempdir()"logged log")logger addhandler(handlerdef logged(function)@functools wraps(functiondef wrapper(*args**kwargs)log "calledfunction __name__ "(log +"join(["{ ! }format(afor in args["{ ! }={ ! }format(kvfor kv in kwargs items()]result exception none tryresult function(*args**kwargsreturn result except exception as errexception err finallylog +(("-str(result)if exception is none else "{ }{ }format(type(exception)exception)logger debug(logif exception is not noneraise exception return wrapper elsedef logged(function)return function
8,894
advanced programming techniques in debug mode the global variable __debug__ is true if this is the case we set up logging using the logging moduleand then create the @logged decorator the logging module is very powerful and flexible--it can log to filesrotated filesemailsnetwork connectionshttp serversand more here we've used only the most basic facilities by creating logging objectsetting its logging level (several levels are supported)and choosing to use file for the output dictionary comprehensions the wrapper' code begins by setting up the log string with the function' name and arguments we then try calling the function and storing its result if any exception occurs we store it in all cases the finally block is executedand there we add the return value (or exceptionto the log string and write to the log if no exception occurredthe result is returnedotherwisewe reraise the exception to correctly mimic the original function' behavior if python is running in optimized mode__debug__ is falsein this case we define the logged(function to simply return the function it is givenso apart from the tiny overhead of this indirection when the function is first createdthere is no runtime overhead at all note that the standard library' trace and cprofile modules can run and analyse programs and modules to produce various tracing and profiling reports both use introspectionso unlike the @logged decorator we have used hereneither trace nor cprofile requires any source code changes function annotations |functions and methods can be defined with annotations--expressions that can be used in function' signature here' the general syntaxdef functionname(par exp par exp parn expn-rexpsuite every colon expression part (expxis an optional annotationand so is the arrow return expression part (-rexpthe last (or onlypositional parameter (if presentcan be of the form *argswith or without an annotationsimilarlythe last (or onlykeyword parameter (if presentcan be of the form **kwargsagain with or without an annotation if annotations are present they are added to the function' __annotations__ dictionaryif they are not present this dictionary is empty the dictionary' keys are the parameter namesand the values are the corresponding expressions the syntax allows us to annotate allsomeor none of the parameters and to annotate the return value or not annotations have no special significance to python the only thing that python does in the face of annotations is to put them in the __annotations__ dictionaryany other action is up to us here is an example of an annotated function that is in the util module
8,895
def is_unicode_punctuation( str-boolfor in sif unicodedata category( )[ !" "return false return true every unicode character belongs to particular category and each category is identified by two-character identifier all the categories that begin with are punctuation characters here we have used python data types as the annotation expressions but they have no particular meaning for pythonas these calls should make clearutil is_unicode_punctuation("zebr\ "util is_unicode_punctuation( ="!@#?"util is_unicode_punctuation(("!""@")returnsfalse returnstrue returnstrue the first call uses positional argument and the second call keyword argumentjust to show that both kinds work as expected the last call passes tuple rather than stringand this is accepted since python does nothing more than record the annotations in the __annotations__ dictionary if we want to give meaning to annotationsfor exampleto provide type checkingone approach is to decorate the functions we want the meaning to apply to with suitable decorator here is very basic type-checking decoratordef strictly_typed(function)annotations function __annotations__ arg_spec inspect getfullargspec(functionassert "returnin annotations"missing type for return valuefor arg in arg_spec args arg_spec kwonlyargsassert arg in annotations("missing type for parameter 'arg "'"@functools wraps(functiondef wrapper(*args**kwargs)for namearg in (list(zip(arg_spec argsargs)list(kwargs items()))assert isinstance(argannotations[name])"expected argument '{ }of { got { }formatnameannotations[name]type(arg))result function(*args**kwargsassert isinstance(resultannotations["return"])"expected return of { got { }formatannotations["return"]type(result))return result return wrapper
8,896
advanced programming techniques this decorator requires that every argument and the return value must be annotated with the expected type it checks that the function' arguments and return type are all annotated with their types when the function it is passed is createdand at runtime it checks that the types of the actual arguments match those expected the inspect module provides powerful introspection services for objects herewe have made use of only small part of the argument specification object it returnsto get the names of each positional and keyword argument--in the correct order in the case of the positional arguments these names are then used in conjunction with the annotations dictionary to ensure that every parameter and the return value are annotated the wrapper function created inside the decorator begins by iterating over every name-argument pair of the given positional and keyword arguments since zip(returns an iterator and dictionary items(returns dictionary view we cannot concatenate them directlyso first we convert them both to lists if any actual argument has different type from its corresponding annotation the assertion will failotherwisethe actual function is called and the type of the value returned is checkedand if it is of the right typeit is returned at the end of the strictly_typed(functionwe return the wrapped function as usual notice that the checking is done only in debug mode (which is python' default mode--controlled by the - command-line option and the pythonoptimize environment variableif we decorate the is_unicode_punctuation(function with the @strictly_typed decoratorand try the same examples as before using the decorated versionthe annotations are acted uponis_unicode_punctuation("zebr\ "is_unicode_punctuation( ="!@#?"is_unicode_punctuation(("!""@")returnsfalse returnstrue raises assertionerror now the argument types are checkedso in the last case an assertionerror is raised because tuple is not string or subclass of str now we will look at completely different use of annotations here' small function that has the same functionality as the built-in range(functionexcept that it always returns floatsdef range_of_floats(*args-"author=reginald perrin"return (float(xfor in range(*args)no use is made of the annotation by the function itselfbut it is easy to envisage tool that imported all of project' modules and produced list of function names and author namesextracting each function' name from its __name__ attributeand the author names from the value of the __annotations__ dictionary' "returnitem
8,897
annotations are very new feature of pythonand because python does not impose any predefined meaning on themthe uses they can be put to are limited only by our imagination further ideas for possible usesand some useful linksare available from pep "function annotations"www python orgdev/peps/pep- further object-oriented programming ||in this section we will look more deeply into python' support for object orientationlearning many techniques that can reduce the amount of code we must writeand that expand the power and capabilities of the programming features that are available to us but we will begin with one very small and simple new feature here is the start of the definition of point class that has exactly the same behavior as the versions we created in class point__slots__ (" "" "def __init__(selfx= = )self self attribute access functions when class is created without the use of __slots__behind the scenes python creates private dictionary called __dict__ for each instanceand this dictionary holds the instance' data attributes this is why we can add or remove attributes from objects (for examplewe added cache attribute to the get_function(function earlier in this if we only need objects where we access the original attributes and don' need to add or remove attributeswe can create classes that don' have __dict__ this is achieved simply by defining class attribute called __slots__ whose value is tuple of attribute names each object of such class will have attributes of the specified names and no __dict__no attributes can be added or removed from such classes these objects consume less memory and are faster than conventional objectsalthough this is unlikely to make much difference unless large numbers of objects are created if we inherit from class that uses __slots__ we must declare slots in our subclasseven if emptysuch as __slots__ ()or the memory and speed savings will be lost controlling attribute access |it is sometimes convenient to have class where attribute values are computed on the fly rather than stored here' the complete implementation of such class
8,898
advanced programming techniques class orddef __getattr__(selfchar)return ord(charwith the ord class availablewe can create an instanceord ord()and then have an alternative to the built-in ord(function that works for any character that is valid identifier for exampleord returns ord returns and ord returns (but ord and similar are syntax errors note that if we typed the ord class into idle it would not work if we then typed ord ord(this is because the instance has the same name as the built-in ord(function that the ord class usesso the ord(call would actually become call to the ord instance and result in typeerror exception the problem would not arise if we imported module containing the ord class because the interactively created ord object and the built-in ord(function used by the ord class would be in two separate modulesso one would not displace the other if we really need to create class interactively and to reuse the name of built-in we can do so by ensuring that the class calls the built-in--in this case by importing the builtins module which provides unambiguous access to all the built-in functionsand calling builtins ord(rather than plain ord(here' another tiny yet complete class this one allows us to create "constantsit isn' difficult to change the values behind the class' backbut it can at least prevent simple mistakes class constdef __setattr__(selfnamevalue)if name in self __dict__raise valueerror("cannot change const attribute"self __dict__[namevalue def __delattr__(selfname)if name in self __dict__raise valueerror("cannot delete const attribute"raise attributeerror("'{ }object has no attribute '{ }'format(self __class__ __name__name)with this class we can create constant objectsayconst const()and set any attributes we like on itfor exampleconst limit but once an attribute' value has been setalthough it can be read as often as we likeany attempt to change or delete it will result in valueerror exception being raised we have not reimplemented __getattr__(because the base class object __getattr__(method does what we want--returns the given attribute' value or raises an attributeerror exception if there is no such attribute in the __delattr__(method we mimic the __getattr__(method' error message for nonexistent attributesand to do this we must get the name of the class we are in as well as
8,899
table attribute access special methods special method usage __delattr__(selfnamedel deletes object ' attribute __dir__(selfdir(x__getattr__(selfname__getattribute__(selfnamedescription returns list of ' attribute names returns the value of object ' attribute if it isn' found directly returns the value of object ' attributesee text __setattr__(selfnamevaluex sets object ' attribute' value to the name of the nonexistent attribute the class works because we are using the object' __dict__ which is what the base class __getattr__()__setattr__()and __delattr__(methods usealthough here we have used only the base class' __getattr__(method all the special methods used for attribute access are listed in table there is another way of getting constantswe can use named tuples here are couple of examplesconst collections namedtuple(" ""min max")( const minconst max returns( offset collections namedtuple(" ""id name description")(*range( )offset idoffset nameoffset description returns( in both cases we have just used throwaway name for the named tuple because we want just one named tuple instance each timenot tuple subclass for creating instances of named tuple although python does not support an enum data typewe can use named tuples as we have done here to get similar effect image py for our last look at attribute access special methods we will return to an example we first saw in in that we created an image class whose widthheightand background color are fixed when an image is created (although they are changed if an image is loadedwe provided access to them using read-only properties for examplewe had@property def width(self)return self __width this is easy to code but could become tedious if there are lot of read-only properties here is different solution that handles all the image class' read-only properties in single method