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 charact...
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 ...
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 a...
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 compar...
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 t...
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...
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 oth...
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""o...
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 t...
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-or...
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 objectw...
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 tha...
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 initiali...
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...
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 l...
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 l...
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 w...
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 ra...
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 l...
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 ...
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 ur...
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 ...
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 ...
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 wh...
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 ...
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(se...
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 l...
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 o...
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 appl...
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 pr...
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 tupl...
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 valu...
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 tr...
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 doe...
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 statem...
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...
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...
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 l...
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...
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 val...
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 keywor...
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"...
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 ...
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 s...
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 classd...
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 ...
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( thr...
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 objec...
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 s...
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 ca...
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...
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 debu...
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...
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_gr...
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 ...
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 stri...
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 t...
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 usi...
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 comple...
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 'worl...
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 c...
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...
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 argumentsinterna...
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 printl...
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 ...
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!"'messa...
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 f...
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 scre...
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 shoul...
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 charact...
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 r...
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 decodi...
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 us...
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 or...
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 ...
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 c...
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 brack...
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...
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 sho...
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 thing...
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 charact...
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 s...
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 serial...
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 protoc...
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 object...
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...
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 shar...
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 transmi...
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 cou...
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 ob...
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 v...
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...
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 dir...
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 arch...
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...
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 a...
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...
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 ...
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 th...