id
int64
0
25.6k
text
stringlengths
0
4.59k
3,400
the first line inside the function uses list comprehension to turn the characters list into list of tuples list comprehensions are an importantnon-object-oriented tool in pythonwe'll be covering them in detail in the next then we loop over each of the characters in the sentence we first look up the index of the character in the characters listwhich we know has the same index in our frequencies listsince we just created the second list from the first we then update that index in the frequencies list by creating new tuplediscarding the original one aside from the garbage collection and memory waste concernsthis is rather difficult to readlike dictionarieslists are objects tooand they have several methods that can be invoked upon them here are some common onesthe append(elementmethod adds an element to the end of the list the insert(indexelementmethod inserts an item at specific position the count(elementmethod tells us how many times an element appears in the list the index()method tells us the index of an item in the listraising an exception if it can' find it the find()method does the same thingbut returns - instead of raising an exception for missing items the reverse(method does exactly what it says--turns the list around the sort(method has some rather intricate object-oriented behaviorswhich we'll cover now sorting lists without any parameterssort will generally do the expected thing if it' list of stringsit will place them in alphabetical order this operation is case sensitiveso all capital letters will be sorted before lowercase lettersthat is comes before if it is list of numbersthey will be sorted in numerical order if list of tuples is providedthe list is sorted by the first element in each tuple if mixture containing unsortable items is suppliedthe sort will raise typeerror exception
3,401
if we want to place objects we define ourselves into list and make those objects sortablewe have to do bit more work the special method __lt__which stands for "less than"should be defined on the class to make instances of that class comparable the sort method on list will access this method on each object to determine where it goes in the list this method should return true if our class is somehow less than the passed parameterand false otherwise here' rather silly class that can be sorted based on either string or numberclass weirdsorteedef __init__(selfstringnumbersort_num)self string string self number number self sort_num sort_num def __lt__(selfobject)if self sort_numreturn self number object number return self string object string def __repr__(self)return"{}:{}format(self stringself numberthe __repr__ method makes it easy to see the two values when we print list the __lt__ method' implementation compares the object to another instance of the same class (or any duck typed object that has stringnumberand sort_num attributesit will fail if those attributes are missingthe following output illustrates this class in actionwhen it comes to sortinga weirdsortee(' ' trueb weirdsortee(' ' truec weirdsortee(' ' trued weirdsortee(' ' truel [ , , ,dl [ : : : : sort( [ : : : :
3,402
for in li sort_num false sort( [ : : : : the first time we call sortit sorts by numbers because sort_num is true on all the objects being compared the second timeit sorts by letters the __lt__ method is the only one we need to implement to enable sorting technicallyhoweverif it is implementedthe class should normally also implement the similar __gt____ eq____ne____ge__and __le__ methods so that all of the ==!=>=and <operators also work properly you can get this for free by implementing __lt__ and __eq__and then applying the @total_ordering class decorator to supply the restfrom functools import total_ordering @total_ordering class weirdsorteedef __init__(selfstringnumbersort_num)self string string self number number self sort_num sort_num def __lt__(selfobject)if self sort_numreturn self number object number return self string object string def __repr__(self)return"{}:{}format(self stringself numberdef __eq__(selfobject)return all(self string =object stringself number =object numberself sort_num =object number )
3,403
this is useful if we want to be able to use operators on our objects howeverif all we want to do is customize our sort orderseven this is overkill for such use casethe sort method can take an optional key argument this argument is function that can translate each object in list into an object that can somehow be compared for examplewe can use str lower as the key argument to perform case-insensitive sort on list of stringsl ["hello""help""helo" sort( ['help''helo''hello' sort(key=str lowerl ['hello''helo''help'remembereven though lower is method on string objectsit is also function that can accept single argumentself in other wordsstr lower(itemis equivalent to item lower(when we pass this function as keyit performs the comparison on lowercase values instead of doing the default case-sensitive comparison there are few sort key operations that are so common that the python team has supplied them so you don' have to write them yourself for exampleit is often common to sort list of tuples by something other than the first item in the list the operator itemgetter method can be used as key to do thisfrom operator import itemgetter [(' ' )(' ' )(' ' )(' ' )(' ' )(' ' ) sort(key=itemgetter( ) [(' ' )(' ' )(' ' )(' ' )(' ' )(' ' )the itemgetter function is the most commonly used one (it works if the objects are dictionariestoo)but you will sometimes find use for attrgetter and methodcallerwhich return attributes on an object and the results of method calls on objects for the same purpose see the operator module documentation for more information
3,404
sets lists are extremely versatile tools that suit most container object applications but they are not useful when we want to ensure objects in the list are unique for examplea song library may contain many songs by the same artist if we want to sort through the library and create list of all the artistswe would have to check the list to see if we've added the artist alreadybefore we add them again this is where sets come in sets come from mathematicswhere they represent an unordered group of (usuallyunique numbers we can add number to set five timesbut it will show up in the set only once in pythonsets can hold any hashable objectnot just numbers hashable objects are the same objects that can be used as keys in dictionariesso againlists and dictionaries are out like mathematical setsthey can store only one copy of each object so if we're trying to create list of song artistswe can create set of string names and simply add them to the set this example starts with list of (songartisttuples and creates set of the artistssong_library [("phantom of the opera""sarah brightman")("knocking on heaven' door""guns nroses")("captain nemo""sarah brightman")("patterns in the ivy""opeth")("november rain""guns nroses")("beautiful""sarah brightman")("mal' song""vixy and tony")artists set(for songartist in song_libraryartists add(artistprint(artiststhere is no built-in syntax for an empty set as there is for lists and dictionarieswe create set using the set(constructor howeverwe can use the curly braces (borrowed from dictionary syntaxto create setso long as the set contains values if we use colons to separate pairs of valuesit' dictionaryas in {'key''value''key ''value 'if we just separate values with commasit' setas in {'value''value 'items can be added individually to the set using its add method if we run this scriptwe see that the set works as advertised{'sarah brightman'"guns nroses"'vixy and tony''opeth'
3,405
if you're paying attention to the outputyou'll notice that the items are not printed in the order they were added to the sets setslike dictionariesare unordered they both use an underlying hash-based data structure for efficiency because they are unorderedsets cannot have items looked up by index the primary purpose of set is to divide the world into two groups"things that are in the set"and"things that are not in the setit is easy to check whether an item is in the set or to loop over the items in setbut if we want to sort or order themwe'll have to convert the set to list this output shows all three of these activities"opethin artists true for artist in artistsprint("{plays good musicformat(artist)sarah brightman plays good music guns nroses plays good music vixy and tony play good music opeth plays good music alphabetical list(artistsalphabetical sort(alphabetical ["guns nroses"'opeth''sarah brightman''vixy and tony'while the primary feature of set is uniquenessthat is not its primary purpose sets are most useful when two or more of them are used in combination most of the methods on the set type operate on other setsallowing us to efficiently combine or compare the items in two or more sets these methods have strange namessince they use the same terminology used in mathematics we'll start with three methods that return the same resultregardless of which is the calling set and which is the called set the union method is the most common and easiest to understand it takes second set as parameter and returns new set that contains all elements that are in either of the two setsif an element is in both original setsit willof courseonly show up once in the new set union is like logical or operationindeedthe operator can be used on two sets to perform the union operationif you don' like calling methods
3,406
converselythe intersection method accepts second set and returns new set that contains only those elements that are in both sets it is like logical and operationand can also be referenced using the operator finallythe symmetric_difference method tells us what' leftit is the set of objects that are in one set or the otherbut not both the following example illustrates these methods by comparing some artists from my song library to those in my sister'smy_artists {"sarah brightman""guns nroses""opeth""vixy and tony"auburns_artists {"nickelback""guns nroses""savage garden"print("all{}format(my_artists union(auburns_artists))print("both{}format(auburns_artists intersection(my_artists))print("either but not both{}formatmy_artists symmetric_difference(auburns_artists))if we run this codewe see that these three methods do what the print statements suggest they will doall{'sarah brightman'"guns nroses"'vixy and tony''savage garden''opeth''nickelback'both{"guns nroses"either but not both{'savage garden''opeth''nickelback''sarah brightman''vixy and tony'these methods all return the same resultregardless of which set calls the other we can say my_artists union(auburns_artistsor auburns_artists union(my_artistsand get the same result there are also methods that return different results depending on who is the caller and who is the argument these methods include issubset and issupersetwhich are the inverse of each other both return bool the issubset method returns trueif all of the items in the calling set are also in the set passed as an argument the issuperset method returns true if all of the items in the argument are also in the calling set thus issubset(tand issuperset(sare identical they will both return true if contains all the elements in
3,407
finallythe difference method returns all the elements that are in the calling setbut not in the set passed as an argumentthis is like half symmetric_difference the difference method can also be represented by the operator the following code illustrates these methods in actionmy_artists {"sarah brightman""guns nroses""opeth""vixy and tony"bands {"guns nroses""opeth"print("my_artists is to bands:"print("issuperset{}format(my_artists issuperset(bands))print("issubset{}format(my_artists issubset(bands))print("difference{}format(my_artists difference(bands))print("*"* print("bands is to my_artists:"print("issuperset{}format(bands issuperset(my_artists))print("issubset{}format(bands issubset(my_artists))print("difference{}format(bands difference(my_artists))this code simply prints out the response of each method when called from one set on the other running it gives us the following outputmy_artists is to bandsissupersettrue issubsetfalse difference{'sarah brightman''vixy and tony'*******************bands is to my_artistsissupersetfalse issubsettrue differenceset(the difference methodin the second casereturns an empty setsince there are no items in bands that are not in my_artists the unionintersectionand difference methods can all take multiple sets as argumentsthey will returnas we might expectthe set that is created when the operation is called on all the parameters
3,408
so the methods on sets clearly suggest that sets are meant to operate on other setsand that they are not just containers if we have data coming in from two different sources and need to quickly combine them in some wayto determine where the data overlaps or is differentwe can use set operations to efficiently compare them or if we have data incoming that may contain duplicates of data that has already been processedwe can use sets to compare the two and process only the new data finallyit is valuable to know that sets are much more efficient than lists when checking for membership using the in keyword if you use the syntax value in container on set or listit will return true if one of the elements in container is equal to value and false otherwise howeverin listit will look at every object in the container until it finds the valuewhereas in setit simply hashes the value and checks for membership this means that set will find the value in the same amount of time no matter how big the container isbut list will take longer and longer to search for value as the list contains more and more values extending built-ins we discussed briefly in when objects are alikehow built-in data types can be extended using inheritance nowwe'll go into more detail as to when we would want to do that when we have built-in container object that we want to add functionality towe have two options we can either create new objectwhich holds that container as an attribute (composition)or we can subclass the built-in object and add or adapt methods on it to do what we want (inheritancecomposition is usually the best alternative if all we want to do is use the container to store some objects using that container' features that wayit' easy to pass that data structure into other methods and they will know how to interact with it but we need to use inheritance if we want to change the way the container actually works for exampleif we want to ensure every item in list is string with exactly five characterswe need to extend list and override the append(method to raise an exception for invalid input we' also minimally have to override __setitem__ (selfindexvalue) special method on lists that is called whenever we use the [index"valuesyntaxand the extend(method
3,409
yeslists are objects all that special non-object-oriented looking syntax we've been looking at for accessing lists or dictionary keyslooping over containersand similar tasks is actually "syntactic sugarthat maps to an object-oriented paradigm underneath we might ask the python designers why they did this isn' object-oriented programming always betterthat question is easy to answer in the following hypothetical exampleswhich is easier to readas programmerwhich requires less typingc add(bl[ setitem( [keyvalue setitem(keyvaluefor in alist#do something with it alist iterator(while it has_next() it next(#do something with the highlighted sections show what object-oriented code might look like (in practicethese methods actually exist as special double-underscore methods on associated objectspython programmers agree that the non-object-oriented syntax is easier both to read and to write yet all of the preceding python syntaxes map to objectoriented methods underneath the hood these methods have special names (with double-underscores before and afterto remind us that there is better syntax out there howeverit gives us the means to override these behaviors for examplewe can make special integer that always returns when we add two of them togetherclass sillyint(int)def __add__(selfnum)return this is an extremely bizarre thing to dograntedbut it perfectly illustrates these object-oriented principles in actiona sillyint( sillyint(
3,410
the awesome thing about the __add__ method is that we can add it to any class we writeand if we use the operator on instances of that classit will be called this is how stringtupleand list concatenation worksfor example this is true of all the special methods if we want to use in myobj syntax for custom-defined objectwe can implement __contains__ if we want to use myobj[ivalue syntaxwe supply __setitem__ method and if we want to use something myobj[ ]we implement __getitem__ there are of these special methods on the list class we can use the dir function to see all of themdir(list['__add__''__class__''__contains__''__delattr__','__delitem__''__doc__''__eq__''__format__''__ge__''__getattribute__''__ getitem__''__gt__''__hash__''__iadd__''__imul__''__init__''__iter__''__le__''__len__''__lt__''__mul__''__ne__''__ new__''__reduce__''__reduce_ex__''__repr__''__reversed__''__rmul__''__setattr__''__setitem__''__sizeof__''__str__''__ subclasshook__''append''count''extend''index''insert''pop''remove''reverse''sortfurtherif we desire additional information on how any of these methods workswe can use the help functionhelp(list __add__help on wrapper_descriptor__add__(selfvalue/return self+value the plus operator on lists concatenates two lists we don' have room to discuss all of the available special functions in this bookbut you are now able to explore all this functionality with dir and help the official online python reference (docs python org/ /has plenty of useful information as well focusespeciallyon the abstract base classes discussed in the collections module soto get back to the earlier point about when we would want to use composition versus inheritanceif we need to somehow change any of the methods on the class-including the special methods--we definitely need to use inheritance if we used compositionwe could write methods that do the validation or alterations and ask the caller to use those methodsbut there is nothing stopping them from accessing the property directly they could insert an item into our list that does not have five charactersand that might confuse other methods in the list
3,411
oftenthe need to extend built-in data type is an indication that we're using the wrong sort of data type it is not always the casebut if we are looking to extend built-inwe should carefully consider whether or not different data structure would be more suitable for exampleconsider what it takes to create dictionary that remembers the order in which keys were inserted one way to do this is to keep an ordered list of keys that is stored in specially derived subclass of dict then we can override the methods keysvalues__iter__and items to return everything in order of coursewe'll also have to override __setitem__ and setdefault to keep our list up to date there are likely to be few other methods in the output of dir(dictthat need overriding to keep the list and dictionary consistent (clear and __delitem__ come to mindto track when items are removed)but we won' worry about them for this example so we'll be extending dict and adding list of ordered keys trivial enoughbut where do we create the actual listwe could include it in the __init__ methodwhich would work just finebut we have no guarantees that any subclass will call that initializer remember the __new__ method we discussed in objects in pythoni said it was generally only useful in very special cases this is one of those special cases we know __new__ will be called exactly onceand we can create list on the new instance that will always be available to our class with that in mindhere is our entire sorted dictionaryfrom collections import keysviewitemsviewvaluesview class dictsorted(dict)def __new__(*args**kwargs)new_dict dict __new__(*args**kwargsnew_dict ordered_keys [return new_dict def __setitem__(selfkeyvalue)'''self[keyvalue syntax''if key not in self ordered_keysself ordered_keys append(keysuper(__setitem__(keyvaluedef setdefault(selfkeyvalue)if key not in self ordered_keysself ordered_keys append(keyreturn super(setdefault(keyvaluedef keys(self)return keysview(selfdef values(self)
3,412
return valuesview(selfdef items(self)return itemsview(selfdef __iter__(self)'''for in self syntax''return self ordered_keys __iter__(the __new__ method creates new dictionary and then puts an empty list on that object we don' override __init__as the default implementation works (actuallythis is only true if we initialize an empty dictsorted objectwhich is standard behavior if we want to support other variations of the dict constructorwhich accept dictionaries or lists of tupleswe' need to fix __init__ to also update our ordered_ keys listthe two methods for setting items are very similarthey both update the list of keysbut only if the item hasn' been added before we don' want duplicates in the listbut we can' use set hereit' unorderedthe keysitemsand values methods all return views onto the dictionary the collections library provides three read-only view objects onto the dictionarythey use the __iter__ method to loop over the keysand then use __getitem__ (which we didn' need to overrideto retrieve the values sowe only need to define our custom __iter__ method to make these three views work you would think the superclass would create these views properly using polymorphismbut if we don' override these three methodsthey don' return properly ordered views finallythe __iter__ method is the really special oneit ensures that if we loop over the dictionary' keys (using for in syntax)it will return the values in the correct order it does this by returning the __iter__ of the ordered_keys listwhich returns the same iterator object that would be used if we used for in on the list instead since ordered_keys is list of all available keys (due to the way we overrode other methods)this is the correct iterator object for the dictionary as well let' look at few of these methods in actioncompared to normal dictionaryds dictsorted( {ds[' ' ds[' ' ds setdefault(' ' [' ' [' ' setdefault(' '
3,413
for , in ds items()print( ,va for , in items()print( ,va ahour dictionary is sorted and the normal dictionary is not hurrayif you wanted to use this class in productionyou' have to override several other special methods to ensure the keys are up to date in all cases howeveryou don' need to do thisthe functionality this class provides is already available in pythonusing the ordereddict object in the collections module try importing the class from collectionsand use help(ordereddictto find out more about it queues queues are peculiar data structures becauselike setstheir functionality can be handled entirely using lists howeverwhile lists are extremely versatile general-purpose toolsthey are occasionally not the most efficient data structure for container operations if your program is using small dataset (up to hundreds or even thousands of elements on today' processors)then lists will probably cover all your use cases howeverif you need to scale your data into the millionsyou may need more efficient container for your particular use case python therefore provides three types of queue data structuresdepending on what kind of access you are looking for all three utilize the same apibut differ in both behavior and data structure before we start our queueshoweverconsider the trusty list data structure python lists are the most advantageous data structure for many use casesthey support efficient random access to any element in the list
3,414
they have strict ordering of elements they support the append operation efficiently they tend to be slowhoweverif you are inserting elements anywhere but the end of the list (especially so if it' the beginning of the listas we discussed in the section on setsthey are also slow for checking if an element exists in the listand by extensionsearching storing data in sorted order or reordering the data can also be inefficient let' look at the three types of containers provided by the python queue module fifo queues fifo stands for first in first out and represents the most commonly understood definition of the word "queueimagine line of people standing in line at bank or cash register the first person to enter the line gets served firstthe second person in line gets served secondand if new person desires servicethey join the end of the line and wait their turn the python queue class is just like that it is typically used as sort of communication medium when one or more objects is producing data and one or more other objects is consuming the data in some wayprobably at different rate think of messaging application that is receiving messages from the networkbut can only display one message at time to the user the other messages can be buffered in queue in the order they are received fifo queues are utilized lot in such concurrent applications (we'll talk more about concurrency in testing object-oriented programs the queue class is good choice when you don' need to access any data inside the data structure except the next object to be consumed using list for this would be less efficient because under the hoodinserting data at (or removing fromthe beginning of list can require shifting every other element in the list queues have very simple api queue can have "infinite(until the computer runs out of memorycapacitybut it is more commonly bounded to some maximum size the primary methods are put(and get()which add an element to the back of the lineas it wereand retrieve them from the frontin order both of these methods accept optional arguments to govern what happens if the operation cannot successfully complete because the queue is either empty (can' getor full (can' putthe default behavior is to block or idly wait until the queue object has data or room available to complete the operation you can have it raise exceptions instead by passing the block=false parameter or you can have it wait defined amount of time before raising an exception by passing timeout parameter
3,415
the class also has methods to check whether the queue is full(or empty(and there are few additional methods to deal with concurrent access that we won' discuss here here is interactive session demonstrating these principlesfrom queue import queue lineup queue(maxsize= lineup get(block=falsetraceback (most recent call last)file ""line in lineup get(block=falsefile "/usr/lib /python /queue py"line in get raise empty queue empty lineup put("one"lineup put("two"lineup put("three"lineup put("four"timeout= traceback (most recent call last)file ""line in lineup put("four"timeout= file "/usr/lib /python /queue py"line in put raise full queue full lineup full(true lineup get('onelineup get('twolineup get('threelineup empty(true
3,416
underneath the hoodpython implements queues on top of the collections deque data structure deques are advanced data structures that permits efficient access to both ends of the collection it provides more flexible interface than is exposed by queue refer you to the python documentation if you' like to experiment more with it lifo queues lifo (last in first outqueues are more frequently called stacks think of stack of papers where you can only access the top-most paper you can put another paper on top of the stackmaking it the new top-most paperor you can take the top-most paper away to reveal the one beneath it traditionallythe operations on stacks are named push and popbut the python queue module uses the exact same api as for fifo queuesput(and get(howeverin lifo queuethese methods operate on the "topof the stack instead of at the front and back of line this is an excellent example of polymorphism if you look at the queue source code in the python standard libraryyou'll actually see that there is superclass with subclasses for fifo and lifo queues that implement the few operations (operating on the top of stack instead of front and back of deque instancethat are critically different between the two here' an example of the lifo queue in actionfrom queue import lifoqueue stack lifoqueue(maxsize= stack put("one"stack put("two"stack put("three"stack put("four"block=falsetraceback (most recent call last)file ""line in stack put("four"block=falsefile "/usr/lib /python /queue py"line in put raise full queue full stack get('threestack get(
3,417
'twostack get('onestack empty(true stack get(timeout= traceback (most recent call last)file ""line in stack get(timeout= file "/usr/lib /python /queue py"line in get raise empty queue empty you might wonder why you couldn' just use the append(and pop(methods on standard list quite franklythat' probably what would do rarely have occasion to use the lifoqueue class in production code working with the end of list is an efficient operationso efficientin factthat the lifoqueue uses standard list under the hoodthere are couple of reasons that you might want to use lifoqueue instead of list the most important one is that lifoqueue supports clean concurrent access from multiple threads if you need stack-like behavior in concurrent settingyou should leave the list at home secondlifoqueue enforces the stack interface you can' unwittingly insert value to the wrong position in lifoqueuefor example (althoughas an exerciseyou can work out how to do this completely wittinglypriority queues the priority queue enforces very different style of ordering from the previous queue implementations once againthey follow the exact same get(and put(apibut instead of relying on the order that items arrive to determine when they should be returnedthe most "importantitem is returned by conventionthe most importantor highest priority item is the one that sorts lowest using the less than operator common convention is to store tuples in the priority queuewhere the first element in the tuple is the priority for that elementand the second element is the data another common paradigm is to implement the __lt__ methodas we discussed earlier in this it is perfectly acceptable to have multiple elements with the same priority in the queuealthough there are no guarantees on which one will be returned first
3,418
priority queue might be usedfor exampleby search engine to ensure it refreshes the content of the most popular web pages before crawling sites that are less likely to be searched for product recommendation tool might use one to display information about the most highly ranked products while still loading data for the lower ranks note that priority queue will always return the most important element currently in the queue the get(method will block (by defaultif the queue is emptybut it will not block and wait for higher priority element to be added if there is already something in the queue the queue knows nothing about elements that have not been added yet (or even about elements that have been previously extracted)and only makes decisions based on the current contents of the queue this interactive session shows priority queue in actionusing tuples as weights to determine what order items are processed inheap put(( "three")heap put(( "four")heap put(( "one"heap put(( "two")heap put(( "five")block=falsetraceback (most recent call last)file ""line in heap put(( "five")block=falsefile "/usr/lib /python /queue py"line in put raise full full while not heap empty()print(heap get()( 'one'( 'two'( 'three'( 'four'priority queues are almost universally implemented using the heap data structure python' implementation utilizes the heapq module to effectively store heap inside normal list direct you to an algorithm and data-structure' textbook for more information on heapsnot to mention many other fascinating structures we haven' covered here no matter what the data structureyou can use object-oriented principles to wrap relevant algorithms (behaviors)such as those supplied in the heapq modulearound the data they are structuring in the computer' memoryjust as the queue module has done on our behalf in the standard library
3,419
case study to tie everything togetherwe'll be writing simple link collectorwhich will visit website and collect every link on every page it finds in that site before we startthoughwe'll need some test data to work with simply write some html files to work with that contain links to each other and to other sites on the internetsomething like thiscontact us blog my dog some hobbies contact again name one of the files index html so it shows up first when pages are served make sure the other files existand keep things complicated so there is lots of linking between them the examples for this include directory called case_study_serve (one of the lamest personal websites in existence!if you would rather not set them up yourself nowstart simple web server by entering the directory containing all these files and run the following commandpython - http server this will start server running on port you can see the pages you made by visiting doubt anyone can get website up and running with less worknever let it be said"you can' do that easily with python the goal will be to pass our collector the base url for the site (in this caselocalhost: /)and have it create list containing every unique link on the site we'll need to take into account three types of urls (links to external siteswhich start with relative linksfor everything elsewe also need to be aware that pages may link to each other in loopwe need to be sure we don' process the same page multiple timesor it may never end with all this uniqueness going onit sounds like we're going to need some sets
3,420
before we get into thatlet' start with the basics what code do we need to connect to page and parse all the links from that pagefrom urllib request import urlopen from urllib parse import urlparse import re import sys link_regex re compile"]*href=['\"]([^'\"]+)['\"][^>]*>"class linkcollectordef __init__(selfurl)self url "urlparse(urlnetloc def collect_links(selfpath="/")full_url self url path page str(urlopen(full_urlread()links link_regex findall(pageprint(linksif __name__ ="__main__"linkcollector(sys argv[ ]collect_links(this is short piece of codeconsidering what it' doing it connects to the server in the argument passed on the command linedownloads the pageand extracts all the links on that page the __init__ method uses the urlparse function to extract just the hostname from the urlso even if we pass in htmlit will still operate on the top level of the host makes sensebecause we want to collect all the links on the sitealthough it assumes every page is connected to the index by some sequence of links the collect_links method connects to and downloads the specified page from the serverand uses regular expression to find all the links in the page regular expressions are an extremely powerful string processing tool unfortunatelythey have steep learning curveif you haven' used them beforei strongly recommend studying any of the entire books or websites on the topic if you don' think they're worth knowingtry writing the preceding code without them and you'll change your mind the example also stops in the middle of the collect_links method to print the value of links this is common way to test program as we're writing itstop and output the value to ensure it is the value we expect here' what it outputs for our example['contact html''blog html''esme html''/hobbies html''/contact html''
3,421
so now we have collection of all the links in the first page what can we do with itwe can' just pop the links into set to remove duplicates because links may be relative or absolute for examplecontact html and /contact html point to the same page so the first thing we should do is normalize all the links to their full urlincluding hostname and relative path we can do this by adding normalize_url method to our objectdef normalize_url(selfpathlink)if link startswith("return link elif link startswith("/")return self url link elsereturn self url path rpartition'/')[ '/link this method converts each url to complete address that includes protocol and hostname now the two contact pages have the same value and we can store them in set we'll have to modify __init__ to create the setand collect_links to put all the links into it thenwe'll have to visit all the non-external links and collect them too but wait minuteif we do thishow do we keep from revisiting link when we encounter the same page twiceit looks like we're actually going to need two setsa set of collected linksand set of visited links this suggests that we were wise to choose set to represent our datawe know that sets are most useful when we're manipulating more than one of them let' set these upclass linkcollectordef __init__(selfurl)self url "self collected_links set(self visited_links set(def collect_links(selfpath="/")full_url self url path self visited_links add(full_urlpage str(urlopen(full_urlread()links link_regex findall(pagelinks {self normalize_url(pathlink for link in linksself collected_links links unionself collected_linksunvisited_links links differenceself visited_links
3,422
print(linksself visited_linksself collected_linksunvisited_linksthe line that creates the normalized list of links uses set comprehensionno different from list comprehensionexcept that the result is set of values we'll be covering these in detail in the next once againthe method stops to print out the current valuesso we can verify that we don' have our sets confusedand that difference really was the method we wanted to call to collect unvisited_links we can then add few lines of code that loop over all the unvisited links and add them to the collection as wellfor link in unvisited_linksif link startswith(self url)self collect_links(urlparse(linkpaththe if statement ensures that we are only collecting links from the one websitewe don' want to go off and collect all the links from all the pages on the internet (unless we're google or the internet archive!if we modify the main code at the bottom of the program to output the collected linkswe can see it seems to have collected them allif __name__ ="__main__"collector linkcollector(sys argv[ ]collector collect_links(for link in collector collected_linksprint(linkit displays all the links we've collectedand only onceeven though many of the pages in my example linked to each other multiple timespython link_collector py
3,423
even though it collected links to external pagesit didn' go off collecting links from any of the external pages we linked to this is great little program if we want to collect all the links in site but it doesn' give me all the information might need to build site mapit tells me which pages havebut it doesn' tell me which pages link to other pages if we want to do that insteadwe're going to have to make some modifications the first thing we should do is look at our data structures the set of collected links doesn' work anymorewe want to know which links were linked to from which pages the first thing we could dothenis turn that set into dictionary of sets for each page we visit the dictionary keys will represent the exact same data that is currently in the set the values will be sets of all the links on that page here are the changesfrom urllib request import urlopen from urllib parse import urlparse import re import sys link_regex re compile"]*href=['\"]([^'\"]+)['\"][^>]*>"class linkcollectordef __init__(selfurl)self url "self collected_links {self visited_links set(def collect_links(selfpath="/")full_url self url path self visited_links add(full_urlpage str(urlopen(full_urlread()links link_regex findall(pagelinks {self normalize_url(pathlink for link in linksself collected_links[full_urllinks for link in linksself collected_links setdefault(linkset()unvisited_links links differenceself visited_linksfor link in unvisited_linksif link startswith(self url)self collect_links(urlparse(linkpathdef normalize_url(selfpathlink)if link startswith("
3,424
return link elif link startswith("/")return self url link elsereturn self url path rpartition('/)[ '/link if __name__ ="__main__"collector linkcollector(sys argv[ ]collector collect_links(for linkitem in collector collected_links items()print("{}{}format(linkitem)it is surprisingly small changethe line that originally created union of two sets has been replaced with three lines that update the dictionary the first of these simply tells the dictionary what the collected links for that page are the second creates an empty set for any items in the dictionary that have not already been added to the dictionaryusing setdefault the result is dictionary that contains all the links as its keysmapped to sets of links for all the internal linksand empty sets for the external links finallyinstead of recursively calling collect_linkswe can use queue to store the links that haven' been processed yet this implementation won' support itbut this would be good first step to creating multithreaded version that makes multiple requests in parallel to save time from urllib request import urlopen from urllib parse import urlparse import re import sys from queue import queue link_regex re compile("]*href=['\"]([^'\"]+)['\"][^>]*>"class linkcollectordef __init__(selfurl)self url "self collected_links {self visited_links set(def collect_links(self)queue queue(queue put(self urlwhile not queue empty()url queue get(rstrip('/'self visited_links add(urlpage str(urlopen(urlread()
3,425
links link_regex findall(pagelinks self normalize_url(urlparse(urlpathlinkfor link in links self collected_links[urllinks for link in linksself collected_links setdefault(linkset()unvisited_links links difference(self visited_linksfor link in unvisited_linksif link startswith(self url)queue put(linkdef normalize_url(selfpathlink)if link startswith("return link rstrip('/'elif link startswith("/")return self url link rstrip('/'elsereturn self url path rpartition('/')[ '/link rstrip('/'if __name__ ="__main__"collector linkcollector(sys argv[ ]collector collect_links(for linkitem in collector collected_links items()print("% % (linkitem) had to manually strip any trailing forward slashes in the normalize_url method to remove duplicates in this version of the code because the end result is an unsorted dictionarythere is no restriction on what order the links should be processed in thereforewe could just as easily have used lifoqueue instead of queue here priority queue probably wouldn' make lot of sense since there is no obvious priority to attach to link in this case exercises the best way to learn how to choose the correct data structure is to do it wrong few times take some code you've recently writtenor write some new code that uses list try rewriting it using some different data structures which ones make more sensewhich ones don'twhich have the most elegant code
3,426
try this with few different pairs of data structures you can look at examples you've done for previous exercises are there objects with methods where you could have used namedtuple or dict insteadattempt both and see are there dictionaries that could have been sets because you don' really access the valuesdo you have lists that check for duplicateswould set sufficeor maybe several setswould one of the queue implementations be more efficientis it useful to restrict the api to the top of stack rather than allowing random access to the listif you want some specific examples to work withtry adapting the link collector to also save the title used for each link perhaps you can generate site map in html that lists all the pages on the siteand contains list of links to other pagesnamed with the same link titles have you written any container objects recently that you could improve by inheriting built-in and overriding some of the "specialdouble-underscore methodsyou may have to do some research (using dir and helpor the python library referenceto find out which methods need overriding are you sure inheritance is the correct tool to applycould composition-based solution be more effectivetry both (if it' possiblebefore you decide try to find different situations where each method is better than the other if you were familiar with the various python data structures and their uses before you started this you may have been bored but if that is the casethere' good chance you use data structures too muchlook at some of your old code and rewrite it to use more self-made objects carefully consider the alternatives and try them all outwhich one makes for the most readable and maintainable systemalways critically evaluate your code and design decisions make habit of reviewing old code and take note if your understanding of "good designhas changed since you've written it software design has large aesthetic componentand like artists with oil on canvaswe all have to find the style that suits us best summary we've covered several built-in data structures and attempted to understand how to choose one for specific applications sometimesthe best thing we can do is create new class of objectsbut oftenone of the built-ins provides exactly what we need when it doesn'twe can always use inheritance or composition to adapt them to our use cases we can even override special methods to completely change the behavior of built-in syntaxes in the next we'll discuss how to integrate the object-oriented and not-so-objectoriented aspects of python along the waywe'll discover that it' more object-oriented than it looks at first sight
3,427
shortcuts there are many aspects of python that appear more reminiscent of structural or functional programming than object-oriented programming although object-oriented programming has been the most visible paradigm of the past two decadesthe old models have seen recent resurgence as with python' data structuresmost of these tools are syntactic sugar over an underlying object-oriented implementationwe can think of them as further abstraction layer built on top of the (already abstractedobject-oriented paradigm in this we'll be covering grab bag of python features that are not strictly object-orientedbuilt-in functions that take care of common tasks in one call file / and context managers an alternative to method overloading functions as objects python built-in functions there are numerous functions in python that perform task or calculate result on certain types of objects without being methods on the underlying class they usually abstract common calculations that apply to multiple types of classes this is duck typing at its bestthese functions accept objects that have certain attributes or methodsand are able to perform generic operations using those methods manybut not allof these are special double underscore methods we've used many of the built-in functions alreadybut let' quickly go through the important ones and pick up few neat tricks along the way
3,428
the len(function the simplest example is the len(functionwhich counts the number of items in some kind of container objectsuch as dictionary or list you've seen it beforelen([ , , , ] why don' these objects have length property instead of having to call function on themtechnicallythey do most objects that len(will apply to have method called __len__(that returns the same value so len(myobjseems to call myobj __len__(why should we use the len(function instead of the __len__ methodobviously __len__ is special double-underscore methodsuggesting that we shouldn' call it directly there must be an explanation for this the python developers don' make such design decisions lightly the main reason is efficiency when we call __len__ on an objectthe object has to look the method up in its namespaceandif the special __getattribute__ method (which is called every time an attribute or method on an object is accessedis defined on that objectit has to be called as well further__getattribute__ for that particular method may have been written to do something nastylike refusing to give us access to special methods such as __len__the len(function doesn' encounter any of this it actually calls the __len__ function on the underlying classso len(myobjmaps to myobj __len__(myobjanother reason is maintainability in the futurethe python developers may want to change len(so that it can calculate the length of objects that don' have __len__for exampleby counting the number of items returned in an iterator they'll only have to change one function instead of countless __len__ methods across the board there is one other extremely important and often overlooked reason for len(being an external functionbackwards compatibility this is often cited in articles as "for historical reasons"which is mildly dismissive phrase that an author will use to say something is the way it is because mistake was made long ago and we're stuck with it strictly speakinglen(isn' mistakeit' design decisionbut that decision was made in less object-oriented time it has stood the test of time and has some benefitsso do get used to it reversed the reversed(function takes any sequence as inputand returns copy of that sequence in reverse order it is normally used in for loops when we want to loop over items from back to front
3,429
similar to lenreversed calls the __reversed__(function on the class for the parameter if that method does not existreversed builds the reversed sequence itself using calls to __len__ and __getitem__which are used to define sequence we only need to override __reversed__ if we want to somehow customize or optimize the processnormal_list=[ , , , , class customsequence()def __len__(self)return def __getitem__(selfindex)return " { }format(indexclass funkybackwards()def __reversed__(self)return "backwards!for seq in normal_listcustomsequence()funkybackwards()print("\ {}format(seq __class__ __name__)end=""for item in reversed(seq)print(itemend=""the for loops at the end print the reversed versions of normal listand instances of the two custom sequences the output shows that reversed works on all three of thembut has very different results when we define __reversed__ ourselveslist customsequencex funkybackwardsbackwards!when we reverse customsequencethe __getitem__ method is called for each itemwhich just inserts an before the index for funkybackwardsthe __reversed__ method returns stringeach character of which is output individually in the for loop the preceding two classes aren' very good sequences as they don' define proper version of __iter__so forward for loop over them will never end
3,430
enumerate sometimeswhen we're looping over container in for loopwe want access to the index (the current position in the listof the current item being processed the for loop doesn' provide us with indexesbut the enumerate function gives us something betterit creates sequence of tupleswhere the first object in each tuple is the index and the second is the original item this is useful if we need to use index numbers directly consider some simple code that outputs each of the lines in file with line numbersimport sys filename sys argv[ with open(filenameas filefor indexline in enumerate(file)print("{ }{ }format(index+ line)end=''running this code using it' own filename as the input file shows how it works import sys filename sys argv[ with open(filenameas file for indexline in enumerate(file) print("{ }{ }format(index+ line)end=''the enumerate function returns sequence of tuplesour for loop splits each tuple into two valuesand the print statement formats them together it adds one to the index for each line numbersince enumeratelike all sequencesis zero-based we've only touched on few of the more important python built-in functions as you can seemany of them call into object-oriented conceptswhile others subscribe to purely functional or procedural paradigms there are numerous others in the standard librarysome of the more interesting ones includeall and anywhich accept an iterable object and return true if allor anyevalexecand compilewhich execute string as code inside the interpreter of the items evaluate to true (such as nonempty string or lista nonzero numberan object that is not noneor the literal truebe careful with these onesthey are not safeso don' execute code an unknown user has supplied to you (in generalassume all unknown users are maliciousfoolishor both
3,431
hasattrgetattrsetattrand delattrwhich allow attributes on an zipwhich takes two or more sequences and returns new sequence of and many moresee the interpreter help documentation for each of the functions listed in dir(__builtins__object to be manipulated by their string names tupleswhere each tuple contains single value from each sequence file / our examples so far that touch the filesystem have operated entirely on text files without much thought to what is going on under the hood operating systemshoweveractually represent files as sequence of bytesnot text we'll do deep dive into the relationship between bytes and text in strings and serialization for nowbe aware that reading textual data from file is fairly involved process pythonespecially python takes care of most of this work for us behind the scenes aren' we luckythe concept of files has been around since long before anyone coined the term object-oriented programming howeverpython has wrapped the interface that operating systems provide in sweet abstraction that allows us to work with file (or file-likevis- -vis duck typingobjects the open(built-in function is used to open file and return file object for reading text from filewe only need to pass the name of the file into the function the file will be opened for readingand the bytes will be converted to text using the platform default encoding of coursewe don' always want to read filesoften we want to write data to themto open file for writingwe need to pass mode argument as the second positional argumentwith value of " "contents "some file contentsfile open("filename"" "file write(contentsfile close(we could also supply the value "aas mode argumentto append to the end of the filerather than completely overwriting existing file contents these files with built-in wrappers for converting bytes to text are greatbut it' be awfully inconvenient if the file we wanted to open was an imageexecutableor other binary filewouldn' it
3,432
to open binary filewe modify the mode string to append 'bso'wbwould open file for writing byteswhile 'rballows us to read them they will behave like text filesbut without the automatic encoding of text to bytes when we read such fileit will return bytes objects instead of strand when we write to itit will fail if we try to pass text object these mode strings for controlling how files are opened are rather cryptic and are neither pythonic nor object-oriented howeverthey are consistent with virtually every other programming language out there file / is one of the fundamental jobs an operating system has to handleand all programming languages have to talk to the os using the same system calls just be glad that python returns file object with useful methods instead of the integer that most major operating systems use to identify file handleonce file is opened for readingwe can call the readreadlineor readlines methods to get the contents of the file the read method returns the entire contents of the file as str or bytes objectdepending on whether there is 'bin the mode be careful not to use this method without arguments on huge files you don' want to find out what happens if you try to load that much data into memoryit is also possible to read fixed number of bytes from filewe pass an integer argument to the read method describing how many bytes we want to read the next call to read will load the next sequence of bytesand so on we can do this inside while loop to read the entire file in manageable chunks the readline method returns single line from the file (where each line ends in newlinea carriage returnor bothdepending on the operating system on which the file was createdwe can call it repeatedly to get additional lines the plural readlines method returns list of all the lines in the file like the read methodit' not safe to use on very large files these two methods even work when the file is open in bytes modebut it only makes sense if we are parsing text-like data that has newlines at reasonable positions an image or audio filefor examplewill not have newline characters in it (unless the newline byte happened to represent certain pixel or sound)so applying readline wouldn' make sense for readabilityand to avoid reading large file into memory at onceit is often better to use for loop directly on file object for text filesit will read each lineone at timeand we can process it inside the loop body for binary filesit' better to read fixed-sized chunks of data using the read(methodpassing parameter for the maximum number of bytes to read
3,433
writing to file is just as easythe write method on file objects writes string (or bytesfor binary dataobject to the file it can be called repeatedly to write multiple stringsone after the other the writelines method accepts sequence of strings and writes each of the iterated values to the file the writelines method does not append new line after each item in the sequence it is basically poorly named convenience function to write the contents of sequence of strings without having to explicitly iterate over it using for loop lastlyand do mean lastlywe come to the close method this method should be called when we are finished reading or writing the fileto ensure any buffered writes are written to the diskthat the file has been properly cleaned upand that all resources associated with the file are released back to the operating system technicallythis will happen automatically when the script exitsbut it' better to be explicit and clean up after ourselvesespecially in long-running processes placing it in context the need to close files when we are finished with them can make our code quite ugly because an exception may occur at any time during file /owe ought to wrap all calls to file in try finally clause the file should be closed in the finally clauseregardless of whether / was successful this isn' very pythonic of coursethere is more elegant way to do it if we run dir on file-like objectwe see that it has two special methods named __enter__ and __exit__ these methods turn the file object into what is known as context manager basicallyif we use special syntax called the with statementthese methods will be called before and after nested code is executed on file objectsthe __exit__ method ensures the file is closedeven if an exception is raised we no longer have to explicitly manage the closing of the file here is what the with statement looks like in practicewith open('filename'as filefor line in fileprint(lineend=''the open call returns file objectwhich has __enter__ and __exit__ methods the returned object is assigned to the variable named file by the as clause we know the file will be closed when the code returns to the outer indentation leveland that this will happen even if an exception is raised
3,434
the with statement is used in several places in the standard library where startup or cleanup code needs to be executed for examplethe urlopen call returns an object that can be used in with statement to clean up the socket when we're done locks in the threading module can automatically release the lock when the statement has been executed most interestinglybecause the with statement can apply to any object that has the appropriate special methodswe can use it in our own frameworks for exampleremember that strings are immutablebut sometimes you need to build string from multiple parts for efficiencythis is usually done by storing the component strings in list and joining them at the end let' create simple context manager that allows us to construct sequence of characters and automatically convert it to string upon exitclass stringjoiner(list)def __enter__(self)return self def __exit__(selftypevaluetb)self result "join(selfthis code adds the two special methods required of context manager to the list class it inherits from the __enter__ method performs any required setup code (in this casethere isn' anyand then returns the object that will be assigned to the variable after as in the with statement oftenas we've done herethis is just the context manager object itself the __exit__ method accepts three arguments in normal situationthese are all given value of none howeverif an exception occurs inside the with blockthey will be set to values related to the typevalueand traceback for the exception this allows the __exit__ method to do any cleanup code that may be requiredeven if an exception occurred in our examplewe take the irresponsible path and create result string by joining the characters in the stringregardless of whether an exception was thrown while this is one of the simplest context managers we could writeand its usefulness is dubiousit does work with with statement have look at it in actionimport randomstring with stringjoiner(as joinerfor in range( )joiner append(random choice(string ascii_letters)print(joiner result
3,435
this code constructs string of random characters it appends these to stringjoiner using the append method it inherited from list when the with statement goes out of scope (back to the outer indentation level)the __exit__ method is calledand the result attribute becomes available on the joiner object we print this value to see random string an alternative to method overloading one prominent feature of many object-oriented programming languages is tool called method overloading method overloading simply refers to having multiple methods with the same name that accept different sets of arguments in statically typed languagesthis is useful if we want to have method that accepts either an integer or stringfor example in non-object-oriented languageswe might need two functionscalled add_s and add_ito accommodate such situations in statically typed object-oriented languageswe' need two methodsboth called addone that accepts stringsand one that accepts integers in pythonwe only need one methodwhich accepts any type of object it may have to do some testing on the object type (for exampleif it is stringconvert it to an integer)but only one method is required howevermethod overloading is also useful when we want method with the same name to accept different numbers or sets of arguments for examplean -mail message method might come in two versionsone of which accepts an argument for the "frome-mail address the other method might look up default "frome-mail address instead python doesn' permit multiple methods with the same namebut it does provide differentequally flexibleinterface we've seen some of the possible ways to send arguments to methods and functions in previous examplesbut now we'll cover all the details the simplest function accepts no arguments we probably don' need an examplebut here' one for completenessdef no_args()pass here' how it' calledno_args( function that does accept arguments will provide the names of those arguments in comma-separated list only the name of each argument needs to be supplied
3,436
when calling the functionthese positional arguments must be specified in orderand none can be missed or skipped this is the most common way we've specified arguments in our previous examplesdef mandatory_args(xyz)pass to call itmandatory_args(" string"a_variable any type of object can be passed as an argumentan objecta containera primitiveeven functions and classes the preceding call shows hardcoded stringan unknown variableand an integer passed into the function default arguments if we want to make an argument optionalrather than creating second method with different set of argumentswe can specify default value in single methodusing an equals sign if the calling code does not supply this argumentit will be assigned default value howeverthe calling code can still choose to override the default by passing in different value oftena default value of noneor an empty string or list is suitable here' function definition with default argumentsdef default_arguments(xyza="some string" =false)pass the first three arguments are still mandatory and must be passed by the calling code the last two parameters have default arguments supplied there are several ways we can call this function we can supply all arguments in order as though all the arguments were positional argumentsdefault_arguments(" string"variable ""truealternativelywe can supply just the mandatory arguments in orderleaving the keyword arguments to be assigned their default valuesdefault_arguments(" longer string"some_variable we can also use the equals sign syntax when calling function to provide values in different orderor to skip default values that we aren' interested in for examplewe can skip the first keyword arguments and supply the second onedefault_arguments(" string"variable =true
3,437
surprisinglywe can even use the equals sign syntax to mix up the order of positional argumentsso long as all of them are supplieddefault_arguments( = , = , = , ="hi" hi false with so many optionsit may seem hard to pick onebut if you think of the positional arguments as an ordered listand keyword arguments as sort of like dictionaryyou'll find that the correct layout tends to fall into place if you need to require the caller to specify an argumentmake it mandatoryif you have sensible defaultthen make it keyword argument choosing how to call the method normally takes care of itselfdepending on which values need to be suppliedand which can be left at their defaults one thing to take note of with keyword arguments is that anything we provide as default argument is evaluated when the function is first interpretednot when it is called this means we can' have dynamically generated default values for examplethe following code won' behave quite as expectednumber def funky_function(number=number)print(numbernumber= funky_function( funky_function(print(numberif we run this codeit outputs the number firstbut then it outputs the number for the call with no arguments we had set the variable to the number as evidenced by the last line of outputbut when the function is calledthe number is printedthe default value was calculated when the function was definednot when it was called this is tricky with empty containers such as listssetsand dictionaries for exampleit is common to ask calling code to supply list that our function is going to manipulatebut the list is optional we' like to make an empty list as default argument we can' do thisit will create only one listwhen the code is first constructeddef hello( =[]) append(' 'print(
3,438
hello([' 'hello([' '' 'whoopsthat' not quite what we expectedthe usual way to get around this is to make the default value noneand then use the idiom iargument argument if argument else [inside the method pay close attentionvariable argument lists default values alone do not allow us all the flexible benefits of method overloading the thing that makes python really slick is the ability to write methods that accept an arbitrary number of positional or keyword arguments without explicitly naming them we can also pass arbitrary lists and dictionaries into such functions for examplea function to accept link or list of links and download the web pages could use such variadic argumentsor varargs instead of accepting single value that is expected to be list of linkswe can accept an arbitrary number of argumentswhere each argument is different link we do this by specifying the operator in the function definitiondef get_pages(*links)for link in links#download the link with urllib print(linkthe *links parameter says " 'll accept any number of arguments and put them all in list named linksif we supply only one argumentit'll be list with one elementif we supply no argumentsit'll be an empty list thusall these function calls are validget_pages(get_pages('get_pages(''we can also accept arbitrary keyword arguments these arrive into the function as dictionary they are specified with two asterisks (as in **kwargsin the function declaration this tool is commonly used in configuration setups the following class allows us to specify set of options with default valuesclass optionsdefault_options
3,439
'port' 'host''localhost''username'none'password'none'debug'falsedef __init__(self**kwargs)self options dict(options default_optionsself options update(kwargsdef __getitem__(selfkey)return self options[keyall the interesting stuff in this class happens in the __init__ method we have dictionary of default options and values at the class level the first thing the __init__ method does is make copy of this dictionary we do that instead of modifying the dictionary directly in case we instantiate two separate sets of options (rememberclass-level variables are shared between instances of the class then__init__ uses the update method on the new dictionary to change any non-default values to those supplied as keyword arguments the __getitem__ method simply allows us to use the new class using indexing syntax here' session demonstrating the class in actionoptions options(username="dusty"password="drowssap"debug=trueoptions['debug'true options['port' options['username''dustywe're able to access our options instance using dictionary indexing syntaxand the dictionary includes both default values and the ones we set using keyword arguments the keyword argument syntax can be dangerousas it may break the "explicit is better than implicitrule in the preceding exampleit' possible to pass arbitrary keyword arguments to the options initializer to represent options that don' exist in the default dictionary this may not be bad thingdepending on the purpose of the classbut it makes it hard for someone using the class to discover what valid options are available it also makes it easy to enter confusing typo ("debuginstead of "debug"for examplethat adds two options where only one should have existed
3,440
keyword arguments are also very useful when we need to accept arbitrary arguments to pass to second functionbut we don' know what those arguments will be we saw this in action in when objects are alikewhen we were building support for multiple inheritance we canof coursecombine the variable argument and variable keyword argument syntax in one function calland we can use normal positional and default arguments as well the following example is somewhat contrivedbut demonstrates the four types in actionimport shutil import os path def augmented_move(target_folder*filenamesverbose=false**specific)'''move all filenames into the target_folderallowing specific treatment of certain files ''def print_verbose(messagefilename)'''print the message only if verbose is enabled''if verboseprint(message format(filename)for filename in filenamestarget_path os path join(target_folderfilenameif filename in specificif specific[filename='ignore'print_verbose("ignoring { }"filenameelif specific[filename='copy'print_verbose("copying { }"filenameshutil copyfile(filenametarget_pathelseprint_verbose("moving { }"filenameshutil move(filenametarget_paththis example will process an arbitrary list of files the first argument is target folderand the default behavior is to move all remaining non-keyword argument files into that folder then there is keyword-only argumentverbosewhich tells us whether to print information on each file processed finallywe can supply dictionary containing actions to perform on specific filenamesthe default behavior is to move the filebut if valid string action has been specified in the keyword argumentsit can be ignored or copied instead notice the ordering of the parameters in the functionfirst the positional argument is specifiedthen the *filenames listthen any specific keyword-only argumentsand finallya **specific dictionary to hold remaining keyword arguments
3,441
we create an inner helper functionprint_verbosewhich will print messages only if the verbose key has been set this function keeps code readable by encapsulating this functionality into single location in common casesassuming the files in question existthis function could be called asaugmented_move("move_here""one""two"this command would move the files one and two into the move_here directoryassuming they exist (there' no error checking or exception handling in the functionso it would fail spectacularly if the files or target directory didn' existthe move would occur without any outputsince verbose is false by default if we want to see the outputwe can call it withaugmented_move("move_here""three"verbose=truemoving three this moves one file named threeand tells us what it' doing notice that it is impossible to specify verbose as positional argument in this examplewe must pass keyword argument otherwisepython would think it was another filename in the *filenames list if we want to copy or ignore some of the files in the listinstead of moving themwe can pass additional keyword argumentsaugmented_move("move_here""four""five""six"four="copy"five="ignore"this will move the sixth file and copy the fourthbut won' display any outputsince we didn' specify verbose of coursewe can do that tooand keyword arguments can be supplied in any orderaugmented_move("move_here""seven""eight""nine"seven="copy"verbose=trueeight="ignore"copying seven ignoring eight moving nine
3,442
unpacking arguments there' one more nifty trick involving variable arguments and keyword arguments we've used it in some of our previous examplesbut it' never too late for an explanation given list or dictionary of valueswe can pass those values into function as if they were normal positional or keyword arguments have look at this codedef show_args(arg arg arg ="three")print(arg arg arg some_args range( more_args "arg ""one""arg ""two"print("unpacking sequence:"end="show_args(*some_argsprint("unpacking dict:"end="show_args(**more_argshere' what it looks like when we run itunpacking sequence unpacking dictone two three the function accepts three argumentsone of which has default value but when we have list of three argumentswe can use the operator inside function call to unpack it into the three arguments if we have dictionary of argumentswe can use the *syntax to unpack it as collection of keyword arguments this is most often useful when mapping information that has been collected from user input or from an outside source (for examplean internet page or text fileto function or method call remember our earlier example that used headers and lines in text file to create list of dictionaries with contact informationinstead of just adding the dictionaries to listwe could use keyword unpacking to pass the arguments to the __init__ method on specially built contact object that accepts the same set of arguments see if you can adapt the example to make this work
3,443
functions are objects too programming languages that overemphasize object-oriented principles tend to frown on functions that are not methods in such languagesyou're expected to create an object to sort of wrap the single method involved there are numerous situations where we' like to pass around small object that is simply called to perform an action this is most frequently done in event-driven programmingsuch as graphical toolkits or asynchronous serverswe'll see some design patterns that use it in python design patterns and python design patterns ii in pythonwe don' need to wrap such methods in an objectbecause functions already are objectswe can set attributes on functions (though this isn' common activity)and we can pass them around to be called at later date they even have few special properties that can be accessed directly here' yet another contrived exampledef my_function()print("the function was called"my_function description " silly functiondef second_function()print("the second was called"second_function description " sillier function def another_function(function)print("the description:"end="print(function descriptionprint("the name:"end="print(function __name__print("the class:"end="print(function __class__print("now 'll call the function passed in"function(another_function(my_functionanother_function(second_functionif we run this codewe can see that we were able to pass two different functions into our third functionand get different output for each onethe descriptiona silly function the namemy_function the classnow 'll call the function passed in
3,444
the function was called the descriptiona sillier function the namesecond_function the classnow 'll call the function passed in the second was called we set an attribute on the functionnamed description (not very good descriptionsadmittedlywe were also able to see the function' __name__ attributeand to access its classdemonstrating that the function really is an object with attributes then we called the function by using the callable syntax (the parenthesesthe fact that functions are top-level objects is most often used to pass them around to be executed at later datefor examplewhen certain condition has been satisfied let' build an event-driven timer that does just thisimport datetime import time class timedeventdef __init__(selfendtimecallback)self endtime endtime self callback callback def ready(self)return self endtime <datetime datetime now(class timerdef __init__(self)self events [def call_after(selfdelaycallback)end_time datetime datetime now(datetime timedelta(seconds=delayself events append(timedevent(end_timecallback)def run(self)while trueready_events ( for in self events if ready()for event in ready_eventsevent callback(selfself events remove(eventtime sleep(
3,445
in productionthis code should definitely have extra documentation using docstringsthe call_after method should at least mention that the delay parameter is in secondsand that the callback function should accept one argumentthe timer doing the calling we have two classes here the timedevent class is not really meant to be accessed by other classesall it does is store endtime and callback we could even use tuple or namedtuple herebut as it is convenient to give the object behavior that tells us whether or not the event is ready to runwe use class instead the timer class simply stores list of upcoming events it has call_after method to add new event this method accepts delay parameter representing the number of seconds to wait before executing the callbackand the callback function itselfa function to be executed at the correct time this callback function should accept one argument the run method is very simpleit uses generator expression to filter out any events whose time has comeand executes them in order the timer loop then continues indefinitelyso it has to be interrupted with keyboard interrupt (ctrl or ctrl breakwe sleep for half second after each iteration so as to not grind the system to halt the important things to note here are the lines that touch callback functions the function is passed around like any other object and the timer never knows or cares what the original name of the function is or where it was defined when it' time to call the functionthe timer simply applies the parenthesis syntax to the stored variable here' set of callbacks that test the timerfrom timer import timer import datetime def format_time(message*args)now datetime datetime now(strftime("% :% :% "print(message format(*argsnow=now)def one(timer)format_time("{now}called one"def two(timer)format_time("{now}called two"def three(timer)
3,446
format_time("{now}called three"class repeaterdef __init__(self)self count def repeater(selftimer)format_time("{now}repeat { }"self countself count + timer call_after( self repeatertimer timer(timer call_after( onetimer call_after( onetimer call_after( twotimer call_after( twotimer call_after( threetimer call_after( threerepeater repeater(timer call_after( repeater repeaterformat_time("{now}starting"timer run(this example allows us to see how multiple callbacks interact with the timer the first function is the format_time function it uses the string format method to add the current time to the messageand illustrates variable arguments in action the format_time method will accept any number of positional argumentsusing variable argument syntaxwhich are then forwarded as positional arguments to the string' format method after thiswe create three simple callback methods that simply output the current time and short message telling us which callback has been fired the repeater class demonstrates that methods can be used as callbacks toosince they are really just functions it also shows why the timer argument to the callback functions is usefulwe can add new timed event to the timer from inside presently running callback we then create timer and add several events to it that are called after different amounts of time finallywe start the timer runningthe output shows that events are run in the expected order : : starting : : called one : : called one : : called two : : called three : : called two : : repeat
3,447
: : called three : : repeat : : repeat : : repeat : : repeat python introduces generic event-loop architecture similar to this we'll be discussing it later in concurrency using functions as attributes one of the interesting effects of functions being objects is that they can be set as callable attributes on other objects it is possible to add or change function to an instantiated objectclass adef print(self)print("my class is "def fake_print()print("my class is not " ( print( print fake_print print(this code creates very simple class with print method that doesn' tell us anything we didn' know then we create new function that tells us something we don' believe when we call print on an instance of the classit behaves as expected if we then set the print method to point at new functionit tells us something differentmy class is my class is not it is also possible to replace methods on classes instead of objectsalthough in that case we have to add the self argument to the parameter list this will change the method for all instances of that objecteven ones that have already been instantiated obviouslyreplacing methods like this can be both dangerous and confusing to maintain somebody reading the code will see that method has been called and look up that method on the original class but the method on the original class is not the one that was called figuring out what really happened can become trickyfrustrating debugging session
3,448
it does have its uses though oftenreplacing or adding methods at run time (called monkey-patchingis used in automated testing if testing client-server applicationwe may not want to actually connect to the server while testing the clientthis may result in accidental transfers of funds or embarrassing test -mails being sent to real people insteadwe can set up our test code to replace some of the key methods on the object that sends requests to the serverso it only records that the methods have been called monkey-patching can also be used to fix bugs or add features in third-party code that we are interacting withand does not behave quite the way we need it to it shouldhoweverbe applied sparinglyit' almost always "messy hacksometimesthoughit is the only way to adapt an existing library to suit our needs callable objects just as functions are objects that can have attributes set on themit is possible to create an object that can be called as though it were function any object can be made callable by simply giving it __call__ method that accepts the required arguments let' make our repeater classfrom the timer examplea little easier to use by making it callableclass repeaterdef __init__(self)self count def __call__(selftimer)format_time("{now}repeat { }"self countself count + timer call_after( selftimer timer(timer call_after( repeater()format_time("{now}starting"timer run(
3,449
this example isn' much different from the earlier classall we did was change the name of the repeater function to __call__ and pass the object itself as callable note that when we make the call_after callwe pass the argument repeater(those two parentheses are creating new instance of the classthey are not explicitly calling the class this happens laterinside the timer if we want to execute the __call__ method on newly instantiated objectwe' use rather odd syntaxrepeater()(the first set of parentheses constructs the objectthe second set executes the __call__ method if we find ourselves doing thiswe may not be using the correct abstraction only implement the __call__ function on an object if the object is meant to be treated like function case study to tie together some of the principles presented in this let' build mailing list manager the manager will keep track of -mail addresses categorized into named groups when it' time to send messagewe can pick group and send the message to all -mail addresses assigned to that group nowbefore we start working on this projectwe ought to have safe way to test itwithout sending -mails to bunch of real people luckilypython has our back herelike the test http serverit has built-in simple mail transfer protocol (smtpserver that we can instruct to capture any messages we send without actually sending them we can run the server with the following commandpython - smtpd - - debuggingserver localhost: running this command at command prompt will start an smtp server running on port on the local machine but we've instructed it to use the debuggingserver class (it comes with the built-in smtp module)whichinstead of sending mails to the intended recipientssimply prints them on the terminal screen as it receives them neatehnowbefore writing our mailing listlet' write some code that actually sends mail of coursepython supports this in the standard librarytoobut it' bit of an odd interfaceso we'll write new function to wrap it all cleanlyimport smtplib from email mime text import mimetext def send_email(subjectmessagefrom_addr*to_addrs
3,450
host="localhost"port= **headers)email mimetext(messageemail['subject'subject email['from'from_addr for headervalue in headers items()email[headervalue sender smtplib smtp(hostportfor addr in to_addrsdel email['to'email['to'addr sender sendmail(from_addraddremail as_string()sender quit(we won' cover the code inside this method too thoroughlythe documentation in the standard library can give you all the information you need to use the smtplib and email modules effectively we've used both variable argument and keyword argument syntax in the function call the variable argument list allows us to supply single string in the default case of having single to addressas well as permitting multiple addresses to be supplied if required any extra keyword arguments are mapped to -mail headers this is an exciting use of variable arguments and keyword argumentsbut it' not really great interface for the person calling the function in factit makes many things the programmer will want to do impossible the headers passed into the function represent auxiliary headers that can be attached to method such headers might include reply-toreturn-pathor -pretty-much-anything but in order to be valid identifier in pythona name cannot include the character in generalthat character represents subtraction soit' not possible to call function with reply-to my@email com it appears we were too eager to use keyword arguments because they are new tool we just learned about in this we'll have to change the argument to normal dictionarythis will work because any string can be used as key in dictionary by defaultwe' want this dictionary to be emptybut we can' make the default parameter an empty dictionary sowe'll have to make the default argument noneand then set up the dictionary at the beginning of the methoddef send_email(subjectmessagefrom_addr*to_addrs
3,451
host="localhost"port= headers=none)headers {if headers is none else headers if we have our debugging smtp server running in one terminalwe can test this code in python interpretersend_email(" model subject""the message contents""from@example com""to @example com""to @example com"thenif we check the output from the debugging smtp serverwe get the followingmessage follows content-typetext/plaincharset="us-asciimime-version content-transfer-encoding bit subjecta model subject fromfrom@example com toto @example com -peer the message contents end message message follows content-typetext/plaincharset="us-asciimime-version content-transfer-encoding bit subjecta model subject fromfrom@example com toto @example com -peer the message contents end message
3,452
excellentit has "sentour -mail to the two expected addresses with subject and message contents included now that we can send messageslet' work on the -mail group management system we'll need an object that somehow matches -mail addresses with the groups they are in since this is many-to-many relationship (any one -mail address can be in multiple groupsany one group can be associated with multiple -mail addresses)none of the data structures we've studied seems quite ideal we could try dictionary of group-names matched to list of associated -mail addressesbut that would duplicate -mail addresses we could also try dictionary of -mail addresses matched to groupsresulting in duplication of groups neither seems optimal let' try this latter versioneven though intuition tells me the groups to -mail address solution would be more straightforward since the values in our dictionary will always be collections of unique -mail addresseswe should probably store them in set container we can use defaultdict to ensure that there is always set container available for each keyfrom collections import defaultdict class mailinglist'''manage groups of -mail addresses for sending -mails ''def __init__(self)self email_map defaultdict(setdef add_to_group(selfemailgroup)self email_map[emailadd(groupnowlet' add method that allows us to collect all the -mail addresses in one or more groups this can be done by converting the list of groups to setdef emails_in_groups(self*groups)groups set(groupsemails set(for eg in self email_map items()if groupsemails add(ereturn emails firstlook at what we're iterating overself email_map items(this methodof coursereturns tuple of key-value pairs for each item in the dictionary the values are sets of strings representing the groups we split these into two variables named and gshort for -mail and groups we add the -mail address to the set of return values only if the passed in groups intersect with the -mail address groups the groups syntax is shortcut for intersection(groups)the set class does this by implementing the special __and__ method to call intersection
3,453
this code could be made wee bit more concise using set comprehensionwhich we'll discuss in the iterator pattern nowwith these building blockswe can trivially add method to our mailinglist class that sends messages to specific groupsdef send_mailing(selfsubjectmessagefrom_addr*groupsheaders=none)emails self emails_in_groups(*groupssend_email(subjectmessagefrom_addr*emailsheaders=headersthis function relies on variable argument lists as inputit takes list of groups as variable arguments it gets the list of -mails for the specified groups and passes those as variable arguments into send_emailalong with other arguments that were passed into this method the program can be tested by ensuring the smtp debugging server is running in one command promptandin second promptloading the code usingpython - mailing_list py create mailinglist object withm mailinglist(then create few fake -mail addresses and groupsalong the lines ofm add_to_group("friend @example com""friends" add_to_group("friend @example com""friends" add_to_group("family @example com""family" add_to_group("pro @example com""professional"finallyuse command like this to send -mails to specific groupsm send_mailing(" party""friends and family onlya party""me@example com""friends""family"headers={"reply-to""me @example com"} -mails to each of the addresses in the specified groups should show up in the console on the smtp server the mailing list works fine as it isbut it' kind of uselessas soon as we exit the programour database of information is lost let' modify it to add couple of methods to load and save the list of -mail groups from and to file
3,454
in generalwhen storing structured data on diskit is good idea to put lot of thought into how it is stored one of the reasons myriad database systems exist is that if someone else has put this thought into how data is storedyou don' have to we'll be looking at some data serialization mechanisms in the next but for this examplelet' keep it simple and go with the first solution that could possibly work the data format have in mind is to store each -mail address followed by spacefollowed by comma-separated list of groups this format seems reasonableand we're going to go with it because data formatting isn' the topic of this howeverto illustrate just why you need to think hard about how you format data on disklet' highlight few problems with the format firstthe space character is technically legal in -mail addresses most -mail providers prohibit it (with good reason)but the specification defining -mail addresses says an -mail can contain space if it is in quotation marks if we are to use space as sentinel in our data formatwe should technically be able to differentiate between that space and space that is part of an -mail we're going to pretend this isn' truefor simplicity' sakebut real-life data encoding is full of stupid issues like this secondconsider the comma-separated list of groups what happens if someone decides to put comma in group nameif we decide to make commas illegal in group nameswe should add validation to ensure this to our add_to_group method for pedagogical claritywe'll ignore this problem too finallythere are many security implications we need to considercan someone get themselves into the wrong group by putting fake comma in their -mail addresswhat does the parser do if it encounters an invalid filethe takeaway from this discussion is to try to use data-storage method that has been field testedrather than designing your own data serialization protocol there are ton of bizarre edge cases you might overlookand it' better to use code that has already encountered and fixed those edge cases but forget thatlet' just write some basic code that uses an unhealthy dose of wishful thinking to pretend this simple data format is safeemail @mydomain com group ,group email @mydomain com group ,group the code to do this is as followsdef save(self)with open(self data_file' 'as filefor emailgroups in self email_map items()file write
3,455
'{{}\nformat(email',join(groups)def load(self)self email_map defaultdict(settrywith open(self data_fileas filefor line in fileemailgroups line strip(split('groups set(groups split(',')self email_map[emailgroups except ioerrorpass in the save methodwe open the file in context manager and write the file as formatted string remember the newline characterpython doesn' add that for us the load method first resets the dictionary (in case it contains data from previous call to loaduses the for in syntaxwhich loops over each line in the file againthe newline character is included in the line variableso we have to call strip(to take it off we'll learn more about such string manipulation in the next before using these methodswe need to make sure the object has self data_file attributewhich can be done by modifying __init__def __init__(selfdata_file)self data_file data_file self email_map defaultdict(setwe can test these two methods in the interpreter as followsm mailinglist('addresses db' add_to_group('friend @example com''friends' add_to_group('family @example com''friends' add_to_group('family @example com''family' save(the resulting addresses db file contains the following linesas expectedfriend @example com friends family @example com friends,family
3,456
we can also load this data back into mailinglist object successfullym mailinglist('addresses db' email_map defaultdict({} load( email_map defaultdict({'friend @example com'{'friends\ '}'family @example com'{'family\ '}'friend @example com'{'friends\ '}}as you can seei forgot to do the load commandand it might be easy to forget the save command as well to make this little easier for anyone who wants to use our mailinglist api in their own codelet' provide the methods to support context managerdef __enter__(self)self load(return self def __exit__(selftypevaluetb)self save(these simple methods just delegate their work to load and savebut we can now write code like this in the interactive interpreter and know that all the previously stored addresses were loaded on our behalfand that the whole list will be saved to the file when we are donewith mailinglist('addresses db'as mlml add_to_group('friend @example com''friends'ml send_mailing("what' up""hey friendshow' it going"'meexample com''friends'exercises if you haven' encountered the with statements and context managers beforei encourage youas usualto go through your old code and find all the places you were opening filesand make sure they are safely closed using the with statement look for places that you could write your own context managers as well ugly or repetitive try finally clauses are good place to startbut you may find them useful any time you need to do before and/or after tasks in context
3,457
you've probably used many of the basic built-in functions before now we covered several of thembut didn' go into great deal of detail play with enumeratezipreversedany and alluntil you know you'll remember to use them when they are the right tool for the job the enumerate function is especially importantbecause not using it results in some pretty ugly code also explore some applications that pass functions around as callable objectsas well as using the __call__ method to make your own objects callable you can get the same effect by attaching attributes to functions or by creating __call__ method on an object in which case would you use one syntaxand when would it be more suitable to use the otherour mailing list object could overwhelm an -mail server if there is massive number of -mails to be sent out try refactoring it so that you can use different send_email functions for different purposes one such function could be the version we used here different version might put the -mails in queue to be sent by server in different thread or process third version could just output the data to the terminalobviating the need for dummy smtp server can you construct the mailing list with callback such that the send_mailing function uses whatever is passed init would default to the current version if no callback is supplied the relationship between argumentskeyword argumentsvariable argumentsand variable keyword arguments can be bit confusing we saw how painfully they can interact when we covered multiple inheritance devise some other examples to see how they can work well togetheras well as to understand when they don' summary we covered grab bag of topics in this each represented an important non-object-oriented feature that is popular in python just because we can use object-oriented principles does not always mean we shouldhoweverwe also saw that python typically implements such features by providing syntax shortcut to traditional object-oriented syntax knowing the object-oriented principles underlying these tools allows us to use them more effectively in our own classes we discussed series of built-in functions and file / operations there are whole bunch of different syntaxes available to us when calling functions with argumentskeyword argumentsand variable argument lists context managers are useful for the common pattern of sandwiching piece of code between two method calls even functions are objectsandconverselyany normal object can be made callable
3,458
in the next we'll learn more about string and file manipulationand even spend some time with one of the least object-oriented topics in the standard libraryregular expressions
3,459
before we get involved with higher level design patternslet' take deep dive into one of python' most common objectsthe string we'll see that there is lot more to the string than meets the eyeand also cover searching strings for patterns and serializing data for storage or transmission in particularwe'll visitthe complexities of stringsbytesand byte arrays the ins and outs of string formatting few ways to serialize data the mysterious regular expression strings strings are basic primitive in pythonwe've used them in nearly every example we've discussed so far all they do is represent an immutable sequence of characters howeverthough you may not have considered it before"characteris bit of an ambiguous wordcan python strings represent sequences of accented characterschinese characterswhat about greekcyrillicor farsiin python the answer is yes python strings are all represented in unicodea character definition standard that can represent virtually any character in any language on the planet (and some made-up languages and random characters as wellthis is done seamlesslyfor the most part solet' think of python strings as an immutable sequence of unicode characters so what can we do with this immutable sequencewe've touched on many of the ways strings can be manipulated in previous examplesbut let' quickly cover it all in one placea crash course in string theory
3,460
string manipulation as you knowstrings can be created in python by wrapping sequence of characters in single or double quotes multiline strings can easily be created using three quote charactersand multiple hardcoded strings can be concatenated together by placing them side by side here are some examplesa "hellob 'worldc ''' multiple line string'' """more multiple"" ("three "strings "together"that last string is automatically composed into single string by the interpreter it is also possible to concatenate strings using the operator (as in "hello "world"of coursestrings don' have to be hardcoded they can also come from various outside sources such as text filesuser inputor encoded on the network the automatic concatenation of adjacent strings can make for some hilarious bugs when comma is missed it ishoweverextremely useful when long string needs to be placed inside function call without exceeding the character line-length limit suggested by the python style guide like other sequencesstrings can be iterated over (character by character)indexedslicedor concatenated the syntax is the same as for lists the str class has numerous methods on it to make manipulating strings easier the dir and help commands in the python interpreter can tell us how to use all of themwe'll consider some of the more common ones directly several boolean convenience methods help us identify whether or not the characters in string match certain pattern here is summary of these methods most of thesesuch as isalphaisupper/islowerand startswith/endswith have obvious interpretations the isspace method is also fairly obviousbut remember that all whitespace characters (including tabnewlineare considerednot just the space character
3,461
the istitle method returns true if the first character of each word is capitalized and all other characters are lowercase note that it does not strictly enforce the english grammatical definition of title formatting for exampleleigh hunt' poem "the glove and the lionsshould be valid titleeven though not all words are capitalized robert service' "the cremation of sam mcgeeshould also be valid titleeven though there is an uppercase letter in the middle of the last word be careful with the isdigitisdecimaland isnumeric methodsas they are more nuanced than you would expect many unicode characters are considered numbers besides the ten digits we are used to worsethe period character that we use to construct floats from strings is not considered decimal characterso ' isdecimal(returns false the real decimal character is represented by unicode value as in (or \ furtherthese methods do not verify whether the strings are valid numbers returns true for all three methods we might think we should use that decimal character instead of period for all numeric quantitiesbut passing that character into the float(or int(constructor converts that decimal character to zerofloat(' \ ' other methods useful for pattern matching do not return booleans the count method tells us how many times given substring shows up in the stringwhile findindexrfindand rindex tell us the position of given substring within the original string the two ' (for 'rightor 'reverse'methods start searching from the end of the string the find methods return - if the substring can' be foundwhile index raises valueerror in this situation have look at some of these methods in actions "hello worlds count(' ' find(' ' rindex(' 'traceback (most recent call last)file ""line in valueerrorsubstring not found most of the remaining string methods return transformations of the string the upperlowercapitalizeand title methods create new strings with all alphabetic characters in the given format the translate method can use dictionary to map arbitrary input characters to specified output characters
3,462
for all of these methodsnote that the input string remains unmodifieda brand new str instance is returned instead if we need to manipulate the resultant stringwe should assign it to new variableas in new_value value capitalize(oftenonce we've performed the transformationwe don' need the old value anymoreso common idiom is to assign it to the same variableas in value value title(finallya couple of string methods return or operate on lists the split method accepts substring and splits the string into list of strings wherever that substring occurs you can pass number as second parameter to limit the number of resultant strings the rsplit behaves identically to split if you don' limit the number of stringsbut if you do supply limitit starts splitting from the end of the string the partition and rpartition methods split the string at only the first or last occurrence of the substringand return tuple of three valuescharacters before the substringthe substring itselfand the characters after the substring as the inverse of splitthe join method accepts list of stringsand returns all of those strings combined together by placing the original string between them the replace method accepts two argumentsand returns string where each instance of the first argument has been replaced with the second here are some of these methods in actions "hello worldhow are yous split(' ['hello''world,''how''are''you''#join( 'hello#world,#how#are#yous replace(''**''hello**world,**how**are**yous partition('('hello'''worldhow are you'there you have ita whirlwind tour of the most common methods on the str classnowlet' look at python ' method for composing strings and variables to create new strings string formatting python has powerful string formatting and templating mechanism that allows us to construct strings comprised of hardcoded text and interspersed variables we've used it in many previous examplesbut it is much more versatile than the simple formatting specifiers we've used
3,463
any string can be turned into format string by calling the format(method on it this method returns new string where specific characters in the input string have been replaced with values provided as arguments and keyword arguments passed into the function the format method does not require fixed set of argumentsinternallyit uses the *args and **kwargs syntax that we discussed in python object-oriented shortcuts the special characters that are replaced in formatted strings are the opening and closing brace charactersand we can insert pairs of these in string and they will be replacedin orderby any positional arguments passed to the str format methodtemplate "hello {}you are currently {print(template format('dusty''writing')if we run these statementsit replaces the braces with variablesin orderhello dustyyou are currently writing this basic syntax is not terribly useful if we want to reuse variables within one string or decide to use them in different position we can place zero-indexed integers inside the curly braces to tell the formatter which positional variable gets inserted at given position in the string let' repeat the nametemplate "hello { }you are { your name is { print(template format('dusty''writing')if we use these integer indexeswe have to use them in all the variables we can' mix empty braces with positional indexes for examplethis code fails with an appropriate valueerror exceptiontemplate "hello {}you are {your name is { print(template format('dusty''writing')escaping braces brace characters are often useful in stringsaside from formatting we need way to escape them in situations where we want them to be displayed as themselvesrather than being replaced this can be done by doubling the braces for examplewe can use python to format basic java programtemplate ""public class { {public static void main(string[args{system out println("{ }")}}}""print(template format("myclass""print('hello world')"))
3,464
wherever we see the {or }sequence in the templatethat isthe braces enclosing the java class and method definitionwe know the format method will replace them with single bracesrather than some argument passed into the format method here' the outputpublic class myclass public static void main(string[argssystem out println("print('hello world')")the class name and contents of the output have been replaced with two parameterswhile the double braces have been replaced with single bracesgiving us valid java file turns outthis is about the simplest possible python program to print the simplest possible java program that can print the simplest possible python programkeyword arguments if we're formatting complex stringsit can become tedious to remember the order of the arguments or to update the template if we choose to insert new argument the format method therefore allows us to specify names inside the braces instead of numbers the named variables are then passed to the format method as keyword argumentstemplate ""fromtosubject{subject{message}""print(template formatfrom_email " @example com"to_email " @example com"message "here' some mail for you hope you enjoy the message!"subject "you have mail!)we can also mix index and keyword arguments (as with all python function callsthe keyword arguments must follow the positional oneswe can even mix unlabeled positional braces with keyword argumentsprint("{{label{}format(" "" "label=" ")
3,465
as expectedthis code outputsx container lookups we aren' restricted to passing simple string variables into the format method any primitivesuch as integers or floats can be printed more interestinglycomplex objectsincluding liststuplesdictionariesand arbitrary objects can be usedand we can access indexes and variables (but not methodson those objects from within the format string for exampleif our -mail message had grouped the from and to -mail addresses into tupleand placed the subject and message in dictionaryfor some reason (perhaps because that' the input required for an existing send_mail function we want to use)we can format it like thisemails (" @example com"" @example com"message 'subject'"you have mail!"'message'"here' some mail for you!template ""fromtosubject{message[subject]{message[message]}""print(template format(emailsmessage=message)the variables inside the braces in the template string look little weirdso let' look at what they're doing we have passed one argument as position-based parameter and one as keyword argument the two -mail addresses are looked up by [ ]where is either or the initial zero representsas with other position-based argumentsthe first positional argument passed to format (the emails tuplein this casethe square brackets with number inside are the same kind of index lookup we see in regular python codeso [ maps to emails[ ]in the emails tuple the indexing syntax works with any indexable objectso we see similar behavior when we access message[subject]except this time we are looking up string key in dictionary notice that unlike in python codewe do not need to put quotes around the string in the dictionary lookup
3,466
we can even do multiple levels of lookup if we have nested data structures would recommend against doing this oftenas template strings rapidly become difficult to understand if we have dictionary that contains tuplewe can do thisemails (" @example com"" @example com"message 'emails'emails'subject'"you have mail!"'message'"here' some mail for you!template ""fromtosubject{ [subject]{ [message]}""print(template format(message)object lookups indexing makes format lookup powerfulbut we're not done yetwe can also pass arbitrary objects as parametersand use the dot notation to look up attributes on those objects let' change our -mail message data once againthis time to classclass emaildef __init__(selffrom_addrto_addrsubjectmessage)self from_addr from_addr self to_addr to_addr self subject subject self message message email email(" @example com"" @example com""you have mail!""here' some mail for you!"template ""fromtosubject{ subject{ message}""print(template format(email)
3,467
the template in this example may be more readable than the previous examplesbut the overhead of creating an -mail class adds complexity to the python code it would be foolish to create class for the express purpose of including the object in template typicallywe' use this sort of lookup if the object we are trying to format already exists this is true of all the examplesif we have tuplelistor dictionarywe'll pass it into the template directly otherwisewe' just create simple set of positional and keyword arguments making it look right it' nice to be able to include variables in template stringsbut sometimes the variables need bit of coercion to make them look right in the output for exampleif we are doing calculations with currencywe may end up with long decimal that we don' want to show up in our templatesubtotal tax subtotal total subtotal tax print("sub${ tax${ total${total}formatsubtotaltaxtotal=total)if we run this formatting codethe output doesn' quite look like proper currencysub$ tax$ total$ technicallywe should never use floating-point numbers in currency calculations like thiswe should construct decimal decimal(objects instead floats are dangerous because their calculations are inherently inaccurate beyond specific level of precision but we're looking at stringsnot floatsand currency is great example for formattingto fix the preceding format stringwe can include some additional information inside the curly braces to adjust the formatting of the parameters there are tons of things we can customizebut the basic syntax inside the braces is the samefirstwe use whichever of the earlier layouts (positionalkeywordindexattribute accessis suitable to specify the variable that we want to place in the template string we follow this with colonand then the specific syntax for the formatting here' an improved versionprint("sub${ : ftax${ : "total${total: }formatsubtotaltaxtotal=total)
3,468
the format specifier after the colons basically saysfrom left to rightfor values lower than onemake sure zero is displayed on the left side of the decimal pointshow two places after the decimalformat the input value as float we can also specify that each number should take up particular number of characters on the screen by placing value before the period in the precision this can be useful for outputting tabular datafor exampleorders [('burger' )('fries' )('cola' )print("product quantity price subtotal"for productpricequantity in orderssubtotal price quantity print("{ : }{ ^ ${ }formatproductquantitypricesubtotal)okthat' pretty scary looking format stringso let' see how it works before we break it down into understandable partsproduct quantity price subtotal burger $ fries $ cola $ niftysohow is this actually happeningwe have four variables we are formattingin each line in the for loop the first variable is string and is formatted with { : sthe means it is string variableand the means it should take up ten characters by defaultwith stringsif the string is shorter than the specified number of charactersit appends spaces to the right side of the string to make it long enough (bewarehoweverif the original string is too longit won' be truncated!we can change this behavior (to fill with other characters or change the alignment in the format string)as we do for the next valuequantity the formatter for the quantity value is { ^ dthe represents an integer value the tells us the value should take up nine characters but with integersinstead of spacesthe extra characters are zerosby default that looks kind of weird so we explicitly specify space (immediately after the colonas padding character the caret character tells us that the number should be aligned in the center of this available paddingthis makes the column look bit more professional the specifiers have to be in the right orderalthough all are optionalfill firstthen alignthen the sizeand finallythe type
3,469
we do similar things with the specifiers for price and subtotal for pricewe use { fin both caseswe're specifying space as the fill characterbut we use the symbolsrespectivelyto represent that the numbers should be aligned to the left or right within the minimum space of eight or seven characters furthereach float should be formatted to two decimal places the "typecharacter for different types can affect formatting output as well we've seen the sdand typesfor stringsintegersand floats most of the other format specifiers are alternative versions of thesefor exampleo represents octal format and represents hexadecimal for integers the type specifier can be useful for formatting integer separators in the current locale' format for floating-point numbersthe type will multiply by and format float as percentage while these standard formatters apply to most built-in objectsit is also possible for other objects to define nonstandard specifiers for exampleif we pass datetime object into formatwe can use the specifiers used in the datetime strftime functionas followsimport datetime print("{ :% -% -% % :% % }formatdatetime datetime now())it is even possible to write custom formatters for objects we create ourselvesbut that is beyond the scope of this book look into overriding the __format__ special method if you need to do this in your code the most comprehensive instructions can be found in pep at the details are bit dry you can find more digestible tutorials using web search the python formatting syntax is quite flexible but it is difficult mini-language to remember use it every day and still occasionally have to look up forgotten concepts in the documentation it also isn' powerful enough for serious templating needssuch as generating web pages there are several third-party templating libraries you can look into if you need to do more than basic formatting of few strings strings are unicode at the beginning of this sectionwe defined strings as collections of immutable unicode characters this actually makes things very complicated at timesbecause unicode isn' really storage format if you get string of bytes from file or socketfor examplethey won' be in unicode they willin factbe the built-in type bytes bytes are immutable sequences of wellbytes bytes are the lowest-level storage format in computing they represent bitsusually described as an integer between and or hexadecimal equivalent between and ff bytes don' represent anything specifica sequence of bytes may store characters of an encoded stringor pixels in an image
3,470
if we print byte objectany bytes that map to ascii representations will be printed as their original characterwhile non-ascii bytes (whether they are binary data or other charactersare printed as hex codes escaped by the \ escape sequence you may find it odd that byterepresented as an integercan map to an ascii character but ascii is really just code where each letter is represented by different byte patternand thereforea different integer the character "ais represented by the same byte as the integer which is the hexadecimal number specificallyall of these are an interpretation of the binary pattern many / operations only know how to deal with byteseven if the bytes object refers to textual data it is therefore vital to know how to convert between bytes and unicode the problem is that there are many ways to map bytes to unicode text bytes are machine-readable valueswhile text is human-readable format sitting in between is an encoding that maps given sequence of bytes to given sequence of text characters howeverthere are multiple such encodings (ascii is only one of themthe same sequence of bytes represents completely different text characters when mapped using different encodingssobytes must be decoded using the same character set with which they were encoded it' not possible to get text from bytes without knowing how the bytes should be decoded if we receive unknown bytes without specified encodingthe best we can do is guess what format they are encoded inand we may be wrong converting bytes to text if we have an array of bytes from somewherewe can convert it to unicode using the decode method on the bytes class this method accepts string for the name of the character encoding there are many such namescommon ones for western languages include asciiutf- and latin- the sequence of bytes (in hex) actually represents the characters of the word cliche in the latin- encoding the following example will encode this sequence of bytes and convert it to unicode string using the latin- encodingcharacters '\ \ \ \ \ \xe print(charactersprint(characters decode("latin- ")
3,471
the first line creates bytes objectthe character immediately before the string tells us that we are defining bytes object instead of normal unicode string within the stringeach byte is specified using--in this case-- hexadecimal number the \ character escapes within the byte stringand each say"the next two characters represent byte using hexadecimal digits provided we are using shell that understands the latin- encodingthe two print calls will output the following stringsb'clich\xe cliche the first print statement renders the bytes for ascii characters as themselves the unknown (unknown to asciithat ischaracter stays in its escaped hex format the output includes character at the beginning of the line to remind us that it is bytes representationnot string the next call decodes the string using latin- encoding the decode method returns normal (unicodestring with the correct characters howeverif we had decoded this same string using the cyrillic "iso - encodingwe' have ended up with the string 'clichshch'this is because the \xe byte maps to different characters in the two encodings converting text to bytes if we need to convert incoming bytes into unicodeclearly we're also going to have situations where we convert outgoing unicode into byte sequences this is done with the encode method on the str classwhichlike the decode methodrequires character set the following code creates unicode string and encodes it in different character setscharacters "clicheprint(characters encode("utf- ")print(characters encode("latin- ")print(characters encode("cp ")print(characters encode("ascii")the first three encodings create different set of bytes for the accented character the fourth one can' even handle that byteb'clich\xc \xa 'clich\xe 'clich\ traceback (most recent call last)
3,472
file " _decode_unicode py"line in print(characters encode("ascii")unicodeencodeerror'asciicodec can' encode character '\xe in position ordinal not in range( do you understand the importance of encoding nowthe accented character is represented as different byte for each encodingif we use the wrong one when we are decoding bytes to textwe get the wrong character the exception in the last case is not always the desired behaviorthere may be cases where we want the unknown characters to be handled in different way the encode method takes an optional string argument named errors that can define how such characters should be handled this string can be one of the followingstrict replace ignore xmlcharrefreplace the strict replacement strategy is the default we just saw when byte sequence is encountered that does not have valid representation in the requested encodingan exception is raised when the replace strategy is usedthe character is replaced with different characterin asciiit is question markother encodings may use different symbolssuch as an empty box the ignore strategy simply discards any bytes it doesn' understandwhile the xmlcharrefreplace strategy creates an xml entity representing the unicode character this can be useful when converting unknown strings for use in an xml document here' how each of the strategies affects our sample wordstrategy "clicheencode("ascii"strategyreplace ignore xmlcharrefreplace 'clich? 'clichb'clich&# ;it is possible to call the str encode and bytes decode methods without passing an encoding string the encoding will be set to the default encoding for the current platform this will depend on the current operating system and locale or regional settingsyou can look it up using the sys getdefaultencoding(function it is usually good idea to specify the encoding explicitlythoughsince the default encoding for platform may changeor the program may one day be extended to work on text from wider variety of sources
3,473
if you are encoding text and don' know which encoding to useit is best to use the utf- encoding utf- is able to represent any unicode character in modern softwareit is de facto standard encoding to ensure documents in any language--or even multiple languages--can be exchanged the various other possible encodings are useful for legacy documents or in regions that still use different character sets by default the utf- encoding uses one byte to represent ascii and other common charactersand up to four bytes for more complex characters utf- is special because it is backwards-compatible with asciiany ascii document encoded using utf- will be identical to the original ascii document can never remember whether to use encode or decode to convert from binary bytes to unicode always wished these methods were named "to_binaryand "from_binaryinstead if you have the same problemtry mentally replacing the word "codewith "binary""enbinaryand "debinaryare pretty close to "to_binaryand "from_binaryi have saved lot of time by not looking up the method help files since devising this mnemonic mutable byte strings the bytes typelike stris immutable we can use index and slice notation on bytes object and search for particular sequence of bytesbut we can' extend or modify them this can be very inconvenient when dealing with /oas it is often necessary to buffer incoming or outgoing bytes until they are ready to be sent for exampleif we are receiving data from socketit may take several recv calls before we have received an entire message this is where the bytearray built-in comes in this type behaves something like listexcept it only holds bytes the constructor for the class can accept bytes object to initialize it the extend method can be used to append another bytes object to the existing array (for examplewhen more data comes from socket or other / channelslice notation can be used on bytearray to modify the item inline for examplethis code constructs bytearray from bytes object and then replaces two bytesb bytearray( "abcdefgh" [ : "\ \xa print(bthe output looks like thisbytearray( 'abcd\ \xa gh'
3,474
be carefulif we want to manipulate single element in the bytearrayit will expect us to pass an integer between and inclusive as the value this integer represents specific bytes pattern if we try to pass character or bytes objectit will raise an exception single byte character can be converted to an integer using the ord (short for ordinalfunction this function returns the integer representation of single characterb bytearray( 'abcdef' [ ord( ' ' [ print(bthe output looks like thisbytearray( 'abcgdf'after constructing the arraywe replace the character at index (the fourth characteras indexing starts at as with listswith byte this integer was returned by the ord function and is the ascii character for the lowercase for illustrationwe also replaced the next character up with the byte number which maps to the ascii character for the uppercase the bytearray type has methods that allow it to behave like list (we can append integer bytes to itfor example)but also like bytes objectwe can use methods like count and find the same way they would behave on bytes or str object the difference is that bytearray is mutable typewhich can be useful for building up complex sequences of bytes from specific input source regular expressions you know what' really hard to do using object-oriented principlesparsing strings to match arbitrary patternsthat' what there have been fair number of academic papers written in which object-oriented design is used to set up string parsingbut the result is always very verbose and hard to readand they are not widely used in practice in the real worldstring parsing in most programming languages is handled by regular expressions these are not verbosebutboyare they ever hard to readat least until you learn the syntax even though regular expressions are not object orientedthe python regular expression library provides few classes and objects that you can use to construct and run regular expressions
3,475
regular expressions are used to solve common problemgiven stringdetermine whether that string matches given pattern andoptionallycollect substrings that contain relevant information they can be used to answer questions likeis this string valid urlwhat is the date and time of all warning messages in log filewhich users in /etc/passwd are in given groupwhat username and document were requested by the url visitor typedthere are many similar scenarios where regular expressions are the correct answer many programmers have made the mistake of implementing complicated and fragile string parsing libraries because they didn' know or wouldn' learn regular expressions in this sectionwe'll gain enough knowledge of regular expressions to not make such mistakesmatching patterns regular expressions are complicated mini-language they rely on special characters to match unknown stringsbut let' start with literal characterssuch as lettersnumbersand the space characterwhich always match themselves let' see basic exampleimport re search_string "hello worldpattern "hello worldmatch re match(patternsearch_stringif matchprint("regex matches"the python standard library module for regular expressions is called re we import it and set up search string and pattern to search forin this casethey are the same string since the search string matches the given patternthe conditional passes and the print statement executes bear in mind that the match function matches the pattern to the beginning of the string thusif the pattern were "ello world"no match would be found with confusing asymmetrythe parser stops searching as soon as it finds matchso the pattern "hello womatches successfully let' build small example program to demonstrate these differences and help us learn other regular expression syntaximport sys
3,476
import re pattern sys argv[ search_string sys argv[ match re match(patternsearch_stringif matchtemplate "'{}matches pattern '{}'elsetemplate "'{}does not match pattern '{}'print(template format(search_stringpattern)this is just generic version of the earlier example that accepts the pattern and search string from the command line we can see how the start of the pattern must matchbut value is returned as soon as match is found in the following command-line interactionpython regex_generic py "hello worl"hello world'hello worldmatches pattern 'hello worlpython regex_generic py "ello world"hello world'hello worlddoes not match pattern 'ello worldwe'll be using this script throughout the next few sections while the script is always invoked with the command line python regex_generic py """we'll only see the output in the following examplesto conserve space if you need control over whether items happen at the beginning or end of line (or if there are no newlines in the stringat the beginning and end of the string)you can use the and characters to represent the start and end of the string respectively if you want pattern to match an entire stringit' good idea to include both of these'hello worldmatches pattern '^hello world$'hello worldoes not match pattern '^hello world$matching selection of characters let' start with matching an arbitrary character the period characterwhen used in regular expression patterncan match any single character using period in the string means you don' care what the character isjust that there is character there for example'hello worldmatches pattern 'hel world'helpo worldmatches pattern 'hel world
3,477
'hel worldmatches pattern 'hel world'helo worlddoes not match pattern 'hel worldnotice how the last example does not match because there is no character at the period' position in the pattern that' all well and goodbut what if we only want few specific characters to matchwe can put set of characters inside square brackets to match any one of those characters so if we encounter the string [abcin regular expression patternwe know that those five (including the two square bracketscharacters will only match one character in the string being searchedand furtherthat this one character will be either an aa bor see few examples'hello worldmatches pattern 'hel[lp] world'helpo worldmatches pattern 'hel[lp] world'helpo worlddoes not match pattern 'hel[lp] worldthese square bracket sets should be named character setsbut they are more often referred to as character classes oftenwe want to include large range of characters inside these setsand typing them all out can be monotonous and error-prone fortunatelythe regular expression designers thought of this and gave us shortcut the dash characterin character setwill create range this is especially useful if you want to match "all lower case letters""all letters"or "all numbersas follows'hello worlddoes not match pattern 'hello [ -zworld'hello worldmatches pattern 'hello [ -zworld'hello worldmatches pattern 'hello [ -za-zworld'hello worldmatches pattern 'hello [ -za- - worldthere are other ways to match or exclude individual charactersbut you'll need to find more comprehensive tutorial via web search if you want to find out what they areescaping characters if putting period character in pattern matches any arbitrary characterhow do we match just period in stringone way might be to put the period inside square brackets to make character classbut more generic method is to use backslashes to escape it here' regular expression to match two digit decimal numbers between and ' matches pattern ' [ - ][ - ]' does not match pattern ' [ - ][ - ]' , does not match pattern ' [ - ][ - ]
3,478
for this patternthe two characters match the single character if the period character is missing or is different characterit does not match this backslash escape sequence is used for variety of special characters in regular expressions you can use \to insert square bracket without starting character classand \to insert parenthesiswhich we'll later see is also special character more interestinglywe can also use the escape symbol followed by character to represent special characters such as newlines (\ )and tabs (\tfurthersome character classes can be represented more succinctly using escape strings\ represents whitespace characters\ represents lettersnumbersand underscoreand \ represents digit'(abc]matches pattern '\(abc\] amatches pattern '\ \ \ '\ ndoes not match pattern '\ \ \ ' nmatches pattern '\ \ \wmatching multiple characters with this informationwe can match most strings of known lengthbut most of the time we don' know how many characters to match inside pattern regular expressions can take care of thistoo we can modify pattern by appending one of several hard-to-remember punctuation symbols to match multiple characters the asterisk (*character says that the previous pattern can be matched zero or more times this probably sounds sillybut it' one of the most useful repetition characters before we explore whyconsider some silly examples to make sure we understand what it does'hellomatches pattern 'hel* 'heomatches pattern 'hel* 'helllllomatches pattern 'hel*osothe character in the pattern says that the previous pattern (the characteris optionaland if presentcan be repeated as many times as possible to match the pattern the rest of the characters (heand ohave to appear exactly once it' pretty rare to want to match single letter multiple timesbut it gets more interesting if we combine the asterisk with patterns that match multiple characters *for examplewill match any stringwhereas [ - ]matches any collection of lowercase wordsincluding the empty string
3,479
for example' string matches pattern '[ - ][ - ][ - ]*'no matches pattern '[ - ][ - ][ - ]*'matches pattern '[ - ]*the plus (+sign in pattern behaves similarly to an asteriskit states that the previous pattern can be repeated one or more timesbutunlike the asterisk is not optional the question mark (?ensures pattern shows up exactly zero or one timesbut not more let' explore some of these by playing with numbers (remember that \ matches the same character class as [ - ]' matches pattern '\ +\ +' matches pattern '\ +\ +' does not match pattern '\ +\ +' %matches pattern '\ ?\ %' %matches pattern '\ ?\ %' %does not match pattern '\ ?\ %grouping patterns together so far we've seen how we can repeat pattern multiple timesbut we are restricted in what patterns we can repeat if we want to repeat individual characterswe're coveredbut what if we want repeating sequence of charactersenclosing any set of patterns in parenthesis allows them to be treated as single pattern when applying repetition operations compare these patterns'abcccmatches pattern 'abc{ }'abcccdoes not match pattern '(abc){ }'abcabcabcmatches pattern '(abc){ }combined with complex patternsthis grouping feature greatly expands our pattern-matching repertoire here' regular expression that matches simple english sentences'eat matches pattern '[ - ][ - ]*[ - ]+)*$'eat more good food matches pattern '[ - ][ - ]*[ - ]+)*$' good meal matches pattern '[ - ][ - ]*[ - ]+)*$the first word starts with capitalfollowed by zero or more lowercase letters thenwe enter parenthetical that matches single space followed by word of one or more lowercase letters this entire parenthetical is repeated zero or more timesand the pattern is terminated with period there cannot be any other characters after the periodas indicated by the matching the end of string
3,480
we've seen many of the most basic patternsbut the regular expression language supports many more spent my first few years using regular expressions looking up the syntax every time needed to do something it is worth bookmarking python' documentation for the re module and reviewing it frequently there are very few things that regular expressions cannot matchand they should be the first tool you reach for when parsing strings getting information from regular expressions let' now focus on the python side of things the regular expression syntax is the furthest thing from object-oriented programming howeverpython' re module provides an object-oriented interface to enter the regular expression engine we've been checking whether the re match function returns valid object or not if pattern does not matchthat function returns none if it does matchhoweverit returns useful object that we can introspect for information about the pattern so farour regular expressions have answered questions such as "does this string match this pattern?matching patterns is usefulbut in many casesa more interesting question is"if this string matches this patternwhat is the value of relevant substring?if you use groups to identify parts of the pattern that you want to reference lateryou can get them out of the match return value as illustrated in the next examplepattern "^[ -za- ]+@([ - ]*[ - ]+)$search_string "some user@example commatch re match(patternsearch_stringif matchdomain match groups()[ print(domainthe specification describing valid -mail addresses is extremely complicatedand the regular expression that accurately matches all possibilities is obscenely long so we cheated and made simple regular expression that matches some common -mail addressesthe point is that we want to access the domain name (after the signso we can connect to that address this is done easily by wrapping that part of the pattern in parenthesis and calling the groups(method on the object returned by match the groups method returns tuple of all the groups matched inside the patternwhich you can index to access specific value the groups are ordered from left to right howeverbear in mind that groups can be nestedmeaning you can have one or more groups inside another group in this casethe groups are returned in the order of their left-most bracketsso the outermost group will be returned before its inner matching groups
3,481
in addition to the match functionthe re module provides couple other useful functionssearchand findall the search function finds the first instance of matching patternrelaxing the restriction that the pattern start at the first letter of the string note that you can get similar effect by using match and putting character at the front of the pattern to match any characters between the start of the string and the pattern you are looking for the findall function behaves similarly to searchexcept that it finds all non-overlapping instances of the matching patternnot just the first one basicallyit finds the first matchthen it resets the search to the end of that matching string and finds the next one instead of returning list of match objectsas you would expectit returns list of matching strings or tuples sometimes it' stringssometimes it' tuples it' not very good api at allas with all bad apisyou'll have to memorize the differences and not rely on intuition the type of the return value depends on the number of bracketed groups inside the regular expressionif there are no groups in the patternre findall will return list of stringswhere each value is complete substring from the source string that matches the pattern if there is exactly one group in the patternre findall will return list of strings where each value is the contents of that group if there are multiple groups in the patternthen re findall will return list of tuples where each tuple contains value from matching groupin order when you are designing function calls in your own python librariestry to make the function always return consistent data structure it is often good to design functions that can take arbitrary inputs and process thembut the return value should not switch from single value to listor list of values to list of tuples depending on the input let re findall be lessonthe examples in the following interactive session will hopefully clarify the differencesimport re re findall(' ''abacadefagah'['ab''ac''ad''ag''ah're findall(' )''abacadefagah'[' '' '' '' '' 're findall('( ))''abacadefagah'
3,482
[(' '' ')(' '' ')(' '' ')(' '' ')(' '' ')re findall('(( )))''abacadefagah'[('ab'' '' ')('ac'' '' ')('ad'' '' ')('ag'' '' ')('ah'' '' ')making repeated regular expressions efficient whenever you call one of the regular expression methodsthe engine has to convert the pattern string into an internal structure that makes searching strings fast this conversion takes non-trivial amount of time if regular expression pattern is going to be reused multiple times (for exampleinside for or while loop)it would be better if this conversion step could be done only once this is possible with the re compile method it returns an object-oriented version of the regular expression that has been compiled down and has the methods we've explored (matchsearchfindallalreadyamong others we'll see examples of this in the case study this has definitely been condensed introduction to regular expressions at this pointwe have good feel for the basics and will recognize when we need to do further research if we have string pattern matching problemregular expressions will almost certainly be able to solve them for us howeverwe may need to look up new syntaxes in more comprehensive coverage of the topic but now we know what to look forlet' move on to completely different topicserializing data for storage serializing objects nowadayswe take the ability to write data to file and retrieve it at an arbitrary later date for granted as convenient as this is (imagine the state of computing if we couldn' store anything!)we often find ourselves converting data we have stored in nice object or design pattern in memory into some kind of clunky text or binary format for storagetransfer over the networkor remote invocation on distant server the python pickle module is an object-oriented way to store objects directly in special storage format it essentially converts an object (and all the objects it holds as attributesinto sequence of bytes that can be stored or transported however we see fit for basic workthe pickle module has an extremely simple interface it is comprised of four basic functions for storing and loading datatwo for manipulating file-like objectsand two for manipulating bytes objects (the latter are just shortcuts to the file-like interfaceso we don' have to create bytesio file-like object ourselves
3,483
the dump method accepts an object to be written and file-like object to write the serialized bytes to this object must have write method (or it wouldn' be file-like)and that method must know how to handle bytes argument (so file opened for text output wouldn' workthe load method does exactly the oppositeit reads serialized object from file-like object this object must have the proper file-like read and readline argumentseach of which mustof coursereturn bytes the pickle module will load the object from these bytes and the load method will return the fully reconstructed object here' an example that stores and then loads some data in list objectimport pickle some_data [" list""containing" "values including another list"["inner""list"]with open("pickled_list"'wb'as filepickle dump(some_datafilewith open("pickled_list"'rb'as fileloaded_data pickle load(fileprint(loaded_dataassert loaded_data =some_data this code works as advertisedthe objects are stored in the file and then loaded from the same file in each casewe open the file using with statement so that it is automatically closed the file is first opened for writing and then second time for readingdepending on whether we are storing or loading data the assert statement at the end would raise an error if the newly loaded object is not equal to the original object equality does not imply that they are the same object indeedif we print the id(of both objectswe would discover they are different howeverbecause they are both lists whose contents are equalthe two lists are also considered equal the dumps and loads functions behave much like their file-like counterpartsexcept they return or accept bytes instead of file-like objects the dumps function requires only one argumentthe object to be storedand it returns serialized bytes object the loads function requires bytes object and returns the restored object the 'scharacter in the method names is short for stringit' legacy name from ancient versions of pythonwhere str objects were used instead of bytes
3,484
both dump methods accept an optional protocol argument if we are saving and loading pickled objects that are only going to be used in python programswe don' need to supply this argument unfortunatelyif we are storing objects that may be loaded by older versions of pythonwe have to use an older and less efficient protocol this should not normally be an issue usuallythe only program that would load pickled object would be the same one that stored it pickle is an unsafe formatso we don' want to be sending it unsecured over the internet to unknown interpreters the argument supplied is an integer version number the default version is number representing the current highly efficient storage system used by python pickling the number is the older versionwhich will store an object that can be loaded on all interpreters back to python as is the oldest of python that is still widely used in the wildversion pickling is normally sufficient versions and are supported on older interpreters is an ascii formatwhile is binary format there is also an optimized version that may one day become the default as rule of thumbthenif you know that the objects you are pickling will only be loaded by python program (for exampleonly your program will be loading them)use the default pickling protocol if they may be loaded by unknown interpreterspass protocol value of unless you really believe they may need to be loaded by an archaic version of python if we do pass protocol to dump or dumpswe should use keyword argument to specify itpickle dumps(my_objectprotocol= this is not strictly necessaryas the method only accepts two argumentsbut typing out the full keyword argument reminds readers of our code what the purpose of the number is having random integer in the method call would be hard to read two whatstore two copies of the objectmayberemembercode should always be readable in pythonless code is often more readable than longer codebut not always be explicit it is possible to call dump or load on single open file more than once each call to dump will store single object (plus any objects it is composed of or contains)while call to load will load and return just one object so for single fileeach separate call to dump when storing the object should have an associated call to load when restoring at later date customizing pickles with most common python objectspickling "just worksbasic primitives such as integersfloatsand strings can be pickledas can any container objectsuch as lists or dictionariesprovided the contents of those containers are also picklable furtherand importantlyany object can be pickledso long as all of its attributes are also picklable
3,485
so what makes an attribute unpicklableusuallyit has something to do with timesensitive attributes that it would not make sense to load in the future for exampleif we have an open network socketopen filerunning threador database connection stored as an attribute on an objectit would not make sense to pickle these objectsa lot of operating system state would simply be gone when we attempted to reload them later we can' just pretend thread or socket connection exists and make it appearnowe need to somehow customize how such transient data is stored and restored here' class that loads the contents of web page every hour to ensure that they stay up to date it uses the threading timer class to schedule the next updatefrom threading import timer import datetime from urllib request import urlopen class updatedurldef __init__(selfurl)self url url self contents 'self last_updated none self update(def update(self)self contents urlopen(self urlread(self last_updated datetime datetime now(self schedule(def schedule(self)self timer timer( self updateself timer setdaemon(trueself timer start(the urlcontentsand last_updated are all pickleablebut if we try to pickle an instance of this classthings go little nutty on the self timer instanceu updatedurl(import pickle serialized pickle dumps(utraceback (most recent call last)file ""line in serialized pickle dumps(u_pickle picklingerrorcan' pickle attribute lookup lock on _thread failed
3,486
that' not very useful errorbut it looks like we're trying to pickle something we shouldn' be that would be the timer instancewe're storing reference to self timer in the schedule methodand that attribute cannot be serialized when pickle tries to serialize an objectit simply tries to store the object' __dict__ attribute__dict__ is dictionary mapping all the attribute names on the object to their values luckilybefore checking __dict__pickle checks to see whether __getstate__ method exists if it doesit will store the return value of that method instead of the __dict__ let' add __getstate__ method to our updatedurl class that simply returns copy of the __dict__ without timerdef __getstate__(self)new_state self __dict__ copy(if 'timerin new_statedel new_state['timer'return new_state if we pickle the object nowit will no longer fail and we can even successfully restore that object using loads howeverthe restored object doesn' have timer attributeso it will not be refreshing the content like it is designed to do we need to somehow create new timer (to replace the missing onewhen the object is unpickled as we might expectthere is complementary __setstate__ method that can be implemented to customize unpickling this method accepts single argumentwhich is the object returned by __getstate__ if we implement both methods__ getstate__ is not required to return dictionarysince __setstate__ will know what to do with whatever object __getstate__ chooses to return in our casewe simply want to restore the __dict__and then create new timerdef __setstate__(selfdata)self __dict__ data self schedule(the pickle module is very flexible and provides other tools to further customize the pickling process if you need them howeverthese are beyond the scope of this book the tools we've covered are sufficient for many basic pickling tasks objects to be pickled are normally relatively simple data objectswe would not likely pickle an entire running program or complicated design patternfor example
3,487
serializing web objects it is not good idea to load pickled object from an unknown or untrusted source it is possible to inject arbitrary code into pickled file to maliciously attack computer via the pickle another disadvantage of pickles is that they can only be loaded by other python programsand cannot be easily shared with services written in other languages there are many formats that have been used for this purpose over the years xml (extensible markup languageused to be very popularespecially with java developers yaml (yet another markup languageis another format that you may see referenced occasionally tabular data is frequently exchanged in the csv (comma separated valueformat many of these are fading into obscurity and there are many more that you will encounter over time python has solid standard or third-party libraries for all of them before using such libraries on untrusted datamake sure to investigate security concerns with each of them xml and yamlfor exampleboth have obscure features thatused maliciouslycan allow arbitrary commands to be executed on the host machine these features may not be turned off by default do your research javascript object notation (jsonis human readable format for exchanging primitive data json is standard format that can be interpreted by wide array of heterogeneous client systems hencejson is extremely useful for transmitting data between completely decoupled systems furtherjson does not have any support for executable codeonly data can be serializedthusit is more difficult to inject malicious statements into it because json can be easily interpreted by javascript enginesit is often used for transmitting data from web server to javascript-capable web browser if the web application serving the data is written in pythonit needs way to convert internal data into the json format there is module to do thispredictably named json this module provides similar interface to the pickle modulewith dumploaddumpsand loads functions the default calls to these functions are nearly identical to those in pickleso let us not repeat the details there are couple differencesobviouslythe output of these calls is valid json notationrather than pickled object in additionthe json functions operate on str objectsrather than bytes thereforewhen dumping to or loading from filewe need to create text files rather than binary ones
3,488
the json serializer is not as robust as the pickle moduleit can only serialize basic types such as integersfloatsand stringsand simple containers such as dictionaries and lists each of these has direct mapping to json representationbut json is unable to represent classesmethodsor functions it is not possible to transmit complete objects in this format because the receiver of an object we have dumped to json format is normally not python objectit would not be able to understand classes or methods in the same way that python doesanyway in spite of the for object in its namejson is data notationobjectsas you recallare composed of both data and behavior if we do have objects for which we want to serialize only the datawe can always serialize the object' __dict__ attribute or we can semiautomate this task by supplying custom code to create or parse json serializable dictionary from certain types of objects in the json moduleboth the object storing and loading functions accept optional arguments to customize the behavior the dump and dumps methods accept poorly named cls (short for classwhich is reserved keywordkeyword argument if passedthis should be subclass of the jsonencoder classwith the default method overridden this method accepts an arbitrary object and converts it to dictionary that json can digest if it doesn' know how to process the objectwe should call the super(methodso that it can take care of serializing basic types in the normal way the load and loads methods also accept such cls argument that can be subclass of the inverse classjsondecoder howeverit is normally sufficient to pass function into these methods using the object_hook keyword argument this function accepts dictionary and returns an objectif it doesn' know what to do with the input dictionaryit can return it unmodified let' look at an example imagine we have the following simple contact class that we want to serializeclass contactdef __init__(selffirstlast)self first first self last last @property def full_name(self)return("{{}format(self firstself last)
3,489
we could just serialize the __dict__ attributec contact("john""smith"json dumps( __dict__'{"last""smith""first""john"}but accessing special (double-underscoreattributes in this fashion is kind of crude alsowhat if the receiving code (perhaps some javascript on web pagewanted that full_name property to be suppliedof coursewe could construct the dictionary by handbut let' create custom encoder insteadimport json class contactencoder(json jsonencoder)def default(selfobj)if isinstance(objcontact)return {'is_contact'true'first'obj first'last'obj last'full'obj full_namereturn super(default(objthe default method basically checks to see what kind of object we're trying to serializeif it' contactwe convert it to dictionary manuallyotherwisewe let the parent class handle serialization (by assuming that it is basic typewhich json knows how to handlenotice that we pass an extra attribute to identify this object as contactsince there would be no way to tell upon loading it this is just conventionfor more generic serialization mechanismit might make more sense to store string type in the dictionaryor possibly even the full class nameincluding package and module remember that the format of the dictionary depends on the code at the receiving endthere has to be an agreement as to how the data is going to be specified we can use this class to encode contact by passing the class (not an instantiated objectto the dump or dumps functionc contact("john""smith"json dumps(ccls=contactencoder'{"is_contact"true"last""smith""full""john smith""first""john"}
3,490
for decodingwe can write function that accepts dictionary and checks the existence of the is_contact variable to decide whether to convert it to contactdef decode_contact(dic)if dic get('is_contact')return contact(dic['first']dic['last']elsereturn dic we can pass this function to the load or loads function using the object_hook keyword argumentdata ('{"is_contact"true"last""smith",'"full""john smith""first""john"}' json loads(dataobject_hook=decode_contactc full_name 'john smithcase study let' build basic regular expression-powered templating engine in python this engine will parse text file (such as an html pageand replace certain directives with text calculated from the input to those directives this is about the most complicated task we would want to do with regular expressionsindeeda full-fledged version of this would likely utilize proper language parsing mechanism consider the following input file/*include header html **this is the title of the front page /*include menu html **my name is /*variable name **this is the content of my front page it goes below the menu favourite books /*loopover book_list **/*loopvar **/*endloop **/*include footer html **copyright &copytoday
3,491
this file contains "tagsof the form /***where the data is an optional single word and the directives areincludecopy the contents of another file here variableinsert the contents of variable here loopoverrepeat the contents of the loop for variable that is list endloopsignal the end of looped text loopvarinsert single value from the list being looped over this template will render different page depending which variables are passed into it these variables will be passed in from so-called context file this will be encoded as json object with keys representing the variables in question my context file might look like thisbut you would derive your own"name""dusty""book_list""thief of time""the thief""snow crash""lathe of heavenbefore we get into the actual string processinglet' throw together some object-oriented boilerplate code for processing files and grabbing data from the command lineimport re import sys import json from pathlib import path directive_re re compiler'/\*\*\ *(include|variable|loopover|endloop|loopvar) '\ *([*]*)\ *\*\*/'class templateenginedef __init__(selfinfilenameoutfilenamecontextfilename)self template open(infilenameread(self working_dir path(infilenameabsolute(parent self pos self outfile open(outfilename' '
3,492
with open(contextfilenameas contextfileself context json load(contextfiledef process(self)print("processing "if __name__ ='__main__'infilenameoutfilenamecontextfilename sys argv[ :engine templateengine(infilenameoutfilenamecontextfilenameengine process(this is all pretty basicwe create class and initialize it with some variables passed in on the command line notice how we try to make the regular expression little bit more readable by breaking it across two lineswe use raw strings (the prefix)so we don' have to double escape all our backslashes this is common in regular expressionsbut it' still mess (regular expressions always arebut they're often worth it the pos indicates the current character in the content that we are processingwe'll see lot more of it in moment now "all that' leftis to implement that process method there are few ways to do this let' do it in fairly explicit way the process method has to find each directive that matches the regular expression and do the appropriate work with it howeverit also has to take care of outputting the normal text beforeafterand between each directive to the output fileunmodified one good feature of the compiled version of regular expressions is that we can tell the search method to start searching at specific position by passing the pos keyword argument if we temporarily define doing the appropriate work with directive as "ignore the directive and delete it from the output file"our process loop looks quite simpledef process(self)match directive_re search(self templatepos=self poswhile matchself outfile write(self template[self pos:match start()]self pos match end(match directive_re search(self templatepos=self posself outfile write(self template[self pos:]
3,493
in englishthis function finds the first string in the text that matches the regular expressionoutputs everything from the current position to the start of that matchand then advances the position to the end of aforesaid match once it' out of matchesit outputs everything since the last position of courseignoring the directive is pretty useless in templating engineso let' set up replace that position advancing line with code that delegates to different method on the class depending on the directivedef process(self)match directive_re search(self templatepos=self poswhile matchself outfile write(self template[self pos:match start()]directiveargument match groups(method_name 'process_{}format(directivegetattr(selfmethod_name)(matchargumentmatch directive_re search(self templatepos=self posself outfile write(self template[self pos:]so we grab the directive and the single argument from the regular expression the directive becomes method name and we dynamically look up that method name on the self object ( little error processing here in case the template writer provides an invalid directive would be betterwe pass the match object and argument into that method and assume that method will deal with everything appropriatelyincluding moving the pos pointer now that we've got our object-oriented architecture this farit' actually pretty simple to implement the methods that are delegated to the include and variable directives are totally straightforwarddef process_include(selfmatchargument)with (self working_dir argumentopen(as includefileself outfile write(includefile read()self pos match end(def process_variable(selfmatchargument)self outfile write(self context get(argument'')self pos match end(the first simply looks up the included file and inserts the file contentswhile the second looks up the variable name in the context dictionary (which was loaded from json in the __init__ method)defaulting to an empty string if it doesn' exist
3,494
the three methods that deal with looping are bit more intenseas they have to share state between the three of them for simplicity ( ' sure you're eager to see the end of this long we're almost there!)we'll handle this as instance variables on the class itself as an exerciseyou might want to consider better ways to architect thisespecially after reading the next three def process_loopover(selfmatchargument)self loop_index self loop_list self context get(argument[]self pos self loop_pos match end(def process_loopvar(selfmatchargument)self outfile write(self loop_list[self loop_index]self pos match end(def process_endloop(selfmatchargument)self loop_index + if self loop_index >len(self loop_list)self pos match end(del self loop_index del self loop_list del self loop_pos elseself pos self loop_pos when we encounter the loopover directivewe don' have to output anythingbut we do have to set the initial state on three variables the loop_list variable is assumed to be list pulled from the context dictionary the loop_index variable indicates what position in that list should be output in this iteration of the loopwhile loop_pos is stored so we know where to jump back to when we get to the end of the loop the loopvar directive outputs the value at the current position in the loop_list variable and skips to the end of the directive note that it doesn' increment the loop index because the loopvar directive could be called multiple times inside loop the endloop directive is more complicated it determines whether there are more elements in the loop_listif there areit just jumps back to the start of the loopincrementing the index otherwiseit resets all the variables that were being used to process the loop and jumps to the end of the directive so the engine can carry on with the next match
3,495
note that this particular looping mechanism is very fragileif template designer were to try nesting loops or forget an endloop callit would go poorly for them we would need lot more error checking and probably want to store more loop state to make this production platform but promised that the end of the was nighso let' just head to the exercisesafter seeing how our sample template is rendered with its contextthis is the title of the front page first link second link my name is dusty this is the content of my front page it goes below the menu favourite books thief of time the thief snow crash lathe of heaven copyright &copytoday there are some weird newline effects due to the way we planned our templatebut it works as expected exercises we've covered wide variety of topics in this from strings to regular expressionsto object serializationand back again now it' time to consider how these ideas can be applied to your own code
3,496
python strings are very flexibleand python is an extremely powerful tool for string-based manipulations if you don' do lot of string processing in your daily worktry designing tool that is exclusively intended for manipulating strings try to come up with something innovativebut if you're stuckconsider writing web log analyzer (how many requests per hourhow many people visit more than five pages?or template tool that replaces certain variable names with the contents of other files spend lot of time toying with the string formatting operators until you've got the syntax memorized write bunch of template strings and objects to pass into the format functionand see what kind of output you get try the exotic formatting operatorssuch as percentage or hexadecimal notation try out the fill and alignment operatorsand see how they behave differently for integersstringsand floats consider writing class of your own that has __format__ methodwe didn' discuss this in detailbut explore just how much you can customize formatting make sure you understand the difference between bytes and str objects the distinction is very complicated in older versions of python (there was no bytesand str acted like both bytes and str unless we needed non-ascii characters in which case there was separate unicode objectwhich was similar to python ' str class it' even more confusing than it sounds!it' clearer nowadaysbytes is for binary dataand str is for character data the only tricky part is knowing how and when to convert between the two for practicetry writing text data to file opened for writing bytes (you'll have to encode the text yourself)and then reading from the same file do some experimenting with bytearraysee how it can act both like bytes object and list or container object at the same time try writing to buffer that holds data in the bytes array until it is certain length before returning it you can simulate the code that puts data into the buffer by using time sleep calls to ensure data doesn' arrive too quickly study regular expressions online study them some more especially learn about named groups greedy versus lazy matchingand regex flagsthree features that we didn' cover in this make conscious decisions about when not to use them many people have very strong opinions about regular expressions and either overuse them or refuse to use them at all try to convince yourself to use them only when appropriateand figure out when that is if you've ever written an adapter to load small amounts of data from file or database and convert it to an objectconsider using pickle instead pickles are not efficient for storing massive amounts of databut they can be useful for loading configuration or other simple objects try coding it multiple waysusing picklea text fileor small database which do you find easiest to work with
3,497
try experimenting with pickling datathen modifying the class that holds the dataand loading the pickle into the new class what workswhat doesn'tis there way to make drastic changes to classsuch as renaming an attribute or splitting it into two new attributes and still get the data out of an older pickle(hinttry placing private pickle version number on each object and update it each time you change the classyou can then put migration path in __setstate__ if you do any web development at alldo some experimenting with the json serializer personallyi prefer to serialize only standard json serializable objectsrather than writing custom encoders or object_hooksbut the desired effect really depends on the interaction between the frontend (javascripttypicallyand backend code create some new directives in the templating engine that take more than one or an arbitrary number of arguments you might need to modify the regular expression or add new ones have look at the django project' online documentationand see if there are any other template tags you' like to work with try mimicking their filter syntax instead of using the variable tag revisit this when you've studied iteration and coroutines and see if you can come up with more compact way of representing the state between related directivessuch as the loop summary we've covered string manipulationregular expressionsand object serialization in this hardcoded strings and program variables can be combined into outputtable strings using the powerful string formatting system it is important to distinguish between binary and textual data and bytes and str have specific purposes that must be understood both are immutablebut the bytearray type can be used when manipulating bytes regular expressions are complex topicbut we scratched the surface there are many ways to serialize python datapickles and json are two of the most popular in the next we'll look at design pattern that is so fundamental to python programming that it has been given special syntax supportthe iterator pattern
3,498
we've discussed how many of python' built-ins and idioms that seemat first blushto be non-object-oriented are actually providing access to major objects under the hood in this we'll discuss how the for loop that seems so structured is actually lightweight wrapper around set of object-oriented principles we'll also see variety of extensions to this syntax that automatically create even more types of object we will coverwhat design patterns are the iterator protocol--one of the most powerful design patterns listsetand dictionary comprehensions generators and coroutines design patterns in brief when engineers and architects decide to build bridgeor toweror buildingthey follow certain principles to ensure structural integrity there are various possible designs for bridges (suspension or cantileverfor example)but if the engineer doesn' use one of the standard designsand doesn' have brilliant new designit is likely the bridge he/she designs will collapse design patterns are an attempt to bring this same formal definition for correctly designed structures to software engineering there are many different design patterns to solve different general problems people who create design patterns first identify common problem faced by developers in wide variety of situations they then suggest what might be considered the ideal solution for that problemin terms of object-oriented design
3,499
knowing design pattern and choosing to use it in our software does nothoweverguarantee that we are creating "correctsolution in the quebec bridge (to this daythe longest cantilever bridge in the worldcollapsed before construction was completedbecause the engineers who designed it grossly underestimated the weight of the steel used to construct it similarlyin software developmentwe may incorrectly choose or apply design patternand create software that "collapsesunder normal operating situations or when stressed beyond its original design limits any one design pattern proposes set of objects interacting in specific way to solve general problem the job of the programmer is to recognize when they are facing specific version of that problemand to adapt the general design in their solution in this we'll be covering the iterator design pattern this pattern is so powerful and pervasive that the python developers have provided multiple syntaxes to access the object-oriented principles underlying the pattern we will be covering other design patterns in the next two some of them have language support and some don'tbut none of them is as intrinsically part of the python coder' daily life as the iterator pattern iterators in typical design pattern parlancean iterator is an object with next(method and done(methodthe latter returns true if there are no items left in the sequence in programming language without built-in support for iteratorsthe iterator would be looped over like thiswhile not iterator done()item iterator next(do something with the item in pythoniteration is special featureso the method gets special name__next__ this method can be accessed using the next(iteratorbuilt-in rather than done methodthe iterator protocol raises stopiteration to notify the loop that it has completed finallywe have the much more readable for item in iterator syntax to actually access items in an iterator instead of messing around with while loop let' look at these in more detail