id
int64
0
25.6k
text
stringlengths
0
4.59k
3,500
the iterator protocol the abstract base class iteratorin the collections abc moduledefines the iterator protocol in python as mentionedit must have __next__ method that the for loop (and other features that support iterationcan call to get new element from the sequence in additionevery iterator must also fulfill the it...
3,501
this example defines an capitaliterable class whose job is to loop over each of the words in string and output them with the first letter capitalized most of the work of that iterable is passed to the capitaliterator implementation the canonical way to interact with this iterator is as followsiterable capitaliterable('...
3,502
of coursewe already know much simpler syntax for constructing an iterator from an iterablefor in iterableprint(ithe quick brown fox jumps over the lazy dog as you can seethe for statementin spite of not looking terribly object-orientedis actually shortcut to some obviously object-oriented design principles keep this in...
3,503
let' have look at one of those common operationsnamelyconverting list of items into list of related items specificallylet' assume we just read list of strings from fileand now we want to convert it to list of integers we know every item in the list is an integerand we want to do some activity (saycalculate an averageon...
3,504
shortened the name of the variable from num to and the result variable to output_ ints so it would still fit on one line other than thisall that' different between this example and the previous one is the if len( part this extra code excludes any strings with more than two characters the if statement is applied before ...
3,505
rememberthe tools we are provided with should not be abusedalways pick the right tool for the jobwhich is always to write maintainable code set and dictionary comprehensions comprehensions aren' restricted to lists we can use similar syntax with braces to create sets and dictionaries as well let' start with sets one wa...
3,506
nowwe have dictionaryand can look up books by title using the normal syntax in summarycomprehensions are not advanced pythonnor are they "non-objectorientedtools that should be avoided they are simply more concise and optimized syntax for creating listsetor dictionary from an existing sequence generator expressions som...
3,507
the following code parses log file in the previously presented formatand outputs new log file that contains only the warning linesimport sys inname sys argv[ outname sys argv[ with open(innameas infilewith open(outname" "as outfilewarnings ( for in infile if 'warningin lfor in warningsoutfile write(lthis program takes ...
3,508
generators generator expressions are actually sort of comprehension toothey compress the more advanced (this time it really is more advanced!generator syntax into one line the greater generator syntax looks even less object-oriented than anything we've seenbut we'll discover that once againit is simple syntax shortcut ...
3,509
self insequence insequence def __iter__(self)return self def __next__(self) self insequence readline(while and 'warningnot in ll self insequence readline(if not lraise stopiteration return replace('\twarning'''with open(innameas infilewith open(outname" "as outfilefilter warningfilter(infilefor in filteroutfile write(l...
3,510
filter warnings_filter(infilefor in filteroutfile write(lokthat' pretty readablemaybe at least it' short but what on earth is going on hereit makes no sense whatsoever and what is yieldanywayin factyield is the key to generators when python sees yield in functionit takes that function and wraps it up in an object not u...
3,511
let' adapt the generator example bit so that instead of accepting sequence of linesit accepts filename this would normally be frowned upon as it ties the object to particular paradigm when possible we should operate on iterators as inputthis way the same function could be used regardless of whether the log lines came f...
3,512
self name name class folder(file)def __init__(selfname)super(__init__(nameself children [root folder(''etc folder('etc'root children append(etcetc children append(file('passwd')etc children append(file('groups')httpd folder('httpd'etc children append(httpdhttpd children append(file('http conf')var folder('var'root chil...
3,513
as an asidesolving the preceding problem without using generator is tricky enough that this problem is common interview question if you answer it as shown like thisbe prepared for your interviewer to be both impressed and somewhat irritated that you answered it so easily they will likely demand that you explain exactly...
3,514
while trueincrement yield score score +increment this code looks like black magic that couldn' possibly workso we'll see it working before going into line-by-line description this simple object could be used by scoring application for baseball team separate tallies could be kept for each teamand their score could be in...
3,515
unlike with generatorsthis yield function looks like it' supposed to return value and assign it to variable this isin factexactly what' happening the coroutine is still paused at the yield statement and waiting to be activated again by another call to next(or ratheras you see in the interactive sessiona call to method ...
3,516
back to log parsing of coursethe previous example could easily have been coded using couple integer variables and calling +increment on them let' look at second example where coroutines actually save us some code this example is somewhat simplified (for pedagogical reasonsversion of problem had to solve in my real job ...
3,517
nowgiven the preceding log filethe problem we need to solve is how to obtain the serial number of any drives that have xfs errors on them this serial number might later be used by data center technician to identify and replace the drive we know we can identify the individual lines using regular expressionsbut we'll hav...
3,518
look at the match_regex coroutine first rememberit doesn' execute any code when it is constructedratherit just creates coroutine object once constructedsomeone outside the coroutine will eventually call next(to start the code runningat which point it stores the state of two variablesfilename and regex it then reads all...
3,519
when calledthe close(method will raise generatorexit exception at the point the coroutine was waiting for value to be sent in it is normally good policy for coroutines to wrap their yield statements in try finally block so that any cleanup tasks (such as closing associated files or socketscan be performed if we need to...
3,520
so in theorygenerators are types of coroutinesfunctions are types of coroutinesand there are coroutines that are neither functions nor generators that' simple enoughehso why does it feel more complicated in pythonin pythongenerators and coroutines are both constructed using syntax that looks like we are constructing fu...
3,521
the first thing we need is dataset to train our algorithm on in production systemyou might scrape list of colors website or survey thousands of people insteadi created simple application that renders random color and asks the user to select one of the preceding nine options to classify it this application is included w...
3,522
we won' go into too much detail about what the algorithm doesratherwe'll focus on some of the ways we can apply the iterator pattern or iterator protocol to this problem let' now write program that performs the following steps in order load the sample data from the file and construct model from it generate random color...
3,523
push the data through pipeline of coroutines even just basic for loop the generator version seems to be most readableso let' add that function to our programfrom random import random def generate_colors(count= )for in range(count)yield (random()random()random()notice how we parameterize the number of colors to generate...
3,524
howeveri strongly recommend not making such optimizations until you have proven that the readable version is too slow now that we have some plumbing in placelet' do the actual -nearest neighbor implementation this seems like good place to use coroutine here it is with some test code to ensure it' yielding sensible valu...
3,525
the sorted call then sorts the results by their first elementwhich is distance this is complicated piece of code and isn' object-oriented at all you may want to break it down into normal for loop to ensure you understand what the generator expression is doing it might also be good exercise to imagine how this code woul...
3,526
this coroutine acceptsas its argumentan existing coroutine in this caseit' an instance of nearest_neighbors this code basically proxies all the values sent into it through that nearest_neighbors instance then it does some processing on the result to get the most common color out of the values that were returned in this...
3,527
you might be wondering"what does this have to do with object-oriented programmingthere isn' even one class in this code!in some waysyou' be rightneither coroutines nor generators are commonly considered object-oriented howeverthe functions that create them return objectsin factyou could think of those functions as cons...
3,528
coroutines abuse the iterator protocol but don' actually fulfill the iterator pattern can you build non-coroutine version of the code that gets serial number from log filetake an object-oriented approach so that you can store an additional state on class you'll learn lot about coroutines if you can create an object tha...
3,529
in the last we were briefly introduced to design patternsand covered the iterator patterna pattern so useful and common that it has been abstracted into the core of the programming language itself in this we'll be reviewing other common patternsand how they are implemented in python as with iterationpython often provid...
3,530
the second option is often suitable alternative to multiple inheritance we can construct core objectand then create decorator around that core since the decorator object has the same interface as the core objectwe can even wrap the new object in other decorators here' how it looks in umlinterface +someaction(core decor...
3,531
clientaddr server accept(respond(clientfinallyserver close(the respond function accepts socket parameter and prompts for data to be sent as replythen sends it to use itwe construct server socket and tell it to listen on port ( picked the port randomlyon the local computer when client connectsit calls the respond functi...
3,532
print("sending { to { }formatdataself socket getpeername()[ ])self socket send(datadef close(self)self socket close(this class decorates socket object and presents the send and close interface to client sockets better decorator would also implement (and possibly customizeall of the remaining socket methods it should pr...
3,533
the send method in this version compresses the incoming data before sending it on to the client now that we have these two decoratorswe can write code that dynamically switches between them when responding this example is not completebut it illustrates the logic we might follow to mix and match decoratorsclientaddr ser...
3,534
print("calling { with { and { }formatfunc __name__argskwargs)return_value func(*args**kwargsprint("executed { in { }msformatfunc __name__time time(now)return return_value return wrapper def test ( , , )print("\ttest called"def test ( , )print("\ttest called"def test ( , )print("\ttest called"time sleep( test log_calls(...
3,535
this syntax allows us to build up decorated function objects dynamicallyjust as we did with the socket exampleif we don' replace the namewe can even keep decorated and non-decorated versions for different situations often these decorators are general modifications that are applied permanently to different functions in ...
3,536
hereit is in umlobserverinterface core observer observer an observer example the observer pattern might be useful in redundant backup system we can write core object that maintains certain valuesand then have one or more observers create serialized copies of that object these copies might be stored in databaseon remote...
3,537
self _update_observers(def _update_observers(self)for observer in self observersobserver(this object has two properties thatwhen setcall the _update_observers method on itself all this method does is loop over the available observers and let each one know that something has changed in this casewe call the observer obje...
3,538
consoleobserver(ii attach( attach( product "gadgetgadget gadget this time when we change the productthere are two sets of outputone for each observer the key idea here is that we can easily add totally different types of observers that back up the data in filedatabaseor internet application at the same time the observe...
3,539
the user code connecting to the strategy pattern simply needs to know that it is dealing with the abstraction interface the actual implementation chosen performs the same taskbut in different wayseither waythe interface is identical strategy example the canonical example of the strategy pattern is sort routinesover the...
3,540
/ for oi in zip(out_img sizein_img sizefor in range(num_tiles[ ])for in range(num_tiles[ ])out_img pastein_imgin_img size[ xin_img size[ yin_img size[ ( + )in_img size[ ( + return out_img class centeredstrategydef make_background(selfimg_filedesktop_size)in_img image open(img_fileout_img image new('rgb'desktop_sizeleft...
3,541
here we have three strategieseach using pil to perform their task individual strategies have make_background method that accepts the same set of parameters once selectedthe appropriate strategy can be called to create correctly sized version of the desktop image tiledstrategy loops over the number of input images that ...
3,542
so we have two types of classesthe context class and multiple state classes the context class maintains the current stateand forwards actions to the state classes the state classes are typically hidden from any other objects that are calling the contextit acts like black box that happens to perform state management int...
3,543
before we look at the states and the parserlet' consider the output of this program we know we want tree of node objectsbut what does node look likewellclearly it'll need to know the name of the tag it is parsingand since it' treeit should probably maintain pointer to the parent node and list of the node' children in o...
3,544
the firsttag state will switch to childnodewhich is responsible for deciding which of the other three states to switch towhen those states are finishedthey'll switch back to childnode the following state-transition diagram shows the available state changesopentag firsttag childnode text closetag the states are responsi...
3,545
the important feature of this parser is the process methodwhich accepts the remaining stringand passes it off to the current state the parser (the self argumentis also passed into the state' process method so that the state can manipulate it the state is expected to return the remainder of the unparsed string when it i...
3,546
elif stripped startswith("<")parser state opentag(elseparser state textnode(return stripped the strip(call removes whitespace from the string then the parser determines if the next item is an opening or closing tagor string of text depending on which possibility occursit sets the parser to particular stateand then tell...
3,547
finallythe textnode state very simply extracts the text before the next close tag and sets it as value on the current nodeclass textnodedef process(selfremaining_stringparser)i_start_tag remaining_string find('<'text remaining_string[:i_start_tagparser current_node text text parser state childnode(return remaining_stri...
3,548
titleobject oriented design number titleobjects in python comparing this to the original simplified xml document tells us the parser is working state versus strategy the state pattern looks very similar to the strategy patternindeedthe uml diagrams for the two are identical the implementationtoois identicalwe could eve...
3,549
so why discuss it at allsingleton is one of the most famous of all design patterns it is useful in overly object-oriented languagesand is vital part of traditional objectoriented programming more relevantlythe idea behind singleton is usefuleven if we implement that idea in totally different way in python the basic ide...
3,550
when __new__ is calledit normally constructs new instance of that class when we override itwe first check if our singleton instance has been createdif notwe create it using super call thuswhenever we call the constructor on oneonlywe always get the exact same instanceo oneonly( oneonly( = true the two objects are equal...
3,551
to use module-level variables instead of singletonwe instantiate an instance of the class after we've defined it we can improve our state pattern to use singletons instead of creating new object every time we change stateswe can create module-level variable that is always accessibleclass firsttagdef process(selfremaini...
3,552
return remaining_string[i_start_tag:class closetagdef process(selfremaining_stringparser)i_start_tag remaining_string find('<'i_end_tag remaining_string find('>'assert remaining_string[i_start_tag+ ="/tag_name remaining_string[i_start_tag+ :i_end_tagassert tag_name =parser current_node tag_name parser current_node pars...
3,553
the template pattern the template pattern is useful for removing duplicate codeit' an implementation to support the don' repeat yourself principle we discussed in when to use object-oriented programming it is designed for situations where we have several different tasks to accomplish that have somebut not allsteps in c...
3,554
issue the query format the results into comma-delimited string output the data to file or -mail the query construction and output steps are different for the two tasksbut the remaining steps are identical we can use the template pattern to put the common steps in base classand the varying steps in two subclasses before...
3,555
def construct_query(self)pass def do_query(self)pass def format_results(self)pass def output_results(self)pass def process_format(self)self connect(self construct_query(self do_query(self format_results(self output_results(the process_format method is the primary method to be called by an outside client it ensures each...
3,556
to help with implementing subclassesthe two methods that are not specified raise notimplementederror this is common way to specify abstract interfaces in python when abstract base classes seem too heavyweight the methods could have empty implementations (with pass)or could be fully unspecified raising notimplementederr...
3,557
exercises while writing this discovered that it can be very difficultand extremely educationalto come up with good examples where specific design patterns should be used instead of going over current or old projects to see where you can apply these patternsas 've suggested in previous think about the patterns and diffe...
3,558
in this we will be introduced to several more design patterns once againwe'll cover the canonical examples as well as any common alternative implementations in python we'll be discussingthe adapter pattern the facade pattern lazy initialization and the flyweight pattern the command pattern the abstract factory pattern ...
3,559
in structurethe adapter pattern is similar to simplified decorator pattern decorators typically provide the same interface that they replacewhereas adapters map between two different interfaces here it is in uml forminterface adapter +make_action(some,argumentsinterface +different_action(other,argumentshereinterface is...
3,560
this is pretty simple class that does what it' supposed to do but we have to wonder what the programmer was thinkingusing specifically formatted string instead of using python' incredibly useful built-in datetime library as conscientious programmers who reuse code whenever possiblemost of the programs we write will int...
3,561
creating class as an adapter is the usual way to implement this patternbutas usualthere are other ways to do it in python inheritance and multiple inheritance can be used to add functionality to class for examplewe could add an adapter on the date class so that it works with the original agecalculator classimport datet...
3,562
the facade pattern the facade pattern is designed to provide simple interface to complex system of components for complex taskswe may need to interact with these objects directlybut there is often "typicalusage for the system for which these complicated interactions aren' necessary the facade pattern allows us to defin...
3,563
the class is initialized with the hostname of the -mail servera usernameand password to log inimport smtplib import imaplib class emailfacadedef __init__(selfhostusernamepassword)self host host self username username self password password the send_email method formats the -mail address and messageand sends it using sm...
3,564
mailbox login(bytes(self username'utf ')bytes(self password'utf ')mailbox select(xdata mailbox search(none'all'messages [for num in data[ split()xmessage mailbox fetch(num'(rfc )'messages append(message[ ][ ]return messages nowif we add all this togetherwe have simple facade class that can send and receive messages in ...
3,565
let' have look at the uml diagram for the flyweight patternflyweightfactory +getflyweight(flyweight specificstate +shared_state +shared_action(specific_stateeach flyweight has no specific stateany time it needs to perform an operation on specificstatethat state needs to be passed into the flyweight by the calling code ...
3,566
we can solve this by taking advantage of python' weakref module this module provides weakvaluedictionary objectwhich basically allows us to store items in dictionary without the garbage collector caring about them if value is in weak referenced dictionary and there are no other references to that object stored anywhere...
3,567
let' add method to our flyweight that hypothetically looks up serial number on specific model of vehicleand determines if it has been involved in any accidents this method needs access to the car' serial numberwhich varies from car to carit cannot be stored with the flyweight thereforethis data must be passed into the ...
3,568
lx carmodel("fit lx"air=truecruise_control=truepower_locks=truetilt=trueid(lx lx carmodel("fit lx"id(lx lx air true the id function tells us the unique identifier for an object when we call it second timeafter deleting all references to the lx model and forcing garbage collectionwe see that the id has changed the value...
3,569
here' the uml diagramcommandinterface +execute(invoker client command +execute(receiver common example of the command pattern is actions on graphical window oftenan action can be invoked by menu item on the menu bara keyboard shortcuta toolbar iconor context menu these are all examples of invoker objects the actions th...
3,570
now let' define some invoker classes these will model toolbarmenuand keyboard events that can happenagainthey aren' actually hooked up to anythingbut we can see how they are decoupled from the commandreceiverand client codeclass toolbarbuttondef __init__(selfnameiconname)self name name self iconname iconname def click(...
3,571
def __init__(selfwindow)self window window def execute(self)self window exit(these commands are straightforwardthey demonstrate the basic patternbut it is important to note that we can store state and other information with the command if necessary for exampleif we had command to insert characterwe could maintain state...
3,572
def exit(self)sys exit( class menuitemdef click(self)self command(window window(menu_item menuitem(menu_item command window exit now that looks lot more like python at first glanceit looks like we've removed the command pattern altogetherand we've tightly connected the menu_item and window classes but if we look closer...
3,573
self document save(document document("a_file txt"shortcut keyboardshortcut(save_command savecommand(documentshortcut command save_command here we have something that looks like the first command patternbut bit more idiomatic as you can seemaking the invoker call callable instead of command object with an execute method...
3,574
the uml class diagram for an abstract factory pattern is hard to understand without specific exampleso let' turn things around and create concrete example first we'll create set of formatters that depend on specific locale and help us format dates and currencies there will be an abstract factory class that picks the sp...
3,575
def format_date(selfymd)ymd (str(xfor in ( , , ) ' if len( = else ' if len( = else ' if len( = else return("{ }-{ }-{ }format( , , )class francecurrencyformatterdef format_currency(selfbasecents)basecents (str(xfor in (basecents)if len(cents= cents ' elif len(cents= cents ' cents digits [for , in enumerate(reversed(bas...
3,576
these classes use some basic string manipulation to try to turn variety of possible inputs (integersstrings of different lengthsand othersinto the following formatsusa france date mm-dd-yyyy dd/mm/yyyy currency $ , eur there could obviously be more validation on the input in this codebut let' keep it simple and dumb fo...
3,577
it is easy to see what needs to be done when we want to add support for more countriescreate the new formatter classes and the abstract factory itself bear in mind that formatter classes might be reusedfor examplecanada formats its currency the same way as the usabut its date format is more sensible than its southern n...
3,578
the composite pattern the composite pattern allows complex tree-like structures to be built from simple components these componentscalled composite objectsare able to behave sort of like container and sort of like variable depending on whether they have child components composite objects are container objectswhere the ...
3,579
of coursein pythononce againwe can take advantage of duck typing to implicitly provide the interfaceso we only need to write two classes let' define these interfaces firstclass folderdef __init__(selfname)self name name self children {def add_child(selfchild)pass def move(selfnew_path)pass def copy(selfnew_path)pass de...
3,580
thinking about the methods involvedwe can see that moving or deleting node behaves in similar wayregardless of whether or not it is file or folder node copyinghoweverhas to do recursive copy for folder nodeswhile copying file node is trivial operation to take advantage of the similar operationswe can extract some of th...
3,581
names path split('/')[ :node root for name in namesnode node children[namereturn node we've created the move and delete methods on the component class both of them access mysterious parent variable that we haven' set yet the move method uses module-level get_path function that finds node from predefined root nodegiven ...
3,582
file move('/folder 'folder children {'file ''folder '<__main__ folder object at xb >yeswe can create foldersadd folders to other foldersadd files to foldersand move them aroundwhat more could we ask for in file hierarchywellwe could ask for copying to be implementedbut to conserve treeslet' leave that as an exercise th...
3,583
it' possible you don' have any hugememory-consuming code that would benefit from the flyweight patternbut can you think of situations where it might be usefulanywhere that large amounts of overlapping data need to be processeda flyweight is waiting to be used would it be useful in the banking industryin web application...
3,584
programs skilled python programmers agree that testing is one of the most important aspects of software development even though this is placed near the end of the bookit is not an afterthoughteverything we have studied so far will help us when writing tests we'll be studyingthe importance of unit testing and test-drive...
3,585
some people argue that testing is more important in python code because of its dynamic naturecompiled languages such as java and +are occasionally thought to be somehow "saferbecause they enforce type checking at compile time howeverpython tests rarely check types they're checking values they're making sure that the ri...
3,586
the first point really doesn' justify the time it takes to write testwe can simply test the code directly in the interactive interpreter but when we have to perform the same sequence of test actions multiple timesit takes less time to automate those steps once and then run them whenever necessary it is good idea to run...
3,587
as concrete exampleimagine writing code that uses an object-relational mapper to store object properties in database it is common to use an automatically assigned database id in such objects our code might use this id for various purposes if we are writing test for such codebefore we write itwe may realize that our des...
3,588
this code simply subclasses the testcase class and adds method that calls the testcase assertequal method this method will either succeed or raise an exceptiondepending on whether the two parameters are equal if we run this codethe main function from unittest will give us the following outputran test in ok did you know...
3,589
we can have as many test methods on one testcase class as we likeas long as the method name begins with testthe test runner will execute each one as separate test each test should be completely independent of other tests results or calculations from previous test should have no impact on the current test the key to wri...
3,590
[]def test_with_zero(self)with self assertraises(zerodivisionerror)average([]if __name__ ="__main__"unittest main(the context manager allows us to write the code the way we would normally write it (by calling functions or executing code directly)rather than having to wrap the function call in another function call ther...
3,591
reducing boilerplate and cleaning up after writing few small testswe often find that we have to do the same setup code for several related tests for examplethe following list subclass has three methods for statistical calculationsfrom collections import defaultdict class statslist(list)def mean(self)return sum(selflen(...
3,592
self assertequal(self stats mean() def test_median(self)self assertequal(self stats median() self stats append( self assertequal(self stats median() def test_mode(self)self assertequal(self stats mode()[ , ]self stats remove( self assertequal(self stats mode()[ ]if __name__ ="__main__"unittest main(if we run this examp...
3,593
python' discover module basically looks for any modules in the current folder or subfolders with names that start with the characters test if it finds any testcase objects in these modulesthe tests are executed it' painless way to ensure we don' miss running any tests to use itensure your test modules are named test_ p...
3,594
def test_skip(self)self assertequal(falsetrue@unittest skipif(sys version_info minor = "broken on "def test_skipif(self)self assertequal(falsetrue@unittest skipunless(sys platform startswith('linux')"broken unless on linux"def test_skipunless(self)self assertequal(falsetrueif __name__ ="__main__"unittest main(the first...
3,595
testing with py test the python unittest module requires lot of boilerplate code to set up and initialize tests it is based on the very popular junit testing framework for java it even uses the same method names (you may have noticed they don' conform to the pep- naming standardwhich suggests underscores rather than ca...
3,596
howeverwe are not forbidden from writing class-based tests classes can be useful for grouping related tests together or for tests that need to access related attributes or methods on the class this example shows an extended class with passing and failing testwe'll see that the error output is more comprehensive than th...
3,597
the output starts with some useful information about the platform and interpreter this can be useful for sharing bugs across disparate systems the third line tells us the name of the file being tested (if there are multiple test modules picked upthey will all be displayed)followed by the familiar we saw in the unittest...
3,598
finallywe have the setup_module and teardown_module functionswhich are run immediately before and after all tests (in functions or classesin that module these can be useful for "one timesetupsuch as creating socket or database connection that will be used by all tests in the module be careful with this oneas it can acc...
3,599
print("running method - "class testclass (basetest)def test_method_ (self)print("running method - "def test_method_ (self)print("running method - "the sole purpose of the basetest class is to extract four methods that would be otherwise identical to the test classesand use inheritance to reduce the amount of duplicate ...