id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
8,700 | herewe read numberswith and occurring most frequentlyand with sample standard deviation of the statistics themselves are held in named tuple called statisticsstatistics collections namedtuple("statistics""mean mode median std_dev"the main(function also serves as an overview of the program' structuredef main()if len(sys argv= or sys argv[ in {"- ""--help"}print("usage{ file [file filen]]formatsys argv[ ])sys exit(numbers [frequencies collections defaultdict(intfor filename in sys argv[ :]read_data(filenamenumbersfrequenciesif numbersstatistics calculate_statistics(numbersfrequenciesprint_results(len(numbers)statisticselseprint("no numbers found"we store all the numbers from all the files in the numbers list to calculate the mode ("most frequently occurring"numberswe need to know how many times each number occursso we create default dictionary using the int(factory functionto keep track of the counts we iterate over each filename and read in its data we pass the list and default dictionary as additional parameters so that the read_data(function can update them once we have read all the dataassuming some numbers were successfully readwe call calculate_statistics(this returns named tuple of type statistics which we then use to print the results def read_data(filenamenumbersfrequencies)for linoline in enumerate(open(filenameencoding="ascii")start= )for in line split()trynumber float(xnumbers append(numberfrequencies[number+ except valueerror as errprint("{filename}:{lino}skipping { }{err}format**locals()) |
8,701 | collection data types we split every line on whitespaceand for each item we attempt to convert it to float if conversion succeeds--as it will for integers and for floating-point numbers in both decimal and exponential notations--we add the number to the numbers list and update the frequencies default dictionary (if we had used plain dictthe update code would have been frequencies[numberfrequencies get(number using str format(with mapping unpacking if conversion failswe output the line number (starting from line as is traditional for text files)the text we attempted to convertand the valueerror exception' error text rather than using positional arguments ( format(filenamelinoetc or explicitly named argumentsformat(filename=filenamelino=linoetc )we have retrieved the names and values of the local variables by calling locals(and used mapping unpacking to pass these as key-value named arguments to the str format(method def calculate_statistics(numbersfrequencies)mean sum(numberslen(numbersmode calculate_mode(frequencies median calculate_median(numbersstd_dev calculate_std_dev(numbersmeanreturn statistics(meanmodemedianstd_devthis function is used to gather all the statistics together because the mean ("average"is so easy to calculatewe do so directly here for the other statistics we call dedicated functionsand at the end we return statistics named tuple object that contains the four statistics we have calculated def calculate_mode(frequenciesmaximum_modes)highest_frequency max(frequencies values()mode [number for numberfrequency in frequencies items(if frequency =highest_frequencyif not ( <len(mode<maximum_modes)mode none elsemode sort(return mode there may be more than one most-frequently-occurring numberso in addition to the dictionary of frequenciesthis function also requires the caller to specify the maximum number of modes that are acceptable (the calculate_statistics(function is the callerand it specified maximum of three modes the max(function is used to find the highest value in the frequencies dictionary thenwe use list comprehension to create list of those modes whose frequency equals the highest value we can compare using operator =since all the frequencies are integers |
8,702 | if the number of modes is or greater than the maximum modes that are acceptablea mode of none is returnedotherwisea sorted list of the modes is returned def calculate_median(numbers)numbers sorted(numbersmiddle len(numbers/ median numbers[middleif len(numbers = median (median numbers[middle ] return median the median ("middle value"is the value that occurs in the middle if the numbers are arranged in order--except when the number of numbers is evenin which case the middle falls between two numbersso in that case the median is the mean of the two middle numbers we begin by sorting the numbers into ascending order then we use truncating (integerdivision to find the index position of the middle numberwhich we extract and store as the median if the number of numbers is evenwe make the median the mean of the two middle numbers def calculate_std_dev(numbersmean)total for number in numberstotal +((number mean* variance total (len(numbers return math sqrt(variancethe sample standard deviation is measure of dispersionthat ishow far the numbers differ from the mean this function calculates the sample standard - deviation using the formula (xn -- xwhere is each number- is the meanand is the number of numbers def print_results(countstatistics)real " fif statistics mode is nonemodeline "elif len(statistics mode= modeline "mode { :{fmt}}\nformatstatistics mode[ ]fmt=realelsemodeline ("mode ["join(["{ }format(mfor in statistics mode]"]\ "print(""" |
8,703 | collection data types count { : mean {mean:{fmt}median {median:{fmt}{ }std dev {std_dev:{fmt}}""formatcountmodelinefmt=real**statistics _asdict())str format( named tuple using str format(with mapping unpacking most of this function is concerned with formatting the modes list into the modeline string if there are no modesthe mode line is not printed at all if there is one modethe mode list has just one item (mode[ ]which is printed using the same format as is used for the other statistics if there are several modeswe print them as list with each one formatted appropriately this is done by using list comprehension to produce list of mode stringsand then joining all the strings in the list together with "in between each one the printing at the end is easy thanks to our use of named tuple and its _asdict(methodin conjunction with mapping unpacking this lets us access the statistics in the statistics object using names rather than numeric indexesand thanks to python' triple-quoted strings we can lay out the text to be printed in an understandable way recall that if we use mapping unpacking to pass arguments to the str format(methodit may be done only once and only at the end there is one subtle point to note the modes are printed as format item { }which is followed by backslash the backslash escapes the newlineso if the mode is the empty string no blank line will appear and it is because we have escaped the newline that we must put \ at the end of the modeline string if it is not empty summary ||in this we covered all of python' built-in collection typesand also couple of collection types from the standard library we covered the collection sequence typestuplecollections namedtupleand listwhich support the same slicing and striding syntax as strings the use of the sequence unpacking operator (*was also coveredand brief mention was made of starred arguments in function calls we also covered the set typesset and frozensetand the mapping typesdict and collections defaultdict we saw how to use the named tuples provided by python' standard library to create simple custom tuple data types whose items can be accessed by index positionor more convenientlyby name we also saw how to create "constantsby using variables with all uppercase names in the coverage of lists we saw that everything that can be done to tuples can be done to lists and thanks to lists being mutable they offer considerably more functionality than tuples this includes methods that modify the list |
8,704 | ( list pop())and the ability to have slices on the left-hand side of an assignmentto provide insertionreplacementand deletion of slices lists are ideal for holding sequences of itemsespecially if we need fast access by index position when we discussed the set and frozenset typeswe noted that they may contain only hashable items sets provide fast membership testing and are useful for filtering out duplicate data dictionaries are in some ways similar to sets--for exampletheir keys must be hashable and are unique just like the items in set but dictionaries hold key-value pairswhose values can be of any type the dictionary coverage included the dict get(and dict setdefault(methodsand the coverage of default dictionaries showed an alternative to using these methods like setsdictionaries provide very fast membership testing and fast access by key listssetsand dictionaries all offer compact comprehension syntaxes that can be used to create collections of these types from iterables (which themselves can be comprehensions)and with conditions attached if required the range(and zip(functions are frequently used in the creation of collectionsboth in conventional for in loops and in comprehensions items can be deleted from the mutable collection types using the relevant methodssuch as list pop(and set discard()or using delfor exampledel [kto delete an item with key from dictionary python' use of object references makes assignment extremely efficientbut it also means that objects are not copied when the assignment operator (=is used we saw the differences between shallow and deep copyingand later on saw how lists can be shallow-copied using slice of the entire listl[:]and how dictionaries can be shallow-copied using the dict copy(method any copyable object can be copied using functions from the copy modulewith copy copy(performing shallow copyand copy deepcopy(performing deep copy we introduced python' highly optimized sorted(function this function is used lot in python programmingsince python doesn' provide any intrinsically ordered collection data typesso when we need to iterate over collections in sorted orderwe use sorted(python' built-in collection data types--tupleslistssetsfrozen setsand dictionaries--are sufficient in themselves for all purposes nonethelessa few additional collection types are available in the standard libraryand many more are available from third parties we often need to read in collections from filesor write collections to files in this we focused just on reading and writing lines of text in our very brief coverage of text file handling full coverage of file handling is given in and additional means of providing data persistence is covered in |
8,705 | collection data types in the next we will look more closely at python' control structuresand introduce one that we have not seen before we will also look in more depth at exception-handling and at some additional statementssuch as assertthat we have not yet covered in additionwe will cover the creation of custom functionsand in particular we will look at python' incredibly versatile argumenthandling facilities exercises || modify the external_sites py program to use default dictionary this is an easy change requiring an additional importand changes to just two other lines solution is provided in external_sites_ans py modify the uniquewords py program so that it outputs the words in frequency of occurrence order rather than in alphabetical order you'll need to iterate over the dictionary' items and create tiny two-line function to extract each item' value and pass this function as sorted()' key function alsothe call to print(will need to be changed appropriately this isn' difficultbut it is slightly subtle solution is provided in uniquewords_ans py modify the generate_usernames py program so that it prints the details of two users per linelimiting names to characters and outputting form feed character after every lineswith the column titles printed at the start of every page here' sample of the expected outputname id username aitkinshatha ( saitkin allisonkarma ( kallison annieneervana ( nannie name id username aldersonnicole ( nalderso alwoodkole ( kealwood appersonlucyann ( leappers this is challenging you'll need to keep the column titles in variables so that they can be printed when neededand you'll need to tweak the format specifications to accommodate the narrower names one way to achieve pagination is to write all the output items to list and then iterate over the list using striding to get the leftand right-hand itemsand using zip(to pair them up solution is provided in generate_usernames_ans py and longer sample data file is provided in data/users txt |
8,706 | control structures exception handling custom functions control structures and functions |||this first two sections cover python' control structureswith the first section dealing with branching and looping and the second section covering exception-handling most of the control structures and the basics of exception-handling were introduced in but here we give more complete coverageincluding additional control structure syntaxesand how to raise exceptions and create custom exceptions the third and largest section is devoted to creating custom functionswith detailed coverage of python' extremely versatile argument handling custom functions allow us to package up and parameterize functionality--this reduces the size of our code by eliminating code duplication and provides code reuse (in the following we will see how to create custom modules so that we can make use of our custom functions in multiple programs ||control structures python provides conditional branching with if statements and looping with while and for in statements python also has conditional expression--this is kind of if statement that is python' answer to the ternary operator (?:used in -style languages |conditional branching as we saw in this is the general syntax for python' conditional branch statementif boolean_expression suite |
8,707 | the parentheses also make things clearer for human readers conditional expressions can be used to improve messages printed for users for examplewhen reporting the number of files processedinstead of printing " file( )"" file( )"and similarwe could use couple of conditional expressionsprint("{ file{ }format((count if count ! else "no")("sif count ! else ""))this will print "no files"" file"" files"and similarwhich gives much more professional impression looping |python provides while loop and for in loopboth of which have more sophisticated syntax than the basics we showed in while loops here is the complete general syntax of the while loopwhile boolean_expressionwhile_suite elseelse_suite the else clause is optional as long as the boolean_expression is truethe while block' suite is executed if the boolean_expression is or becomes falsethe loop terminatesand if the optional else clause is presentits suite is executed inside the while block' suiteif continue statement is executedcontrol is immediately returned to the top of the loopand the boolean_expression is evaluated again if the loop does not terminate normallyany optional else clause' suite is skipped the optional else clause is rather confusingly named since the else clause' suite is always executed if the loop terminates normally if the loop is broken out of due to break statementor return statement (if the loop is in function or method)or if an exception is raisedthe else clause' suite is not executed (if an exception occurspython skips the else clause and looks for suitable exception handler--this is covered in the next section on the plus sidethe behavior of the else clause is the same for while loopsfor in loopsand try except blocks let' look at an example of the else clause in action the str index(and list index(methods return the index position of given string or itemor raise valueerror exception if the string or item is not found the str find( |
8,708 | control structures and functions method does the same thingbut on failureinstead of raising an exception it returns an index of - there is no equivalent method for listsbut if we wanted function that did thiswe could create one using while loopdef list_find(lsttarget)index while index len(lst)if lst[index=targetbreak index + elseindex - return index this function searches the given list looking for the target if the target is foundthe break statement terminates the loopcausing the appropriate index position to be returned if the target is not foundthe loop runs to completion and terminates normally after normal terminationthe else suite is executedand the index position is set to - and returned for loops like while loopthe full syntax of the for in loop also includes an optional else clausefor expression in iterablefor_suite elseelse_suite the expression is normally either single variable or sequence of variablesusually in the form of tuple if tuple or list is used for the expressioneach item is unpacked into the expression' items if continue statement is executed inside the for in loop' suitecontrol is immediately passed to the top of the loop and the next iteration begins if the loop runs to completion it terminatesand any else suite is executed if the loop is broken out of due to break statementor return statement (if the loop is in function or method)or if an exception is raisedthe else clause' suite is not executed (if an exception occurspython skips the else clause and looks for suitable exception handler--this is covered in the next section enumerate( here is for in loop version of the list_find(functionand like the while loop versionit shows the else clause in actiondef list_find(lsttarget)for indexx in enumerate(lst) |
8,709 | if =targetbreak elseindex - return index as this code snippet impliesthe variables created in the for in loop' expression continue to exist after the loop has terminated like all local variablesthey cease to exist at the end of their enclosing scope exception handling ||python indicates errors and exceptional conditions by raising exceptionsalthough some third-party python libraries use more old-fashioned techniquessuch as "errorreturn values catching and raising exceptions |exceptions are caught using try except blockswhose general syntax istrytry_suite except exception_group as variable except_suite except exception_groupn as variablenexcept_suiten elseelse_suite finallyfinally_suite there must be at least one except blockbut both the else and the finally blocks are optional the else block' suite is executed when the try block' suite has finished normally--but it is not executed if an exception occurs if there is finally blockit is always executed at the end each except clause' exception group can be single exception or parenthesized tuple of exceptions for each groupthe as variable part is optionalif usedthe variable contains the exception that occurredand can be accessed in the exception block' suite if an exception occurs in the try block' suiteeach except clause is tried in turn if the exception matches an exception groupthe corresponding suite is executed to match an exception groupthe exception must be of the same type |
8,710 | control structures and functions here is final version of the list_find(functionthis time using exceptionhandlingdef list_find(lsttarget)tryindex lst index(targetexcept valueerrorindex - return index herewe have effectively used the try except block to turn an exception into return valuethe same approach can also be used to catch one kind of exception and raise another instead-- technique we will see shortly python also offers simpler try finally block which is sometimes usefultrytry_suite finallyfinally_suite no matter what happens in the try block' suite (apart from the computer or program crashing!)the finally block' suite will be executed the with statement used with context manager (both covered in can be used to achieve similar effect to using try finally block one common pattern of use for try except finally blocks is for handling file errors for examplethe noblanks py program reads list of filenames on the command lineand for each one produces another file with the same namebut with its extension changed to nband with the same contents except for no blank lines here' the program' read_data(functiondef read_data(filename)lines [fh none tryfh open(filenameencoding="utf "for line in fhif line strip()lines append(lineexcept (ioerroroserroras errprint(errreturn [finallyif fh is not nonefh close(return lines |
8,711 | we set the file objectfhto none because it is possible that the open(call will failin which case nothing will be assigned to fh (so it will stay as none)and an exception will be raised if one of the exceptions we have specified occurs (ioerror or oserror)after printing the error message we return an empty list but note that before returningthe finally block' suite will be executedso the file will be safely closed--if it had been successfully opened in the first place notice also that if an encoding error occurseven though we don' catch the relevant exception (unicodedecodeerror)the file will still be safely closed in such cases the finally block' suite is executed and then the exception is passed up the call stack--there is no return value since the function finishes as result of the unhandled exception and in this casesince there is no suitable except block to catch encoding error exceptionsthe program will terminate and print traceback dealing with runtime errors we could have written the except clause slightly less verboselyexcept environmenterror as errprint(errreturn [this works because environmenterror is the base class for both ioerror and oserror in we will show slightly more compact idiom for ensuring that files are safely closedthat does not require finally block context managers raising exceptions exceptions provide useful means of changing the flow of control we can take advantage of this either by using the built-in exceptionsor by creating our ownraising either kind when we want to there are three syntaxes for raising exceptionsraise exception(argsraise exception(argsfrom original_exception raise when the first syntax is used the exception that is specified should be either one of the built-in exceptionsor custom exception that is derived from exception if we give the exception some text as its argumentthis text will be output if the exception is printed when it is caught the second syntax is variation of the first--the exception is raised as chained exception (covered in that includes the original_exception exceptionso this syntax is used inside except suites when the third syntax is usedthat iswhen no exception is specifiedraise will reraise the currently active exception--and if there isn' one it will raise typeerror chained exceptions |
8,712 | control structures and functions custom exceptions |custom exceptions are custom data types (classescreating classes is covered in but since it is easy to create simple custom exception typeswe will show the syntax hereclass exceptionname(baseexception)pass the base class should be exception or class that inherits from exception one use of custom exceptions is to break out of deeply nested loops for exampleif we have table object that holds records (rows)which hold fields (columns)which have multiple values (items)we could search for particular value with code like thisfound false for rowrecord in enumerate(table)for columnfield in enumerate(record)for indexitem in enumerate(field)if item =targetfound true break if foundbreak if foundbreak if foundprint("found at ({ }{ }{ })format(rowcolumnindex)elseprint("not found"the lines of code are complicated by the fact that we must break out of each loop separately an alternative solution is to use custom exceptionclass foundexception(exception)pass tryfor rowrecord in enumerate(table)for columnfield in enumerate(record)for indexitem in enumerate(field)if item =targetraise foundexception(except foundexceptionprint("found at ({ }{ }{ })format(rowcolumnindex)elseprint("not found" |
8,713 | this cuts the code down to ten linesor including defining the exceptionand is much easier to read if the item is found we raise our custom exception and the except block' suite is executed--and the else block is skipped and if the item is not foundno exception is raised and so the else suite is executed at the end let' look at another example to see some of the different ways that exceptionhandling can be done all of the snippets are taken from the checktags py programa program that reads all the html files it is given on the command line and performs some simple tests to verify that tags begin with "<and end with ">"and that entities are correctly formed the program defines four custom exceptionsclass invalidentityerror(exception)pass class invalidnumericentityerror(invalidentityerror)pass class invalidalphaentityerror(invalidentityerror)pass class invalidtagcontenterror(exception)pass the second and third exceptions inherit from the firstwe will see why this is useful when we discuss the code that uses the exceptions the parse(function that uses the exceptions is more than lines longso we will show only those parts that are relevant to exception-handling fh none tryfh open(filenameencoding="utf "errors false for linoline in enumerate(fhstart= )for columnc in enumerate(linestart= )trythe code begins conventionally enoughsetting the file object to none and putting all the file handling in try block the program reads the file line by line and reads each line character by character notice that we have two try blocksthe outer one is used to handle file object exceptionsand the inner one is used to handle parsing exceptions elif state =parsing_entityif =";"if entity startswith("#")if frozenset(entity[ :]hexdigitsraise invalidnumericentityerror(elif not entity isalpha()raise invalidalphaentityerror( |
8,714 | control structures and functions the function has various statesfor exampleafter reading an ampersand (&)it enters the parsing_entity stateand stores the characters between (but excludingthe ampersand and semicolon in the entity string set type the part of the code shown here handles the case when semicolon has been found while reading an entity if the entity is numeric (of the form "&#"with hexadecimal digitsand then ";"for example"&# ac;")we convert the numeric part of it into set and take away from the set all the hexadecimal digitsif anything is left at least one invalid character was present and we raise custom exception if the entity is alphabetic (of the form "&"with lettersand then";"for example"©")we raise custom exception if any of its letters is not alphabetic except (invalidentityerrorinvalidtagcontenterroras errif isinstance(errinvalidnumericentityerror)error "invalid numeric entityelif isinstance(errinvalidalphaentityerror)error "invalid alphabetic entityelif isinstance(errinvalidtagcontenterror)error "invalid tagprint("error { in { on line { column { }format(errorfilenamelinocolumn)if skip_on_first_errorraise if parsing exception is raised we catch it in this except block by using the invalidentityerror base classwe catch both invalidnumericentityerror and invalidalphaentityerror exceptions we then use isinstance(to check which type of exception occurredand to set the error message accordingly the built-in isinstance(function returns true if its first argument is the same type as the type (or one of that type' base typesgiven as its second argument we could have used separate except block for each of the three custom parsing exceptionsbut in this case combining them means that we avoided repeating the last four lines (from the print(call to raise)in each one the program has two modes of use if skip_on_first_error is falsethe program continues checking file even after parsing error has occurredthis can lead to multiple error messages being output for each file if skip_on_first_error is trueonce parsing error has occurredafter the (one and onlyerror message is printedraise is called to reraise the parsing exception and the outer (per-filetry block is left to catch it isinstance( |
8,715 | elif state =parsing_entityraise eoferror("missing ';at end of filenameat the end of parsing filewe need to check to see whether we have been left in the middle of an entity if we havewe raise an eoferrorthe built-in end-of-file exceptionbut give it our own message text we could just as easily have raised custom exception except (invalidentityerrorinvalidtagcontenterror)pass already handled except eoferror as errprint("error unexpected eof:"errexcept environmenterror as errprint(errfinallyif fh is not nonefh close(for the outer try block we have used separate except blocks since the behavior we want varies if we have parsing exceptionwe know that an error message has already been output and the purpose is simply to break out of reading the file and to move on to the next fileso we don' need to do anything in the exception handler if we get an eoferror it could be caused by genuine premature end of file or it could be the result of us raising the exception ourselves in either casewe print an error messageand the exception' text if an environmenterror occurs ( if an ioerror or an oserror occurs)we simply print its message and finallyno matter whatif the file was openedwe close it custom functions ||functions are means by which we can package up and parameterize functionality four kinds of functions can be created in pythonglobal functionslocal functionslambda functionsand methods every function we have created so far has been global function global objects (including functionsare accessible to any code in the same module ( the same py filein which the object is created global objects can also be accessed from other modulesas we will see in the next local functions (also called nested functionsare functions that are defined inside other functions these functions are visible only to the function where they are definedthey are especially useful for creating small helper functions that have no use elsewhere we first show them in |
8,716 | control structures and functions online documentation although this book provides solid coverage of the python language and the built-in functions and most commonly used modules in the standard librarypython' online documentation provides considerable amount of reference documentationboth on the languageand particularly on python' extensive standard library the documentation is available online at docs python org and is also provided with python itself on windows the documentation is supplied in the windows help file format click start-all programs-python -python manuals to launch the windows help browser this tool has both an index and search function that makes finding documentation easy unix users have the documentation in html format in addition to the hyperlinksthere are various index pages there is also very convenient quick search function available on the left-hand side of each page the most frequently used online document for new users is the library referenceand for experienced users the global module index both of these have links to pages covering python' entire standard library--and in the case of the library referencelinks to pages covering all of python' built-in functionality as well it is well worth skimming through the documentationparticularly the library reference or the global module indexto see what python' standard library offersand clicking through to the documentation of whichever topics are of interest this should provide an initial impression of what is available and should also help you to establish mental picture of where you can find the documentation you are interested in ( brief summary of python' standard library is provided in help is also available from the interpreter itself if you call the builtin help(function with no argumentsyou will enter the online help system--simply follow the instructions to get the information you wantand type "qor "quitto return to the interpreter if you know what module or data type you want help onyou can call help(with the module or data type as its argument for examplehelp(strprovides information on the str data typeincluding all of its methodshelp(dict updateprovides information on the dict collection data type' update(methodand help(osdisplays information about the os module (providing it has been importedonce familiar with pythonit is often sufficient to just be reminded about what attributes ( what methodsa data type provides this information is available using the dir(function--for exampledir(strlists all the string methodsand dir(oslists all the os module' constants and functions (againproviding the module has been imported |
8,717 | lambda functions are expressionsso they can be created at their point of usehoweverthey are much more limited than normal functions methods are functions that are associated with particular data type and can be used only in conjunction with the data type--they are introduced in when we cover object-oriented programming python provides many built-in functionsand the standard library and thirdparty libraries add hundreds more (thousands if we count all the methods)so in many cases the function we want has already been written for this reasonit is always worth checking python' online documentation to see what is already available see the sidebar "online documentation( the general syntax for creating (global or localfunction isdef functionname(parameters)suite the parameters are optionaland if there is more than one they are written as sequence of comma-separated identifiersor as sequence of identifier=value pairs as we will discuss shortly for examplehere is function that calculates the area of triangle using heron' formuladef heron(abc) ( return math sqrt( ( ( ( )inside the functioneach parameteraband cis initialized with the corresponding value that was passed as an argument when the function is calledwe must supply all of the argumentsfor exampleheron( if we give too few or too many argumentsa typeerror exception will be raised when we do call like this we are said to be using positional argumentsbecause each argument passed is set as the value of the parameter in the corresponding position so in this casea is set to to and to when the function is called every function in python returns valuealthough it is perfectly acceptable (and commonto ignore the return value the return value is either single value or tuple of valuesand the values returned can be collectionsso there are no practical limitations on what we can return we can leave function at any point by using the return statement if we use return with no argumentsor if we don' have return statement at allthe function will return none (in we will cover the yield statement which can be used instead of return in certain kinds of functions some functions have parameters for which there can be sensible default for examplehere is function that counts the letters in stringdefaulting to the ascii letters |
8,718 | control structures and functions def letter_count(textletters=string ascii_letters)letters frozenset(letterscount for char in textif char in letterscount + return count we have specified default value for the letters parameter by using the parameter=default syntax this allows us to call letter_count(with just one argumentfor exampleletter_count("maggie and hopey"hereinside the functionletters will be the string that was given as the default value but we can still change the defaultfor exampleusing an extra positional argumentletter_count("maggie and hopey""aeiouaeiou")or using keyword argument (covered next)letter_count("maggie and hopey"letters="aeiouaeiou"the parameter syntax does not permit us to follow parameters with default values with parameters that don' have defaultsso def bad(ab= )won' work on the other handwe are not forced to pass our arguments in the order they appear in the function' definition--insteadwe can use keyword argumentspassing each argument in the form name=value here is tiny function that returns the string it is givenor if it is longer than the specified lengthit returns shortened version with an indicator addeddef shorten(textlength= indicator=")if len(textlengthtext text[:length len(indicator)indicator return text here are few example callsshorten("the silkie"returns'the silkieshorten(length= text="the silkie"returns'the shorten("the silkie"indicator="&"length= returns'the si&shorten("the silkie" "&"returns'the si&because both length and indicator have default valueseither or both can be omitted entirelyin which case the default is used--this is what happens in the first call in the second call we use keyword arguments for both of the specified parametersso we can order them as we like the third call mixes both positional and keyword arguments we used positional first argument (positional arguments must always precede keyword arguments)and then two keyword arguments the fourth call simply uses positional arguments the difference between mandatory parameter and an optional parameter is that parameter with default is optional (because python can use the default)and parameter with no default is mandatory (because python can |
8,719 | control structures and functions using conditional expression we can save line of code for each parameter that has mutable default argument |names and docstrings using good names for function and its parameters goes long way toward making the purpose and use of the function clear to other programmers--and to ourselves some time after we have created the function here are few rules of thumb that you might like to consider use naming schemeand use it consistently in this book we use uppercase for constantstitlecase for classes (including exceptions)camelcase for gui (graphical user interfacefunctions and methods (covered in )and lowercase or lowercase_with_underscores for everything else for all namesavoid abbreviationsunless they are both standardized and widely used be proportional with variable and parameter namesx is perfectly good name for an -coordinate and is fine for loop counterbut in general the name should be long enough to be descriptive the name should describe the data' meaning rather than its type ( amount_due rather than money)unless the use is generic to particular type--seefor examplethe text parameter in the shorten(example functions and methods should have names that say what they do or what they return (depending on their emphasis)but never how they do it--since that might change here are few naming examplesdef find(lsi= )def linear_search(lsi= )def first_index_of(sorted_name_listnamestart= )bad bad good all three functions return the index position of the first occurrence of name in list of namesstarting from the given starting index and using an algorithm that assumes the list is already sorted the first one is bad because the name gives no clue as to what will be foundand its parameters (presumablyindicate the required types (liststringintegerwithout indicating what they mean the second one is bad because the function name describes the algorithm originally used--it might have been changed since this may not matter to users of the functionbut it will probably confuse maintainers if the name implies linear searchbut the algorithm implemented has been changed to binary search the third one is good be |
8,720 | cause the function name says what is returnedand the parameter names clearly indicate what is expected none of the functions have any way of indicating what happens if the name isn' found--do they returnsay- or do they raise an exceptionsomehow such information needs to be documented for users of the function we can add documentation to any function by using docstring--this is simply string that comes immediately after the def lineand before the function' code proper begins for examplehere is the shorten(function we saw earlierbut this time reproduced in fulldef shorten(textlength= indicator=")"""returns text or truncated copy with the indicator added text is any stringlength is the maximum length of the returned string (including any indicator)indicator is the string added at the end to indicate that the text has been shortened shorten("second variety"'second varietyshorten("voices from the street" 'voices from th shorten("radio free albemuth" "*"'radio fre*""if len(textlengthtext text[:length len(indicator)indicator return text it is not unusual for function or method' documentation to be longer than the function itself one convention is to make the first line of the docstring brief one-line descriptionthen have blank line followed by full descriptionand then to reproduce some examples as they would appear if typed in interactively in and we will see how examples in function documentation can be used to provide unit tests argument and parameter unpacking sequence unpacking |we saw in the previous that we can use the sequence unpacking operator (*to supply positional arguments for exampleif we wanted to compute the area of triangle and had the lengths of the sides in listwe could make the call like thisheron(sides[ ]sides[ ]sides[ ])or simply unpack the list and do the much simpler callheron(*sidesand if the list (or other sequencehas more items than the function has parameterswe can use slicing to extract exactly the right number of arguments |
8,721 | control structures and functions we can also use the sequence unpacking operator in function' parameter list this is useful when we want to create functions that can take variable number of positional arguments here is product(function that computes the product of the arguments it is givendef product(*args)result for arg in argsresult *arg return result this function has one parameter called args having the in front means that inside the function the args parameter will be tuple with its items set to however many positional arguments are given here are few example callsproduct( product( product( args =( )returns args =( )returns args =( ,)returns we can have keyword arguments following positional argumentsas this function to calculate the sum of its argumentseach raised to the given powershowsdef sum_of_powers(*argspower= )result for arg in argsresult +arg *power return result the function can be called with just positional argumentsfor examplesum_of_powers( )or with both positional and keyword argumentsfor examplesum_of_powers( power= it is also possible to use as "parameterin its own right this is used to signify that there can be no positional arguments after the *although keyword arguments are allowed here is modified version of the heron(function this time the function takes exactly three positional argumentsand has one optional keyword argument def heron (abc*units="square meters") ( area math sqrt( ( ( ( )return "{ { }format(areaunitshere are few example callsheron ( returns' square metersheron ( units="sq inches"returns' sq inches |
8,722 | heron ( "sq inches" wrongraises typeerror in the third call we have attempted to pass fourth positional argumentbut the does not allow this and causes typeerror to be raised by making the the first parameter we can prevent any positional arguments from being usedand force callers to use keyword arguments here is such (fictitiousfunction' signaturedef print_setup(*paper="letter"copies= color=false)we can call print_setup(with no argumentsand accept the defaults or we can change some or all of the defaultsfor exampleprint_setup(paper=" "color=truebut if we attempt to use positional argumentsfor exampleprint_setup(" ") typeerror will be raised just as we can unpack sequence to populate function' positional argumentswe can also unpack mapping using the mapping unpacking operatorasterisk asterisk (**we can use *to pass dictionary to the print_setup(function for exampleoptions dict(paper=" "color=trueprint_setup(**optionshere the options dictionary' key-value pairs are unpacked with each key' value being assigned to the parameter whose name is the same as the key if the dictionary contains key for which there is no corresponding parametera typeerror is raised any argument for which the dictionary has no corresponding item is set to its default value--but if there is no defaulta typeerror is raised we can also use the mapping unpacking operator with parameters this allows us to create functions that will accept as many keyword arguments as are given here is an add_person_details(function that takes social security number and surname positional argumentsand any number of keyword argumentsdef add_person_details(ssnsurname**kwargs)print("ssn ="ssnprint(surname ="surnamefor key in sorted(kwargs)print({ { }format(keykwargs[key])this function could be called with just the two positional argumentsor with additional informationfor exampleadd_person_details( "luther"forename="lexis"age= this provides us with lot of flexibility and we as we saw in when used as binary operator*is the pow(operator |
8,723 | control structures and functions can of course accept both variable number of positional arguments and variable number of keyword argumentsdef print_args(*args**kwargs)for iarg in enumerate(args)print("positional argument { { }format(iarg)for key in kwargsprint("keyword argument { { }format(keykwargs[key])this function just prints the arguments it is given it can be called with no argumentsor with any number of positional and keyword arguments accessing variables in the global scope |it is sometimes convenient to have few global variables that are accessed by various functions in the program this is usually okay for "constants"but is not good practice for variablesalthough for short one-off programs it isn' always unreasonable the digit_names py program takes an optional language ("enor "fr"and number on the command line and outputs the names of each of the digits it is given so if it is invoked with " on the command lineit will output "one two threethe program has three global variableslanguage "enenglish { "zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"french { "zero" "un" "deux" "trois" "quatre" "cinq" "six" "sept" "huit" "neuf"we have followed the convention that all uppercase variable names indicate constantsand have set the default language to english (python does not provide direct way to create constantsinstead relying on programmers to respect the convention elsewhere in the program we access the language variableand use it to choose the appropriate dictionary to usedef print_digits(digits)dictionary english if language ="enelse french for digit in digitsprint(dictionary[int(digit)]end="print(when python encounters the language variable in this function it looks in the local (functionscope and doesn' find it so it then looks in the global py filescopeand finds it there the end keyword argument used with the first print(call is explained in the sidebar "the print(function |
8,724 | control structures and functions "fr"but the global language variable used in the print_digits(function would remain unchanged as "enfor nontrivial programs it is best not to use global variables except as constantsin which case there is no need to use the global statement lambda functions |lambda functions are functions created using the following syntaxlambda parametersexpression the parameters are optionaland if supplied they are normally just commaseparated variable namesthat ispositional argumentsalthough the complete argument syntax supported by def statements can be used the expression cannot contain branches or loops (although conditional expressions are allowed)and cannot have return (or yieldstatement the result of lambda expression is an anonymous function when lambda function is called it returns the result of computing the expression as its result if the expression is tuple it should be enclosed in parentheses here is simple lambda function for adding an (or notdepending on whether its argument is lambda "if = else "sthe lambda expression returns an anonymous function which we assign to the variable any (callablevariable can be called using parenthesesso given the count of files processed in some operation we could output message using the (function like thisprint("{ file{ processedformat(counts(count))lambda functions are often used as the key function for the built-in sorted(function and for the list sort(method suppose we have list of elements as -tuples of (groupnumbername)and we wanted to sort this list in various ways here is an example of such listelements [( "mg")( "na")( "li")( "be")if we sort this listwe get this result[( 'li')( 'na')( 'be')( 'mg')sorted( we saw earlier when we covered the sorted(function that we can provide key function to alter the sort order for exampleif we wanted to sort the list by number and namerather than the natural ordering of groupnumberand namewe could write tiny functiondef ignore ( )return [ ] [ ]which could be provided as the key function creating lots of little functions like this can be inconvenientso frequently used alternative is lambda functiongenerator functions |
8,725 | elements sort(key=lambda ( [ ] [ ])here the key function is lambda ( [ ] [ ]with being each -tuple element in the list the parentheses around the lambda expression are required when the expression is tuple and the lambda function is created as function' argument we could use slicing to achieve the same effectelements sort(key=lambda ee[ : ] slightly more elaborate version gives us sorting in case-insensitive namenumber orderelements sort(key=lambda ( [ lower() [ ])here are two equivalent ways to create function that calculates the area of triangle using the conventional base height formulaarea lambda bh def area(bh)return we can call area( )whether we created the function using lambda expression or using def statementand the result will be the same default dictionaries another neat use of lambda functions is when we want to create default dictionaries recall from the previous that if we access default dictionary using nonexistent keya suitable item is created with the given key and with default value here are few examplesminus_one_dict collections defaultdict(lambda- point_zero_dict collections defaultdict(lambda( )message_dict collections defaultdict(lambda"no message available"if we access the minus_one_dict with nonexistent keya new item will be created with the given key and with value of - similarly for the point_zero_dict where the value will be the tuple ( )and for the message_dict where the value will be the "no message availablestring assertions |what happens if function receives arguments with invalid datawhat happens if we make mistake in the implementation of an algorithm and perform an incorrect computationthe worst thing that can happen is that the program executes without any (apparentproblem and no one is any the wiser one way to help avoid such insidious problems is to write tests--something we will briefly look at in another way is to state the preconditions and postconditions and to indicate an error if any of these are not met ideallywe should use tests and also state preconditions and postconditions |
8,726 | control structures and functions preconditions and postconditions can be specified using assert statementswhich have the syntaxassert boolean_expressionoptional_expression if the boolean_expression evaluates to false an assertionerror exception is raised if the optional optional_expression is givenit is used as the argument to the assertionerror exception--this is useful for providing error messages notethoughthat assertions are designed for developersnot end-users problems that occur in normal program use such as missing files or invalid command-line arguments should be handled by other meanssuch as providing an error or log message here are two new versions of the product(function both versions are equivalent in that they require that all the arguments passed to them are nonzeroand consider call with argument to be coding error def product(*args)pessimistic assert all(args)" argumentresult for arg in argsresult *arg return result def product(*args)optimistic result for arg in argsresult *arg assert result" argumentreturn result the "pessimisticversion on the left checks all the arguments (or up to the first argumenton every call the "optimisticversion on the right just checks the resultafter allif any argument was then the result will be if one of these product(functions is called with argument an assertionerror exception will be raisedand output similar to the following will be written to the error stream (sys stderrusually the console)traceback (most recent call last)file "program py"line in product( file "program py"line in product assert result" argumentassertionerror argument python automatically provides traceback that gives the filenamefunctionand line numberas well as the error message we specified once program is ready for public release (and of course passes all its tests and does not violate any assertions)what do we do about the assert statementswe can tell python not to execute assert statements--in effectto throw them away at runtime this can be done by running the program at the command line with the - optionfor examplepython - program py another approach is to set the pythonoptimize environment variable to if the docstrings are of |
8,727 | no use to our users (and normally they wouldn' be)we can use the -oo option which in effect strips out both assert statements and docstringsnote that there is no environment variable for setting this option some developers take simpler approachthey produce copy of their program with all assert statements commented outand providing this passes their teststhey release the assertion-free version examplemake_html_skeleton py ||in this section we draw together some of the techniques covered in this and show them in the context of complete example program very small web sites are often created and maintained by hand one way to make this slightly more convenient is to have program that can generate skeleton html files that can later be fleshed out with content the make_html_skeleton py program is an interactive program that prompts the user for various details and then creates skeleton html file the program' main(function has loop so that users can create skeleton after skeletonand it retains common data ( copyright informationso that users don' have to type it in more than once here is transcript of typical interactionmake_html_skeleton py make html skeleton enter your name (for copyright)harold pinter enter copyright year [ ] enter filenamecareer-synopsis enter titlecareer synopsis enter description (optional)synopsis of the career of harold pinter enter keyword (optional)playwright enter keyword (optional)actor enter keyword (optional)activist enter keyword (optional)enter the stylesheet filename (optional)style saved skeleton career-synopsis html create another ( / )[ ]make html skeleton enter your name (for copyright[harold pinter]enter copyright year [ ]enter filenamecancelled create another ( / )[ ] |
8,728 | control structures and functions notice that for the second skeleton the name and year had as their defaults the values entered previouslyso they did not need to be retyped but no default for the filename is providedso when that was not given the skeleton was cancelled now that we have seen how the program is usedwe are ready to study the code the program begins with two importsimport datetime import xml sax saxutils the datetime module provides some simple functions for creating datetime date and datetime time objects the xml sax saxutils module has useful xml sax saxutils escape(function that takes string and returns an equivalent string with the special html characters ("&"""in their escaped forms ("&""<"and ">"three global strings are definedthese are used as templates copyright_template "copyright ( { { all rights reserved stylesheet_template ('<link rel="stylesheettype="text/css'media="allhref="{ }/>\ 'html_template ""<!doctype html public "-// //dtd xhtml strict//en{title{stylesheet}""str format( these strings will be used as templates in conjunction with the str format(method in the case of html_template we have used names rather than index positions for the field namesfor example{titlewe will see shortly that we must use keyword arguments to provide values for these class cancellederror(exception)pass |
8,729 | one custom exception is definedwe will see it in use when we look at couple of the program' functions the program' main(function is used to set up some initial informationand to provide loop on each iteration the user has the chance to enter some information for the html page they want generatedand after each one they are given the chance to finish def main()information dict(name=noneyear=datetime date today(yearfilename=nonetitle=nonedescription=nonekeywords=nonestylesheet=nonewhile truetryprint("\nmake html skeleton\ "populate_information(informationmake_html_skeleton(**informationexcept cancellederrorprint("cancelled"if (get_string("\ncreate another ( / )?"default=" "lower(not in {" ""yes"})break the datetime date today(function returns datetime date object that holds today' date we want just the year attribute all the other items of information are set to none since there are no sensible defaults that can be set inside the while loop the program prints titlethen calls the populate_information(function with the information dictionary this dictionary is updated inside the populate_information(function nextthe make_html_skeleton(function is called--this function takes number of argumentsbut rather than give explicit values for each one we have simply unpacked the information dictionary if the user cancelsfor exampleby not providing mandatory informationthe program prints out "cancelledat the end of each iteration (whether cancelled or not)the user is asked whether they want to create another skeleton--if they don'twe break out of the loop and the program terminates def populate_information(information)name get_string("enter your name (for copyright)""name"information["name"]if not nameraise cancellederror(year get_integer("enter copyright year""year"information["year"] datetime date today(year true |
8,730 | title xml sax saxutils escape(titledescription xml sax saxutils escape(descriptionkeywords ",join([xml sax saxutils escape(kfor in keywords]if keywords else "stylesheet (stylesheet_template format(stylesheetif stylesheet else ""html html_template format(**locals()to get the copyright text we call str format(on the copyright_templatesupplying the year and name (suitably html-escapedas positional arguments to replace { and { for the title and description we produce html-escaped copies of their texts str format( for the html keywords we have two cases to deal withand we distinguish them using conditional expression if no keywords have been enteredwe set the keywords string to be the empty using otherwisewe use list comprehension to iterate over all the keywords to produce new list of stringswith each one being html-escaped this list is then joined into single string with comma separating each item using str join(the stylesheet text is created in similar way to the copyright textbut within the context of conditional expression so that the text is the empty string if no stylesheet is specified using str format(with mapping unpacking the html text is created from the html_templatewith keyword arguments used to provide the data for the replacement fields rather than the positional arguments used for the other template strings rather than pass each argument explicitly using key=value syntaxwe have used mapping unpacking on the mapping returned by locals(to do this for us (the alternative would be to write the format(call as format(title=titlecopyright=copyrightetc fh none tryfh open(filename" "encoding="utf "fh write(htmlexcept environmenterror as errprint("error"errelseprint("saved skeleton"filenamefinallyif fh is not nonefh close(once the html has been prepared we write it to the file with the given filename we inform the user that the skeleton has been saved--or of the error message if something went wrong as usual we use finally clause to ensure that the file is closed if it was opened |
8,731 | control structures and functions def get_string(messagename="string"default=noneminimum_length= maximum_length= )message +"if default is none else [{ }]format(defaultwhile truetryline input(messageif not lineif default is not nonereturn default if minimum_length = return "elseraise valueerror("{ may not be emptyformatname)if not (minimum_length <len(line<maximum_length)raise valueerror("{namemust have at least "{minimum_lengthand at most "{maximum_lengthcharactersformat**locals())return line except valueerror as errprint("error"errusing str format(with mapping unpacking this function has one mandatory argumentmessageand four optional arguments if default value is given we include it in the message string so that the user can see the default they would get if they just press enter without typing any text the rest of the function is enclosed in an infinite loop the loop can be broken out of by the user entering valid string--or by accepting the default (if givenby just pressing enter if the user makes mistakean error message is printed and the loop continues as usualrather than explicitly using key=value syntax to pass local variables to str format(with format string that uses named fieldswe have simply used mapping unpacking on the mapping returned by locals(to do this for us the user could also break out of the loopand indeed out of the entire programby typing ctrl+ --this would cause keyboardinterrupt exception to be raisedand since this is not handled by any of the program' exception handlerswould cause the program to terminate and print traceback should we leave such "loophole"if we don'tand there is bug in our programwe could leave the user stuck in an infinite loop with no way out except to kill the process unless there is very strong reason to prevent ctrl+ from terminating programit should not be caught by any exception handler notice that this function is not specific to the make_html_skeleton py program--it could be reused in many interactive programs of this type such reuse could be achieved by copying and pastingbut that would lead to main |
8,732 | tenance headaches--in the next we will see how to create custom modules with functionality that can be shared across any number of programs def get_integer(messagename="integer"default=noneminimum= maximum= allow_zero=true)this function is so similar in structure to the get_string(function that it would add nothing to reproduce it here (it is included in the source code that accompanies the bookof course the allow_zero parameter can be useful when is not valid value but where we want to permit one invalid value to signify that the user has cancelled another approach would be to pass an invalid default valueand if that is returnedtake it to mean that the user has cancelled the last statement in the program is simply call to main(overall the program is slightly more than lines and shows several features of the python language introduced in this and the previous ones summary ||this covered the complete syntax for all of python' control structures it also showed how to raise and catch exceptionsand how to create custom exception types most of the was devoted to custom functions we saw how to create functions and presented some rules of thumb for naming functions and their parameters we also saw how to provide documentation for functions python' versatile parameter syntax and argument passing were covered in detailincluding both fixed and variable numbers of positional and keyword argumentsand default values for arguments of both immutable and mutable data types we also briefly recapped sequence unpacking with and showed how to do mapping unpacking with *mapping unpacking is particularly useful when applied to dictionary (or other mapping)or to the mapping returned by locals()for passing key-value arguments to str format(format string that uses named fields if we need to assign new value to global variable inside functionwe can do so by declaring that the variable is globalthereby preventing python from creating local variable and assigning to that in generalthoughit is best to use global variables only for constants lambda functions are often used as key functionsor in other contexts where functions must be passed as parameters this showed how to create lambda functionsboth as anonymous functions and as means of creating small named one-line functions by assigning them to variable |
8,733 | control structures and functions the also covered the use of the assert statement this statement is very useful for specifying the preconditions and postconditions that we expect to be true on every use of functionand can be real aid to robust programming and bug hunting in this we covered all the fundamentals of creating functionsbut many other techniques are available to us these include creating dynamic functions (creating functions at runtimepossibly with implementations that differ depending on circumstances)covered in local (nestedfunctionscovered in and recursive functionsgenerator functionsand so oncovered in although python has considerable amount of built-in functionalityand very extensive standard libraryit is still likely that we will write some functions that would be useful in many of the programs we develop copying and pasting such functions would lead to maintenance nightmaresbut fortunately python provides clean easy-to-use solutioncustom modules in the next we will learn how to create our own modules with our own functions inside them we will also see how to import functionality from the standard library and from our own modulesand will briefly review what the standard library has to offer so that we can avoid reinventing the wheel exercise ||write an interactive program that maintains lists of strings in files when the program is run it should create list of all the files in the current directory that have the lst extension use os listdir("to get all the files and filter out those that don' have the lst extension if there are no matching files the program should prompt the user to enter filename--adding the lst extension if the user doesn' enter it if there are one or more lst files they should be printed as numbered list starting from the user should be asked to enter the number of the file they want to loador in which case they should be asked to give filename for new file if an existing file was specified its items should be read if the file is emptyor if new file was specifiedthe program should show message"no items are in the listif there are no itemstwo options should be offered"addand "quitonce the list has one or more itemsthe list should be shown with each item numbered from and the options offered should be "add""delete""save(unless already saved)and "quitif the user chooses "quitand there are unsaved changes they should be given the chance to save here is transcript of session with the program (with most blank lines removedand without the "list keepertitle shown above the list each time) |
8,734 | choose filenamemovies -no items are in the list -[ ]dd [ ]uit [ ] add itemlove actually love actually [ ]dd [ ]elete [ ]ave add itemabout boy about boy love actually [ ]dd [ ]elete [ ]ave add itemalien [ ]uit [ ] [ ]uit [ ] about boy alien love actually [ ]dd [ ]elete [ ]ave [ ]uit [ ] errorinvalid choice--enter one of 'aaddssqqpress enter to continue [ ]dd [ ]elete [ ]ave [ ]uit [ ] delete item number (or to cancel) about boy love actually [ ]dd [ ]elete [ ]ave [ ]uit [ ] saved items to movies lst press enter to continue about boy love actually [ ]dd [ ]elete [ ]uit [ ]add itemfour weddings and funeral about boy four weddings and funeral love actually [ ]dd [ ]elete [ ]ave [ ]uit [ ] save unsaved changes ( / [ ]saved items to movies lst keep the main(function fairly small (less than linesand use it to provide the program' main loop write function to get the new or existing filename (and in the latter case to load the items)and function to present the options and get the user' choice of option also write functions to add an itemdelete an itemprint list (of either items or filenames)load the listand save the list either copy the get_string(and get_integer(functions from make_html_skeleton pyor write your own versions |
8,735 | control structures and functions when printing the list or the filenamesprint the item numbers using field width of if there are less than ten itemsof if there are less than itemsand of otherwise keep the items in case-insensitive alphabetical orderand keep track of whether the list is "dirty(has unsaved changesoffer the "saveoption only if the list is dirty and ask the user whether they want to save unsaved changes when they quit only if the list is dirty adding or deleting an item will make the list dirtysaving the list will make it clean again model solution is provided in listkeeper pyit is less than lines of code |
8,736 | modules and packages overview of python' standard library |||modules whereas functions allow us to parcel up pieces of code so that they can be reused throughout programmodules provide means of collecting sets of functions (and as we will see in the next custom data typestogether so that they can be used by any number of programs python also has facilities for creating packages--these are sets of modules that are grouped togetherusually because their modules provide related functionality or because they depend on each other this first section describes the syntaxes for importing functionality from modules and packages--whether from the standard libraryor from our own custom modules and packages the section then goes on to show how to create custom packages and custom modules two custom module examples are shownthe first introductory and the second illustrating how to handle many of the practical issues that arisesuch as platform independence and testing online documentation the second section provides brief overview of python' standard library it is important to be aware of what the library has to offersince using predefined functionality makes programming much faster than creating everything from scratch alsomany of the standard library' modules are widely usedwell testedand robust in addition to the overviewa few small examples are used to illustrate some common use cases and cross-references are provided for modules covered in other modules and packages || python modulesimply putis py file module can contain any python code we like all the programs we have written so far have been contained in single py fileand so they are modules as well as programs the key difference |
8,737 | modules is that programs are designed to be runwhereas modules are designed to be imported and used by programs not all modules have associated py files--for examplethe sys module is built into pythonand some modules are written in other languages (most commonlychowevermuch of python' library is written in pythonsofor exampleif we write import collections we can create named tuples by calling collections namedtuple()and the functionality we are accessing is in the collections py module file it makes no difference to our programs what language module is written insince all modules are imported and used in the same way several syntaxes can be used when importing for exampleimport importable import importable importable importablen import importable as preferred_name here importable is usually module such as collectionsbut could be package or module in packagein which case each part is separated with dot )for exampleos path the first two syntaxes are the ones we use throughout this book they are the simplest and also the safest because they avoid the possibility of having name conflictssince they force us to always use fully qualified names the third syntax allows us to give name of our choice to the package or module we are importing--theoretically this could lead to name clashesbut in practice the as syntax is used to avoid them renaming is particularly useful when experimenting with different implementations of module for exampleif we had two modules mymodulea and mymoduleb that had the same api (application programming interface)we could write import mymodulea as mymodule in programand later on seamlessly switch to using import mymoduleb as mymodule where should import statements goit is common practice to put all the import statements at the beginning of py filesafter the shebang lineand after the module' documentation and as we said back in we recommend importing standard library modules firstthen third-party library modulesand finally our own modules here are some other import syntaxesfrom importable import object as preferred_name from importable import object object objectn from importable import (object object object object object object objectnfrom importable import packages |
8,738 | these syntaxes can cause name conflicts since they make the imported objects (variablesfunctionsdata typesor modulesdirectly accessible if we want to use the from import syntax to import lots of objectswe can use multiple lines either by escaping each newline except the lastor by enclosing the object names in parenthesesas the third syntax illustrates in the last syntaxthe means "import everything that is not private"which in practical terms means either that every object in the module is imported except for those whose names begin with leading underscoreorif the module has global __all__ variable that holds list of namesthat all the objects named in the __all__ variable are imported here are few import examplesimport os print(os path basename(filename)safe fully qualified access import os path as path print(path basename(filename)risk of name collision with path from os import path print(path basename(filename)risk of name collision with path from os path import basename print(basename(filename)risk of name collision with basename from os path import print(basename(filename)risk of many name collisions the from importable import syntax imports all the objects from the module (or all the modules from the package)--this could be hundreds of names in the case of from os path import *almost names are importedincluding dirnameexistsand splitany of which might be names we would prefer to use for our own variables or functions for exampleif we write from os path import dirnamewe can conveniently call dirname(without qualification but if further on in our code we write dirname "the object reference dirname will now be bound to the string instead of to the dirname(functionso if we try calling dirname(we will get typeerror exception because dirname now refers to string and strings are not callable in view of the potential for name collisions the import syntax createssome programming teams specify in their guidelines that only the import importable syntax may be used howevercertain large packagesparticularly gui (graphical user interfacelibrariesare often imported this way because they have large numbers of functions and classes (custom data typesthat can be tedious to type out by hand question that naturally arises ishow does python know where to look for the modules and packages that are importedthe built-in sys module has __all__ |
8,739 | at every subsequent import of the module python will detect that the module has already been imported and will do nothing when python needs module' byte-code compiled codeit generates it automatically--this differs fromsayjavawhere compiling to byte code must be done explicitly first python looks for file with the same name as the module' py file but with the extension pyo--this is an optimized byte-code compiled version of the module if there is no pyo file (or if it is older than the py filethat isif it is out of date)python looks for file with the extension pyc--this is nonoptimized byte-code compiled version of the module if python finds an up-to-date byte-code compiled version of the moduleit loads itotherwisepython loads the py file and compiles byte-code compiled version either waypython ends up with the module in memory in byte-code compiled form if python had to byte-compile the py fileit saves pyc version (or pyo if - was specified on python' command lineor is set in the pythonoptimize environment variable)providing the directory is writable saving the byte code can be avoided by using the - command-line optionor by setting the pythondontwritebytecode environment variable using byte-code compiled files leads to faster start-up times since the interpreter only has to load and run the coderather than loadcompile(save if possible)and run the coderuntimes are not affectedthough when python is installedthe standard library modules are usually byte-code compiled as part of the installation process packages | package is simply directory that contains set of modules and file called __init__ py supposefor examplethat we had fictitious set of module files for reading and writing various graphics file formatssuch as bmp pyjpeg pypng pytiff pyand xpm pyall of which provided the functions load()save()and so on we could keep the modules in the same directory as our programbut for large program that uses scores of custom modules the graphics modules will be dispersed by putting them in their own subdirectorysaygraphicsthey can be kept together and if we put an empty __init__ py file in the graphics directory along with themthe directory will become packagegraphics__init__ py bmp py jpeg py extensive support for handling graphics files is provided by variety of third-party modulesmost notably the python imaging library (www pythonware com/products/pil |
8,740 | modules png py tiff py xpm py as long as the graphics directory is subdirectory inside our program' directory or is in the python pathwe can import any of these modules and make use of them we must be careful to ensure that our top-level module name (graphicsis not the same as any top-level name in the standard library so as to avoid name conflicts (on unix this is easily done by starting with an uppercase letter since all of the standard library' modules have lowercase names here' how we can import and use our moduleimport graphics bmp image graphics bmp load("bashful bmp"for short programs some programmers prefer to use shorter namesand python makes this possible using two slightly different approaches import graphics jpeg as jpeg image jpeg load("doc jpeg"here we have imported the jpeg module from the graphics package and told python that we want to refer to it simply as jpeg rather than using its fully qualified namegraphics jpeg from graphics import png image png load("dopey png"this code snippet imports the png module directly from the graphics package this syntax (from importmakes the png module directly accessible we are not obliged to use the original package names in our code for examplefrom graphics import tiff as picture image picture load("grumpy tiff"here we are using the tiff modulebut have in effect renamed it inside our program as the picture module in some situations it is convenient to load in all of package' modules using single statement to do this we must edit the package' __init__ py file to contain statement which specifies which modules we want loaded this statement must assign list of module names to the special variable __all__ for examplehere is the necessary line for the graphics/__init__ py file__all__ ["bmp""jpeg""png""tiff""xpm" |
8,741 | that is all that is requiredalthough we are free to put any other code we like in the __init__ py file now we can write different kind of import statementfrom graphics import image xpm load("sleepy xpm"the from package import syntax directly imports all the modules named in the __all__ list soafter this importnot only is the xpm module directly accessiblebut so are all the others as noted earlierthis syntax can also be applied to modulethat isfrom module import *in which case all the functionsvariablesand other objects defined in the module (apart from those whose names begin with leading underscorewill be imported if we want to control exactly what is imported when the from module import syntax is usedwe can define an __all__ list in the module itselfin which case doing from module import will import only those objects named in the __all__ list so far we have shown only one level of nestingbut python allows us to nest packages as deeply as we like so we could have subdirectory inside the graphics directorysayvectorwith module files inside thatsuch as eps py and svg pygraphics__init__ py bmp py jpeg py png py tiff py vector__init__ py eps py svg py xpm py for the vector directory to be package it must have an __init__ py fileand as notedthis can be empty or could have an __all__ list as convenience for programmers who want to import using from graphics vector import to access nested package we just build on the syntax we have already usedimport graphics vector eps image graphics vector eps load("sneezy eps"the fully qualified name is rather longso some programmers try to keep their module hierarchies fairly flat to avoid this |
8,742 | modules import graphics vector svg as svg image svg load("snow svg"we can always use our own short name for moduleas we have done herealthough this does increase the risk of having name conflict all the imports we have used so far (and that we will use throughout the rest of the bookare absolute imports--this means that every module we import is in one of sys path' directories (or subdirectories if the import name included one or more periods which effectively serve as path separatorswhen creating large multimodule multidirectory packages it is often useful to import other modules that are part of the same package for examplein eps py or svg py we could get access to the png module using conventional importor using relative importimport graphics png as png from graphics import png these two code snippets are equivalentthey both make the png module directly available inside the module where they are used but note that relative importsthat isimports that use the from module import syntax with leading dots in front of the module name (each dot representing stepping up one directory)can be used only in modules that are inside package using relative imports makes it easier to rename the top-level package and prevents accidentally importing standard modules rather than our own inside packages custom modules |since modules are just py files they can be created without formality in this section we will look at two custom modules the first moduletextutil (in file textutil py)contains just three functionsis_balanced(which returns true if the string it is passed has balanced parentheses of various kindsshorten((shown earlier )and simplify() function that can strip spurious whitespace and other characters from string in the coverage of this module we will also see how to execute the code in docstrings as unit tests the second modulechargrid (in file chargrid py)holds grid of characters and allows us to "drawlinesrectanglesand text onto the grid and to render the grid on the console this module shows some techniques that we have not seen before and is more typical of largermore complex modules the textutil module the structure of this module (and most othersdiffers little from that of program the first line is the shebang lineand then we have some comments (typically the copyright and license informationnext it is common to have |
8,743 | triple quoted string that provides an overview of the module' contentsoften including some usage examples--this is the module' docstring here is the start of the textutil py file (but with the license comment lines omitted)#!/usr/bin/env python copyright ( - qtrac ltd all rights reserved ""this module provides few string manipulation functions is_balanced("(python (is (not (lisp))))"true shorten("the crossing" 'the cro simplify(some text with spurious 'some text with spurious whitespace""whitespace "import string this module' docstring is available to programs (or other modulesthat import the module as textutil __doc__ after the module docstring come the importsin this case just oneand then the rest of the module shorten( we have already seen the shorten(function reproduced in fullso we will not repeat it here and since our focus is on modules rather than on functionsalthough we will show the simplify(function in fullincluding its docstringwe will show only the code for is_balanced(this is the simplify(functionbroken into two partsdef simplify(textwhitespace=string whitespacedelete="") """returns the text with multiple spaces reduced to single spaces the whitespace parameter is string of characterseach of which is considered to be space if delete is not empty it should be stringin which case any characters in the delete string are excluded from the resultant string simplify(this and\ that\ too"'this and that toosimplify(washington \ "'washington simplify(washington \ "delete=",;"'washington dcsimplify(disemvoweled "delete="aeiou"'dsmvwld"" |
8,744 | raw strings modules after the def line comes the function' docstringlaid out conventionally with single line descriptiona blank linefurther descriptionand then some examples written as though they were typed in interactively because the quoted strings are inside docstring we must either escape the backslashes inside themor do what we have done here and use raw triple quoted string result [word "for char in textif char in deletecontinue elif char in whitespaceif wordresult append(wordword "elseword +char if wordresult append(wordreturn join(resultthe result list is used to hold "words"--strings that have no whitespace or deleted characters the given text is iterated over character by characterwith deleted characters skipped if whitespace character is encountered and word is in the makingthe word is added to the result list and set to be an empty stringotherwisethe whitespace is skipped any other character is added to the word being built up at the end single string is returned consisting of all the words in the result list joined with single space between each one the is_balanced(function follows the same pattern of having def linethen docstring with single-line descriptiona blank linefurther descriptionand some examplesand then the code itself here is the code without the docstringdef is_balanced(textbrackets="()[]{}")counts {left_for_right {for leftright in zip(brackets[:: ]brackets[ :: ])assert left !right"the bracket characters must differcounts[left left_for_right[rightleft for in textif in countscounts[ + elif in left_for_rightleft left_for_right[ |
8,745 | if counts[left= return false counts[left- return not any(counts values()the function builds two dictionaries the counts dictionary' keys are the opening characters ("(""[""{"and "<")and its values are integers the left_for_right dictionary' keys are the closing characters (")""]""}"and ">")and its values are the corresponding opening characters once the dictionaries are set up the function iterates character by character over the text whenever an opening character is encounteredits corresponding count is incremented similarlywhen closing character is encounteredthe function finds out what the corresponding opening character is if the count for that character is it means we have reached one closing character too many so can immediately return falseotherwisethe relevant count is decremented at the end every count should be if all the pairs are balancedso if any one of them is not the function returns falseotherwiseit returns true up to this point everything has been much like any other py file if textutil py was program there would presumably be some more functionsand at the end we would have single call to one of those functions to start off the processing but since this is module that is intended to be importeddefining functions is sufficient and nowany program or module can import textutil and make use of itimport textutil text puzzling conundrum text textutil simplify(texttext =' puzzling conundrumif we want the textutil module to be available to particular programwe just need to put textutil py in the same directory as the program if we want textutil py to be available to all our programsthere are few approaches that can be taken one approach is to put the module in the python distribution' site-packages subdirectory--this is usually :\python \lib\site-packages on windowsbut it varies on mac os and other unixes this directory is in the python pathso any module that is here will always be found second approach is to create directory specifically for the custom modules we want to use for all our programsand to set the pythonpath environment variable to this directory third approach is to put the module in the local site-packages subdirectory--this is %appdata%\python\python \site-packages on windows and ~local/lib/python /site-packages on unix (including mac os xand is in the python path the second and third approaches have the advantage of keeping our own code separate from the official installation having the textutil module is all very wellbut if we end up with lots of programs using it we might want to be more confident that it works as advertised |
8,746 | modules one really simple way to do this is to execute the examples in the docstrings and make sure that they produce the expected results this can be done by adding just three lines at the end of the module' py fileif __name__ ="__main__"import doctest doctest testmod(whenever module is imported python creates variable for the module called __name__ and stores the module' name in this variable module' name is simply the name of its py file but without the extension so in this examplewhen the module is imported __name__ will have the value "textutil"and the if condition will not be metso the last two lines will not be executed this means that these last three lines have virtually no cost when the module is imported whenever py file is run python creates variable for the program called __name__ and sets it to the string "__main__so if we were to run textutil py as though it were programpython will set __name__ to "__main__and the if condition will evaluate to true and the last two lines will be executed the doctest testmod(function uses python' introspection features to discover all the functions in the module and their docstringsand attempts to execute all the docstring code snippets it finds running module like this produces output only if there are errors this can be disconcerting at first since it doesn' look like anything happened at allbut if we pass command-line flag of -vwe will get output like thistryingis_balanced("(python (is (not (lisp))))"expectingtrue ok tryingsimplify(disemvoweled "delete="aeiou"expecting'dsmvwldok items passed all tests tests in __main__ tests in __main__ is_balanced tests in __main__ shorten tests in __main__ simplify tests in items passed and failed test passed |
8,747 | we have used an ellipsis to indicate lot of lines that have been omitted if there are functions (or classes or methodsthat don' have teststhese are listed when the - option is used notice that the doctest module found the tests in the module' docstring as well as those in the functionsdocstrings examples in docstrings that can be executed as tests are called doctests note that when we write doctestswe are able to call simplify(and the other functions unqualified (since the doctests occur inside the module itselfoutside the moduleassuming we have done import textutilwe must use the qualified namesfor exampletextutil is_balanced(in the next subsection we will see how to do more thorough tests--in particulartesting cases where we expect failuresfor exampleinvalid data causing exceptions (testing is covered more fully in we will also address some other issues that arise when creating modulesincluding module initializationaccounting for platform differencesand ensuring that if the from module import syntax is usedonly the objects we want to be made public are actually imported into the importing program or module the chargrid module the chargrid module holds grid of characters in memory it provides functions for "drawinglinesrectanglesand text on the gridand for rendering the grid onto the console here are the module' docstring' doctestsresize( add_rectangle( *get_size()add_vertical_line( add_vertical_line( "!"add_horizontal_line( "+"add_rectangle( "%"add_rectangle( "#"trueadd_rectangle( "add_text( "this is the chargrid module"add_text( "pleasantville""@"add_rectangle( fill=truerender(falsethe chargrid add_rectangle(function takes at least four argumentsthe topleft corner' row and column and the bottom-right corner' row and column the character used to draw the outline can be given as fifth argumentand boolean indicating whether the rectangle should be filled (with the same character as the outlineas sixth argument the first time we call it we pass the third and fourth arguments by unpacking the -tuple (widthheight)returned by the chargrid get_size(function |
8,748 | modules by defaultthe chargrid render(function clears the screen before printing the gridbut this can be prevented by passing false as we have done here here is the grid that results from the preceding doctests%%%%%********************************************@@@@@@@@@@@@@@@pleasantville+++++++++@@@@@@@@@@@@@@%%%%################################################################***##***#this is the chargrid module #***##***################################***################################*************************************************the module begins in the same way as the textutil modulewith shebang linecopyright and license commentsand module docstring that describes the module and has the doctests quoted earlier then the code proper begins with two importsone of the sys module and the other of the subprocess module the subprocess module is covered more fully in the module has two error-handling policies in place several functions have char parameter whose actual argument must always be string containing exactly one charactera violation of this requirement is considered to be fatal coding errorso assert statements are used to verify the length but passing out-of-range row or column numbers is considered erroneous but normalso custom exceptions are raised when this happens we will now review some illustrative and key parts of the module' codebeginning with the custom exceptionsclass rangeerror(exception)pass class rowrangeerror(rangeerror)pass class columnrangeerror(rangeerror)pass none of the functions in the module that raise an exception ever raise rangeerrorthey always raise the specific exception depending on whether an out-of-range row or column was given but by using hierarchywe give users of the module the choice of catching the specific exceptionor to catch either of them by catching their rangeerror base class note also that inside doctests the exception names are used as they appear herebut if the module is imported with import chargridthe exception names areof coursechargrid rangeerrorchargrid rowrangeerrorand chargrid columnrangeerror |
8,749 | _char_assert_template ("char must be single character'{ }"is too long"_max_rows _max_columns _grid [_background_char here we define some private data for internal use by the module we use leading underscores so that if the module is imported using from chargrid import *none of these variables will be imported (an alternative approach would be to set an __all__ list the _char_assert_template is string for use with the str format(functionwe will see it used to give an error message in assert statements we will discuss the other variables as we encounter them if sys platform startswith("win")def clear_screen()subprocess call(["cmd exe""/ ""cls"]elsedef clear_screen()subprocess call(["clear"]clear_screen __doc__ """clears the screen using the underlying window system' clear screen command""the means of clearing the console screen is platform-dependent on windows we must execute the cmd exe program with appropriate arguments and on most unix systems we execute the clear program the subprocess module' subprocess call(function lets us run an external programso we can use it to clear the screen in the appropriate platform-specific way the sys platform string holds the name of the operating system the program is running onfor example"win or "linux so one way of handling the platform differences would be to have single clear_screen(function like thisdef clear_screen()command (["clear"if not sys platform startswith("win"else ["cmd exe""/ ""cls"]subprocess call(commandthe disadvantage of this approach is that even though we know the platform cannot change while the program is runningwe perform the check every time the function is called to avoid checking which platform the program is being run on every time the clear_screen(function is calledwe have created platform-specific clear_screen(function once when the module is importedand from then on we always use it this is possible because the def statement is python statement like any otherwhen the interpreter reaches the if it executes either the first or the second def statementdynamically creating one or the other |
8,750 | modules clear_screen(function since the function is not defined inside another function (or inside class as we will see in the next it is still global functionaccessible like any other function in the module after creating the function we explicitly set its docstringthis avoids us having to write the same docstring in two placesand also illustrates that docstring is simply one of the attributes of function other attributes include the function' module and its name def resize(max_rowsmax_columnschar=none)"""changes the size of the gridwiping out the contents and changing the background if the background char is not none ""assert max_rows and max_columns "too smallglobal _grid_max_rows_max_columns_background_char if char is not noneassert len(char= _char_assert_template format(char_background_char char _max_rows max_rows _max_columns max_columns _grid [[_background_char for column in range(_max_columns)for row in range(_max_rows)this function uses an assert statement to enforce the policy that it is coding error to attempt to resize the grid smaller than if background character is specified an assert is used to guarantee that it is string of exactly one characterif it is notthe assertion error message is the _char_assert_template' text with the { replaced with the given char string unfortunatelywe must use the global statement because we need to update number of global variables inside this function this is something that using an object-oriented approach can help us to avoidas we will see in list comprehensions the _grid is created using list comprehension inside list comprehension using list replication such as [[charcolumnsrows will not work because the inner list will be shared (shallow-copiedwe could have used nested for in loops instead_grid [for row in range(_max_rows)_grid append([]for column in range(_max_columns)_grid[- append(_background_charthis code is arguably trickier to understand than the list comprehensionand is much longer |
8,751 | we will review just one of the drawing functions to give flavor of how the drawing is donesince our primary concern is with the implementation of the module here is the add_horizontal_line(functionsplit into two partsdef add_horizontal_line(rowcolumn column char="-")"""adds horizontal line to the grid using the given char add_horizontal_line( "="char_at( =char_at( ="=true add_horizontal_line( traceback (most recent call last)rowrangeerror ""the docstring has two testsone that is expected to work and another that is expected to raise an exception when dealing with exceptions in doctests the pattern is to specify the "tracebacklinesince that is always the same and tells the doctest module an exception is expectedthen to use an ellipsis to stand for the intervening lines (which vary)and ending with the exception line we expect to get the char_at(function is one of those provided by the moduleit returns the character at the given row and column position in the grid assert len(char= _char_assert_template format(chartryfor column in range(column column )_grid[row][columnchar except indexerrorif not <row <_max_rowsraise rowrangeerror(raise columnrangeerror(the code begins with the same character length check that is used in the resize(function rather than explicitly checking the row and column argumentsthe function works by assuming that the arguments are valid if an indexerror exception occurs because nonexistent row or column is accessedwe catch the exception and raise the appropriate module-specific exception in its place this style of programming is known colloquially as "it' easier to ask forgiveness than permission"and is generally considered more pythonic (good python programming stylethan "look before you leap"where checks are made in advance relying on exceptions to be raised rather than checking in advance is more efficient when exceptions are rare (assertions don' count as "look before you leapbecause they should never occur--and are often commented out--in deployed code |
8,752 | modules almost at the end of the moduleafter all the functions have been definedthere is single call to resize()resize(_max_rows_max_columnsthis call initializes the grid to the default size ( and ensures that code that imports the module can safely make use of it immediately without this callevery time the module was importedthe importing program or module would have to call resize(to initialize the gridforcing programmers to remember that fact and also leading to multiple initializations if __name__ ="__main__"import doctest doctest testmod(the last three lines of the module are the standard ones for modules that use the doctest module to check their doctests (testing is covered more fully in the chargrid module has an important failingit supports only single character grid one solution to this would be to hold collection of grids in the modulebut that would mean that users of the module would have to provide key or index with every function call to identify which grid they were referring to in cases where multiple instances of an object are requireda better solution is to create module that defines class ( custom data type)since we can create as many class instances (objects of the data typeas we like an additional benefit of creating class is that we should be able to avoid using the global statement by storing class (staticdata we will see how to create classes in the next overview of python' standard library ||python' standard library is generally described as "batteries included"and certainly wide range of functionality is availablespread over around two hundred packages and modules in factso many high-quality modules have been developed for python over the yearsthat to include them all in the standard library would probably increase the size of the python distribution packages by at least an order of magnitude so those modules that are in the library are more reflection of python' history and of the interests of its core developers than of any concerted or systematic effort to create "balancedlibrary alsosome modules have proved very difficult to maintain within the library--most notably the berkeley db module--and so have been taken out of the library and are now maintained independently this means many excellent third-party modules are available for python that--despite their quality and usefulness--are not in the standard |
8,753 | library (we will look at two such modules later onthe pyparsing and ply modules that are used to create parsers in in this section we present broad overview of what is on offertaking thematic approachbut excluding those packages and modules that are of very specialized interest and those which are platform-specific in many cases small example is shown to give flavor of some of the packages and modulescross-references are provided for those packages and modules that are covered elsewhere in the book string handling |the string module provides some useful constants such as string ascii_letters and string hexdigits it also provides the string formatter class which we can subclass to provide custom string formatters the textwrap module can be used to wrap lines of text to specified widthand to minimize indentation the struct module provides functions for packing and unpacking numbersbooleansand strings to and from bytes objects using their binary representations this can be useful when handling data to be sent to or received from lowlevel libraries written in the struct and textwrap modules are used by the convert-incidents py program covered in the difflib module provides classes and methods for comparing sequencessuch as stringsand is able to produce output both in standard "diffformats and in html python' most powerful string handling module is the re (regular expressionmodule this is covered in the io stringio class can provide string-like object that behaves like an in-memory text file this can be convenient if we want to use the same code that writes to file to write to string examplethe io stringio class python provides two different ways of writing text to files one way is to use file object' write(methodand the other is to use the print(function with the file keyword argument set to file object that is open for writing for exampleprint("an error message"file=sys stdoutsys stdout write("another error message\ "the term subclassing (or specializingis used for when we create custom data type ( classbased on another class gives full coverage of this topic bytes type the struct module |
8,754 | modules both lines of text are printed to sys stdouta file object that represents the "standard output stream"--this is normally the console and differs from sys stderrthe "error output streamonly in that the latter is unbuffered (python automatically creates and opens sys stdinsys stdoutand sys stderr at program start-up the print(function adds newline by defaultalthough we can stop this by giving the end keyword argument set to an empty string in some situations it is useful to be able to capture into string the output that is intended to go to file this can be achieved using the io stringio class which provides an object that can be used just like file objectbut which holds any data written to it in string if the io stringio object is given an initial stringit can also be read as though it were file we can access io stringio if we do import ioand we can use it to capture output destined for file object such as sys stdoutsys stdout io stringio(if this line is put at the beginning of programafter the imports but before any use is made of sys stdoutany text that is sent to sys stdout will actually be sent to the io stringio file-like object which this line has created and which has replaced the standard sys stdout file object nowwhen the print(and sys stdout write(lines shown earlier are executedtheir output will go to the io stringio object instead of the console (at any time we can restore the original sys stdout with the statement sys stdout sys __stdout__ we can obtain all the strings that have been written to the io stringio object by calling the io stringio getvalue(functionin this case by calling sys stdout getvalue()--the return value is string containing all the lines that have been written this string could be printedor saved to log or sent over network connection like any other string we will see another example of io stringio use bit further on command-line programming |if we need program to be able to process text that may have been redirected in the console or that may be in files listed on the command linewe can use the fileinput module' fileinput input(function this function iterates over all the lines redirected from the console (if anyand over all the lines in the files listed on the command lineas one continuous sequence of lines the module can report the current filename and line number at any time using fileinput filename(and fileinput lineno()and can handle some kinds of compressed files two separate modules are provided for handling command-line optionsoptparse and getopt the getopt module is popular because it is simple to use |
8,755 | and has been in the library for long time the optparse module is newer and more powerful examplethe optparse module csv html py example back in we described the csv html py program in that exercises we proposed extending the program to accept the command-line arguments"maxwidthtaking an integer and "formattaking string the model solution (csv html _ans pyhas -line function to process the arguments here is the start of the main(function for csv html _opt pya version of the program that uses the optparse module to handle the command-line arguments rather than custom functiondef main()parser optparse optionparser(parser add_option("- ""--maxwidth"dest="maxwidth"type="int"help=("the maximum number of characters that can be "output to string fields [default%default]")parser add_option("- ""--format"dest="format"help=("the format used for outputting numbers "[default%default]")parser set_defaults(maxwidth= format= "optsargs parser parse_args(only nine lines of code are neededplus the import optparse statement furthermorewe do not need to explicitly provide - and --help optionsthese are handled by the optparse module to produce suitable usage message using the texts from the help keyword argumentsand with any "%defaulttext replaced with the option' default value notice also that the options now use the conventional unix style of having both short and long option names that start with hyphen short names are convenient for interactive use at the consolelong names are more understandable when used in shell scripts for exampleto set the maximum width to we can use any of - - --maxwidth= or --maxwidth after the command line is parsedthe options are available using the dest namesfor exampleopts maxwidth and opts format any command-line arguments that have not been processed (usually filenamesare in the args list if an error occurs when parsing the command linethe optparse parser will call sys exit( this leads to clean program termination and returns to the operating system as the program' result value conventionallya return value of signifies usage error signifies any other kind of errorand means success when sys exit(is called with no arguments it returns to the operating system |
8,756 | mathematics and numbers modules |in addition to the built-in intfloatand complex numbersthe library provides the decimal decimal and fractions fraction numbers three numeric libraries are availablemath for the standard mathematical functionscmath for complex number mathematical functionsand random which provides many functions for random number generationthese modules were introduced in python' numeric abstract base classes (classes that can be inherited from but that cannot be used directlyare in the numbers module they are useful for checking that an objectsayxis any kind of number using isinstance(xnumbers number)or is specific kind of numberfor exampleisinstance(xnumbers rationalor isinstance(xnumbers integralthose involved in scientific and engineering programming will find the thirdparty numpy package to be useful this module provides highly efficient -dimensional arraysbasic linear algebra functions and fourier transformsand tools for integration with cc++and fortran code the scipy package incorporates numpy and extends it to include modules for statistical computationssignal and image processinggenetic algorithmsand great deal more both are freely available from www scipy org times and dates |the calendar and datetime modules provide functions and classes for date and time handling howeverthey are based on an idealized gregorian calendarso they are not suitable for dealing with pre-gregorian dates time and date handling is very complex topic--the calendars in use have varied in different places and at different timesa day is not precisely hoursa year is not exactly daysand daylight saving time and time zones vary the datetime datetime class (but not the datetime date classhas provisions for handling time zonesbut does not do so out of the box third-party modules are available to make good this deficiencyfor exampledateutil from www labix org/python-dateutiland mxdatetime from www egenix com/products/python/mxbase/mxdatetime the time module handles timestamps these are simply numbers that hold the number of seconds since the epoch ( : : on unixthis module can be used to get timestamp of the machine' current time in utc (coordinated universal time)or as local time that accounts for daylight saving timeand to create datetimeand date/time strings formatted in various ways it can also parse strings that have dates and times |
8,757 | examplethe calendardatetimeand time modules objects of type datetime datetime are usually created programmaticallywhereas objects that hold utc date/times are usually received from external sourcessuch as file timestamps here are some examplesimport calendardatetimetime moon_datetime_a datetime datetime( moon_time calendar timegm(moon_datetime_a utctimetuple()moon_datetime_b datetime datetime utcfromtimestamp(moon_timemoon_datetime_a isoformat(returns' : : moon_datetime_b isoformat(returns' : : time strftime("% -% -%dt% :% :% "time gmtime(moon_time)the moon_datetime_a variable is of type datetime datetime and holds the date and time that apollo landed on the moon the moon_time variable is of type int and holds the number of seconds since the epoch to the moon landing--this number is provided by the calendar timegm(function which takes time_struct object returned by the datetime datetime utctimetuple(functionand returns the number of seconds that the time_struct represents (since the moon landing occurred before the unix epochthe number is negative the moon_datetime_b variable is of type datetime datetime and is created from the moon_time integer to show the conversion from the number of seconds since the epoch to datetime datetime object the last three lines all return identical iso -format date/time strings the current utc date/time is available as datetime datetime object by calling datetime datetime utcnow()and as the number of seconds since the epoch by calling time time(for the local date/timeuse datetime datetime now(or time mktime(time localtime()algorithms and collection data types |the bisect module provides functions for searching sorted sequences such as sorted listsand for inserting items while preserving the sort order this module' functions use the binary search algorithmso they are very fast the heapq module provides functions for turning sequence such as list into heap-- collection data type where the first item (at index position is always the smallest itemand for inserting and removing items while keeping the sequence as heap unfortunately for windows usersthe datetime datetime utcfromtimestamp(function can' handle negative timestampsthat istimestamps for dates prior to january |
8,758 | default dictionary named tuple ordered dictionary modules the collections package provides the collections defaultdict dictionary and the collections namedtuple collection data types that we have previously discussed in additionthis package provides the collections userlist and collections userdict typesalthough subclassing the built-in list and dict types is probably more common than using these types another type is collections dequewhich is similar to listbut whereas list is very fast for adding and removing items at the enda collections deque is very fast for adding and removing items both at the beginning and at the end python introduced the collections ordereddict and the collections counter classes ordereddicts have the same api as normal dictsalthough when iterated the items are always returned in insertion order ( from first to last inserted)and the popitem(method always returns the most recently added ( lastitem the counter class is dict subclass used to provide fast and easy way of keeping various counts given an iterable or mapping (such as dictionary) counter instance canfor examplereturn list of the unique elements or list of the most common elements as (elementcount -tuples python' non-numeric abstract base classes (classes that can be inherited from but that cannot be used directlyare also in the collections package they are discussed in the array module provides the array array sequence type that can store numbers or characters in very space-efficient way it has similar behavior to lists except that the type of object it can store is fixed when it is createdso unlike lists it cannot store objects of different types the third-party numpy package mentioned earlier also provides efficient arrays the weakref module provides functionality for creating weak references--these behave like normal object referencesexcept that if the only reference to an object is weak referencethe object can still be scheduled for garbage collection this prevents objects from being kept in memory simply because we have reference to them naturallywe can check whether the object weak reference refers to still existsand can access the object if it does examplethe heapq module the heapq module provides functions for converting list into heap and for adding and removing items from the heap while preserving the heap property heap is binary tree that respects the heap propertywhich is that the first item (at index position is always the smallest item each of heap' subtrees is also heapso they too respect the heap property here is how heap could be created from scratchstrictly speakingthe heapq module provides min heapheaps where the first item is always the largest are max heaps |
8,759 | import heapq heap [heapq heappush(heap( "rest")heapq heappush(heap( "work")heapq heappush(heap( "study")if we already have listwe can turn it into heap with heapq heapify(alist)this will do any necessary reordering in-place the smallest item can be removed from the heap using heapq heappop(heapfor in heapq merge([ ][ ][ ])print(xend="prints the heapq merge(function takes any number of sorted iterables as arguments and returns an iterator that iterates over all the items from all the iterables in order file formatsencodingsand data persistence character encodings |the standard library has extensive support for variety of standard file formats and encodings the base module has functions for reading and writing using the base base and base encodings specified in rfc the quopri module has functions for reading and writing "quoted-printableformat this format is defined in rfc and is used for mime (multipurpose internet mail extensionsdata the uu module has functions for reading and writing uuencoded data rfc defines the external data representation standard and module xdrlib provides functions for reading and writing data in this format modules are also provided for reading and writing archive files in the most popular formats the bz module can handle bz filesthe gzip module handles gz filesthe tarfile module handles tartar gz (also tgz)and tar bz filesand the zipfile module handles zip files we will see an example of using the tarfile module in this subsectionand later on there is small example that uses the gzip modulewe will also see the gzip module in action again in support is also provided for handling some audio formatswith the aifc module for aiff (audio interchange file formatand the wave module for (uncompressedwav files some forms of audio data can be manipulated using the audioop moduleand the sndhdr module provides couple of functions for determining what kind of sound data is stored in file and some of its propertiessuch as the sampling rate rfc (request for commentsdocuments are used to specify various internet technologies each one has unique identification number and many of them have become officially adopted standards |
8,760 | modules format for configuration files (similar to old-style windows ini filesis specified in rfc and the configparser module provides functions for reading and writing such files many applicationsfor exampleexcelcan read and write csv (comma separated valuedataor variants such as tab-delimited data the csv module can read and write these formatsand can account for the idiosyncracies that prevent csv files from being straightforward to handle directly in addition to its support of various file formatsthe standard library also has packages and modules that provide data persistence the pickle module is used to store and retrieve arbitrary python objects (including entire collectionsto and from diskthis module is covered in the library also supports dbm files of various kinds--these are like dictionaries except that their items are stored on disk rather than in memoryand both their keys and their values must be bytes objects or strings the shelve modulecovered in can be used to provide dbm files with string keys and arbitrary python objects as values--the module seamlessly converts the python objects to and from bytes objects behind the scenes the dbm modulespython' database apiand using the built-in sqlite database are all covered in examplethe base module the base module is mostly used for handling binary data that is embedded in emails as ascii text it can also be used to store binary data inside py files the first step is to get the binary data into base format here we assume that the base module has been imported and that the path and filename of png file are in the variable left_align_pngbinary open(left_align_png"rb"read(ascii_text "for ic in enumerate(base encode(binary))if and = ascii_text +"\\\nascii_text +chr(cleft_align png this code snippet reads the file in binary mode and converts it to base string of ascii characters every sixty-eighth character backslash-newline combination is added this limits the width of the lines of ascii characters to but ensures that when the data is read back the newlines will be ignored (because the backslash will escape themthe ascii text obtained like this can be stored as bytes literal in py filefor exampleleft_align_png """ivborw kggoaaaansuheugaaacaaaaagcayaaabzenr aaaabgdbtueaalgpc/xhbqaabytes type |
8,761 | bmquu pamvt +cwvv rcya uffmcki+bn tcwqcuzrdowbh zvcr+jzveaaaaaelftksuqmcc""we've omitted most of the lines as indicated by the ellipsis the data can be converted back to its original binary form like thisbinary base decode(left_align_pngthe binary data could be written to file using open(filename"wb"writebinarykeeping binary data in py files is much less compact than keeping it in its original formbut can be useful if we want to provide program that requires some binary data as single py file examplethe tarfile module most versions of windows don' come with support for the tar format that is so widely used on unix systems this inconvenient omission can easily be rectified using python' tarfile modulewhich can create and unpack tar and tar gz archives (known as tarballs)and with the right libraries installedtar bz archives the untar py program can unpack tarballs using the tarfile modulehere we will just show some key extractsstarting with the first import statementbz _available true tryimport bz except importerrorbz _available false the bz module is used to handle the bzip compression formatbut importing it will fail if python was built without access to the bzip library (the python binary for windows is always built with bzip compression built-init is only on some unix builds that it might be absent we account for the possibility that the module is not available using try except blockand keep boolean variable that we can refer to later (although we don' quote the code that uses ituntrusted_prefixes tuple(["/""\\"[ ":for in string ascii_letters]this statement creates the tuple ('/''\'' :'' :'' :'' :'' :'' :'any filename in the tarball being unpacked that begins with one of these is suspect--tarballs should not use absolute paths since then they risk overwriting system filesso as precaution we will not unpack any file whose name starts with one of these prefixes |
8,762 | modules def untar(archive)tar none trytar tarfile open(archivefor member in tar getmembers()if member name startswith(untrusted_prefixes)print("untrusted prefixignoring"member nameelif in member nameprint("suspect pathignoring"member nameelsetar extract(memberprint("unpacked"member nameexcept (tarfile tarerrorenvironmenterroras errerror(errfinallyif tar is not nonetar close(each file in tarball is called member the tarfile getmembers(function returns list of tarfile tarinfo objectsone for each member the member' filenameincluding its pathis in the tarfile tarinfo name attribute if the name begins with an untrusted prefixor contains in its pathwe output an error messageotherwisewe call tarfile extract(to save the member to disk the tarfile module has its own set of custom exceptionsbut we have taken the simplistic approach that if any exception occurs we output the error message and finish def error(messageexit_status= )print(messagesys exit(exit_statuswe have just quoted the error(function for completeness the (unquotedmain(function prints usage message if - or --help is givenotherwiseit performs some basic checks before calling untar(with the tarball' filename filedirectoryand process handling |the shutil module provides high-level functions for file and directory handlingincluding shutil copy(and shutil copytree(for copying files and entire directory treesshutil move(for moving directory treesand shutil rmtree(for removing entire directory treesincluding nonempty ones temporary files and directories should be created using the tempfile module which provides the necessary functionsfor exampletempfile mkstemp()and creates the temporaries in the most secure manner possible |
8,763 | the filecmp module can be used to compare files with the filecmp cmp(function and to compare entire directories with the filecmp cmpfiles(function one very powerful and effective use of python programs is to orchestrate the running of other programs this can be done using the subprocess module which can start other processescommunicate with them using pipesand retrieve their results this module is covered in an even more powerful alternative is to use the multiprocessing module which provides extensive facilities for offloading work to multiple processes and for accumulating resultsand can often be used as an alternative to multithreading the os module provides platform-independent access to operating system functionality the os environ variable holds mapping object whose items are environment variable names and their values the program' working directory is provided by os getcwd(and can be changed using os chdir(the module also provides functions for low-level file-descriptor-based file handling the os access(function can be used to determine whether file exists or whether it is readable or writableand the os listdir(function returns list of the entries ( the files and directoriesbut excluding the and entries)in the directory it is given the os stat(function returns various items of information about file or directorysuch as its modeaccess timeand size directories can be created using os mkdir()or if intermediate directories need to be createdusing os makedirs(empty directories can be removed using os rmdir()and directory trees that contain only empty directories can be removed using os removedirs(files or directories can be removed using os remove()and can be renamed using os rename(the os walk(function iterates over an entire directory treeretrieving the name of every file and directory in turn the os module also provides many low-level platform-specific functionsfor exampleto work with file descriptorsand to fork (only on unix systems)spawnand exec whereas the os module provides functions for interacting with the operating systemespecially in the context of the file systemthe os path module provides mixture of string manipulation (of paths)and some file system convenience functions the os path abspath(function returns the absolute path of its argumentwith redundant path separators and elements removed the os path split(function returns -tuple with the first element containing the path and the second the filename (which will be empty if path with no filename was giventhese two parts are also available directly using os path basename(and os path dirname( filename can also be split into two partsname and extensionusing os path splitext(the os path join(function takes any number of path strings and returns single path using the platform-specific path separator |
8,764 | modules if we need several pieces of information about file or directory we can use os stat()but if we need just one piecewe can use the relevant os path functionfor exampleos path exists()os path getsize()os path isfile()or os path isdir(the mimetypes module has the mimetypes guess_type(function that tries to guess the given file' mime type examplethe os and os path modules here is how we can use the os and os path modules to create dictionary where each key is filename (including its pathand where each value is the timestamp (seconds since the epochwhen the file was last modifiedfor those files in the given pathdate_from_name {for name in os listdir(path)fullname os path join(pathnameif os path isfile(fullname)date_from_name[fullnameos path getmtime(fullnamethis code is pretty straightforwardbut can be used only for the files in single directory if we need to traverse an entire directory tree we can use the os walk(function here is code snippet taken from the finddup py program the code creates dictionary where each key is -tuple (file sizefilenamewhere the filename excludes the pathand where each value is list of the full filenames that match their key' filename and have the same file sizedata collections defaultdict(listfor rootdirsfiles in os walk(path)for filename in filesfullname os path join(rootfilenamekey (os path getsize(fullname)filenamedata[keyappend(fullnamefor each directoryos walk(returns the root and two listsone of the subdirectories in the directory and the other of the files in the directory to get the full path for filename we need to combine just the root and the filename notice that we do not have to recurse into the subdirectories ourselves--os walk(does that for us once the data has been gatheredwe can iterate over it to produce report of possible duplicate filesa much more sophisticated find duplicates programfindduplicates- pywhich uses multiple threads and md checksumsis covered in |
8,765 | for sizefilename in sorted(data)names data[(sizefilename)if len(names print("{filename({sizebytesmay be duplicated "({ files):format(len(names)**locals())for name in namesprint("\ { }format(name)because the dictionary keys are (sizefilenametupleswe don' need to use key function to get the data sorted in size order if any (sizefilenametuple has more than one filename in its listthese might be duplicates shell dll ( bytesmay be duplicated ( files)\windows\system \shell dll \windows\system \dllcache\shell dll this is the last item taken from the lines of output produced by running finddup py \windows on windows xp system networking and internet programming |packages and modules for networking and internet programming are major part of python' standard library at the lowest levelthe socket module provides the most fundamental network functionalitywith functions for creating socketsdoing dns (domain name systemlookupsand handling ip (internet protocoladdresses encrypted and authenticated sockets can be set up using the ssl module the socketserver module provides tcp (transmission control protocoland udp (user datagram protocolservers these servers can handle requests directlyor can create separate process (by forkingor separate thread to handle each request asynchronous client and server socket handling can be achieved using the asyncore module and the higher-level asynchat module that is built on top of it python has defined the wsgi (web server gateway interfaceto provide standard interface between web servers and web applications written in python in support of the standard the wsgiref package provides reference implementation of wsgi that has modules for providing wsgi-compliant http serversand for handling response header and cgi (common gateway interfacescripts in additionthe http server module provides an http server which can be given request handler ( standard one is provided)to run cgi scripts the http cookies and http cookiejar modules provide functions for managing cookiesand cgi script support is provided by the cgi and cgitb modules |
8,766 | modules client access to http requests is provided by the http client modulealthough the higher-level urllib package' modulesurllib parseurllib requesturllib responseurllib errorand urllib robotparserprovide easier and more convenient access to urls grabbing file from the internet is as simple asfh urllib request urlopen("html fh read(decode("utf "the urllib request urlopen(function returns an object that behaves much like file object opened in read binary mode here we retrieve the python web site' index html file (as bytes object)and store it as string in the html variable it is also possible to grab files and store them in local files with the urllib request urlretrieve(function html and xhtml documents can be parsed using the html parser moduleurls can be parsed and created using the urllib parse moduleand robots txt files can be parsed with the urllib robotparser module data that is represented using json (javascript object notationcan be read and written using the json module in addition to http server and client supportthe library provides xml-rpc (remote procedure callsupport with the xmlrpc client and xmlrpc server modules additional client functionality is provided for ftp (file transfer protocolby the ftplib modulefor nntp (network news transfer protocolby the nntplib moduleand for telnet with the telnetlib module the smtpd module provides an smtp (simple mail transfer protocolserverand the email client modules are smtplib for smtpimaplib for imap (internet message access protocol)and poplib for pop (post office protocolmailboxes in various formats can be accessed using the mailbox module individual messages (including multipart messagescan be created and manipulated using the email module if the standard library' packages and modules are insufficient in this areatwisted (www twistedmatrix comprovides comprehensive third-party networking library many third-party web programming libraries are also availableincluding django (www djangoproject comand turbogears (www turbogears orgfor creating web applicationsand plone (www plone organd zope (www zope orgwhich provide complete web frameworks and content management systems all of these libraries are written in python xml |there are two widely used approaches to parsing xml documents one is the dom (document object modeland the other is sax (simple api for xmltwo dom parsers are providedone by the xml dom module and the other by the xml dom minidom module sax parser is provided by the xml sax mod |
8,767 | ule we have already used the xml sax saxutils module for its xml sax saxutils escape(function (to xml-escape "&"""there is also an xml sax saxutils quoteattr(function that does the same thing but additionally escapes quotes (to make the text suitable for tag' attribute)and xml sax saxutils unescape(to do the opposite conversion two other parsers are available the xml parsers expat module can be used to parse xml documents with expatproviding the expat library is availableand the xml etree elementtree can be used to parse xml documents using kind of dictionary/list interface (by defaultthe dom and element tree parsers themselves use the expat parser under the hood writing xml manually and writing xml using dom and element treesand parsing xml using the domsaxand element tree parsersis covered in there is also third-party librarylxml (www codespeak net/lxml)that claims to be "the most feature-rich and easy-to-use library for working with xml and html in the python language this library provides an interface that is essentially superset of what the element tree module providesas well as many additional features such as support for xpathxsltand many other xml technologies examplethe xml etree elementtree module python' dom and sax parsers provide the apis that experienced xml programmers are used toand the xml etree elementtree module offers more pythonic approach to parsing and writing xml the element tree module is fairly recent addition to the standard libraryand so may not be familiar to some readers in view of thiswe will present very short example here to give flavor of it-provides more substantial example and provides comparative code using dom and sax the government' noaa (national oceanic and atmospheric administrationweb site provides wide variety of dataincluding an xml file that lists the weather stations the file is more than lines long and contains details of around two thousand stations here is typical entrykbos ma bostonlogan international airport the xml etree elementtree module first appeared in python |
8,768 | modules we have cut out few lines and reduced the indentation that is present in the file the file is about in sizeso we have compressed it using gzip to more manageable unfortunatelythe element tree parser requires either filename or file object to readbut we cannot give it the compressed file since that will just appear to be random binary data we can solve this problem with two initial stepsbinary gzip open(filenameread(fh io stringio(binary decode("utf ")io stringio the gzip module' gzip open(function is similar to the built-in open(except that it reads gzip-compressed files (those with extension gzas raw binary data we need the data available as file that the element tree parser can work withso we use the bytes decode(method to convert the binary data to string using utf- encoding (which is what the xml file uses)and we create file-like io stringio object with the string containing the entire xml file as its data tree xml etree elementtree elementtree(root tree parse(fhstations [for element in tree getiterator("station_name")stations append(element texthere we create new xml etree elementtree elementtree object and give it file object from which to read the xml we want it to parse as far as the element tree parser is concerned it has been passed file object open for readingalthough in fact it is reading string inside an io stringio object we want to extract the names of all the weather stationsand this is easily achieved using the xml etree elementtree elementtree getiterator(method which returns an iterator that returns all the xml etree elementtree element objects that have the given tag name we just use the element' text attribute to retrieve the text like os walk()we don' have to do any recursion ourselvesthe iterator method does that for us nor do we have to specify tag--in which case the iterator will return every element in the entire xml document other modules |we don' have the space to cover the nearly packages and modules that are available in the standard library nonethelessthis general overview should be sufficient to get flavor of what the library provides and some of the key packages in the major areas it serves in this section' final subsection we discuss just few more areas of interest in the previous section we saw how easy it is to create tests in docstrings and to run them using the doctest module the library also has unit-testing bytes type |
8,769 | framework provided by the unittest module--this is python version of the java junit test framework the doctest module also provides some basic integration with the unittest module (testing is covered more fully in several third-party testing frameworks are also availablefor examplepy test from codespeak net/py/dist/test/test html and nose from code google com/ /python-nose noninteractive applications such as servers often report problems by writing to log files the logging module provides uniform interface for loggingand in addition to being able to log to filesit can log using http get or post requestsor using email or sockets the library provides many modules for introspection and code manipulationand although most of them are beyond the scope of this bookone that is worth mentioning is pprint which has functions for "pretty printingpython objectsincluding collection data typeswhich is sometimes useful for debugging we will see simple use of the inspect module that introspects live objects in the threading module provides support for creating threaded applicationsand the queue module provides three different kinds of thread-safe queues threading is covered in python has no native support for gui programmingbut several gui libraries can be used by python programs the tk library is available using the tkinter moduleand is usually installed as standard gui programming is introduced in the abc (abstract base classmodule provides the functions necessary for creating abstract base classes this module is covered in shallow and deep copying the copy module provides the copy copy(and copy deepcopy(functions that were discussed in access to foreign functionsthat isto functions in shared libraries dll files on windowsdylib files on mac os xand so files on linux)is available using the ctypes module python also provides apiso it is possible to create custom data types and functions in and make these available to python both the ctypes module and python' api are beyond the scope of this book if none of the packages and modules mentioned in this section provides the functionality you needbefore writing anything from scratch it is worth checking the python documentation' global module index to see whether suitable module is availablesince we have not been able to mention every one here and failing thattry looking at the python package index (pypi python org/pypiwhich contains several thousand python add-ons ranging from small one-file modules all the way up to large library and framework packages containing anything from scores to hundreds of modules |
8,770 | summary modules ||the began by introducing the various syntaxes that can be used for importing packagesmodulesand objects inside modules we noted that many programmers only use the import importable syntax so as to avoid name clashesand that we must be careful not to give program or module the same name as top-level python module or directory also discussed were python packages these are simply directories with an __init__ py file and one or more py modules inside them the __init__ py file can be emptybut to support the from importable import syntaxwe can create an __all__ special variable in the __init__ py file set to list of module names we can also put any common initialization code in the __init__ py file it was noted that packages can be nested simply by creating subdirectories and having each of these contain its own __init__ py file two custom modules were described the first just provided few functions and had very simple doctests the second was more elaborate with its own exceptionsthe use of dynamic function creation to create function with platform-specific implementationprivate global dataa call to an initialization functionand more elaborate doctests about half the was devoted to high-level overview of python' standard library several string handling modules were mentioned and couple of io stringio examples were presented one example showed how to write text to file using either the built-in print(function or file object' write(methodand how to use an io stringio object in place of real file in previous we handled command-line options by reading sys argv ourselvesbut in the coverage of the library' support for command-line programming we introduced the optparse module which greatly simplifies command-line argument handling--we will use this module extensively from now on mention was made of python' excellent support for numbersand the library' numeric types and its three modules of mathematical functionsas well as the support for scientific and engineering mathematics provided by the scipy project both library and third-party date/time handling classes were briefly described and examples of how to obtain the current date/time and how to convert between datetime datetime and the number of seconds since the epoch were shown also discussed were the additional collection data types and the algorithms for working with ordered sequences that the standard library providesalong with some examples of using the heapq module' functions the modules that support various file encodings (besides character encodingswere discussedas well as the modules for packing and unpacking the most popular archive formatsand those that have support for audio data an example showing how to use the base encoding to store binary data in py files was givenand also program to unpack tarballs considerable support is provided |
8,771 | for handling directories and files--and all of this is abstracted into platformindependent functions examples were shown for creating dictionary with filename keys and last modified timestamp valuesand for doing recursive search of directory to identify possible duplicate files based on their name and size large part of the library is devoted to networking and internet programming we very briefly surveyed what is availablefrom raw sockets (including encrypted sockets)to tcp and udp serversto http servers and support for the wsgi also mentioned were the modules for handling cookiescgi scriptsand http dataand for parsing htmlxhtmland urls other modules that were mentioned included those for handling xml-rpc and for handling higher-level protocols such as ftp and nntpas well as the email client and server support using smtp and client support for imap and pop the library' comprehensive support for xml writing and parsing was also mentionedincluding the domsaxand element tree parsersand the expat module and an example was given using the element tree module mention was also made of some of the many other packages and modules that the library provides python' standard library represents an extremely useful resource that can save enormous amounts of time and effortand in many cases allows us to write much smaller programs by relying on the functionality that the library provides in additionliterally thousands of third-party packages are available to fill any gaps the standard library may have all of this predefined functionality allows us to focus much more on what we want our programs to dowhile leaving the library modules to take care of most of the details this brings us to the end of the fundamentals of procedural programming later and particularly will look at more advanced and specialized procedural techniquesand the following introduces object-oriented programming using python as purely procedural language is both possible and practical--especially for small programs--but for medium to large programsfor custom packages and modulesand for long-term maintainabilitythe object-oriented approach usually wins out fortunatelyall that we have covered up to now is both useful and relevant in object-oriented programmingso the subsequent will continue to build up our python knowledge and skills based on the foundations that have now been laid exercise ||write program to show directory listingsrather like the dir command in windows or ls in unix the benefit of creating our own listing program is that we can build in the defaults we prefer and can use the same program on |
8,772 | modules all platforms without having to remember the differences between dir and ls create program that supports the following interfaceusagels py [options[path [path pathn]]the paths are optionalif not given is used options- --help show this help message and exit - --hidden show hidden files [defaultoff- --modified show last modified date/time [defaultoff- order--order=order order by ('name'' ''modified'' ''size'' '[defaultname- --recursive recurse into subdirectories [defaultoff- --sizes show sizes [defaultoff(the output has been modified slightly to fit the book' page here is an example of output on small directory using the command line ls py -ms -os misc/ : : : : : : , misc/abstract pdf , misc/klmqtintro lyx , , misc/tracking pdf misc/phonelog files directory we used option grouping in the command line (optparse handles this automatically for us)but the same could have been achieved using separate optionsfor examplels py - - -os misc/or by even more groupingls py -msos misc/or by using long optionsls py --modified --sizes --order=size misc/or any combination of these note that we define "hiddenfile or directory as one whose name begins with dot the exercise is quite challenging you will need to read the optparse documentation to see how to provide options that set true valueand how to offer fixed list of choices if the user sets the recursive option you will need to process the files (but not the directoriesusing os walk()otherwiseyou will have to use os listdir(and process both files and directories yourself one rather tricky aspect is avoiding hidden directories when recursing they can be cut out of os walk()' dirs list--and therefore skipped by os walk()--by modifying that list but be careful not to assign to the dirs variable itselfsince that won' change the list it refers to but will simply (and uselesslyreplace itthe approach used in the model solution is to assign to slice of the whole listthat isdirs[:[dir for dir in dirs if not dir startswith(")locale setlocale( the best way to get grouping characters in the file sizes is to import the locale modulecall locale setlocale(to get the user' default localeand use the format character overallls py is about lines split over four functions |
8,773 | the object-oriented approach custom classes custom collection classes object-oriented programming |||in all the previous we used objects extensivelybut our style of programming has been strictly procedural python is multiparadigm language--it allows us to program in proceduralobject-orientedand functional styleor in any mixture of stylessince it does not force us to program in any one particular way it is perfectly possible to write any program in procedural styleand for very small programs (up tosay lines)doing so is rarely problem but for most programsand especially for medium-size and large programsobject-oriented programming offers many advantages this covers all the fundamental concepts and techniques for doing object-oriented programming in python the first section is especially for those who are less experienced and for those coming from procedural programming background (such as or fortranthe section starts by looking at some of the problems that can arise with procedural programming that object-oriented programming can solve then it briefly describes python' approach to objectoriented programming and explains the relevant terminology after thatthe two main sections begin the second section covers the creation of custom data types that hold single items (although the items themselves may have many attributes)and the third section covers the creation of custom collection data types that can hold any number of objects of any types these sections cover most aspects of object-oriented programming in pythonalthough we defer some more advanced material to |
8,774 | object-oriented programming the object-oriented approach ||in this section we will look at some of the problems of purely procedural approach by considering situation where we need to represent circlespotentially lots of them the minimum data required to represent circle is its (xyposition and its radius one simple approach is to use -tuple for each circle for examplecircle ( one drawback of this approach is that it isn' obvious what each element of the tuple represents we could mean (xyradiusorjust as easily(radiusxyanother drawback is that we can access the elements by index position only if we have two functionsdistance_from_origin(xyand edge_distance_from_origin(xyradius)we would need to use tuple unpacking to call them with circle tupledistance distance_from_origin(*circle[: ]distance edge_distance_from_origin(*circleboth of these assume that the circle tuples are of the form (xyradiuswe can solve the problem of knowing the element order and of using tuple unpacking by using named tupleimport collections circle collections namedtuple("circle"" radius"circle circle( distance distance_from_origin(circle xcircle ythis allows us to create circle -tuples with named attributes which makes function calls much easier to understandsince to access elements we can use their names unfortunatelyproblems remain for examplethere is nothing to stop an invalid circle from being createdcircle circle( - it doesn' make sense to have circle with negative radiusbut the circle named tuple is created here without raising an exception--just as it would be if the radius was given as variable that held negative number the error will be noticed only if we call the edge_distance_from_origin(function--and then only if that function actually checks for negative radius this inability to validate when creating an object is probably the worst aspect of taking purely procedural approach if we want circles to be mutable so that we can move them by changing their coordinates or resize them by changing their radiuswe can do so by using the private collections namedtuple _replace(method |
8,775 | circle circle _replace(radius= just as when we create circlethere is nothing to stop us from (or warn us aboutsetting invalid data if the circles were going to need lots of changeswe might opt to use mutable data type such as listfor the sake of conveniencecircle [ this doesn' give us any protection from putting in invalid dataand the best we can do about accessing elements by name is to create some constants so that we can write things like circle[radius but using list brings additional problems--for examplewe can legitimately call circle sort()using dictionary might be an alternativefor examplecircle dict( = = radius= )but again there is no way to ensure valid radius and no way to prevent inappropriate methods from being called object-oriented concepts and terminology |what we need is some way to package up the data that is needed to represent circleand some way to restrict the methods that can be applied to the data so that only valid operations are possible both of these things can be achieved by creating custom circle data type we will see how to create circle data type in later in this sectionbut first we need to cover some preliminaries and explain some terminology don' worry if the terminology is unfamiliar at firstit will become much clearer once we reach the examples we use the terms classtypeand data type interchangeably in python we can create custom classes that are fully integrated and that can be used just like the built-in data types we have already encountered many classesfor exampledictintand str we use the term objectand occasionally the term instanceto refer to an instance of particular class for example is an int object and "oblongis str object most classes encapsulate both data and the methods that can be applied to that data for examplethe str class holds string of unicode characters as its data and supports methods such as str upper(many classes also support additional featuresfor examplewe can concatenate two strings (or any two sequencesusing the operator and find sequence' length using the built-in len(function such features are provided by special methods--these are like normal methods except that their names always begin and end with two underscoresand are predefined for exampleif we want to create class that supports concatenation using the operator and also the len(functionwe can do so by implementing the __add__(and __len__(special methods in our class converselywe should never define any method with name that begins and ends with two underscores unless it is one of the predefined special methods and is |
8,776 | object-oriented programming appropriate to our class this will ensure that we never get conflicts with later versions of python even if they introduce new predefined special methods objects usually have attributes--methods are callable attributesand other attributes are data for examplea complex object has imag and real attributes and lots of methodsincluding special methods like __add__(and __sub__ (to support the binary and operators)and normal methods like conjugate(data attributes (often referred to simply as "attributes"are normally implemented as instance variablesthat isvariables that are unique to particular object we will see examples of thisand also examples of how to provide data attributes as properties property is an item of object data that is accessed like an instance variable but where the accesses are handled by methods behind the scenes as we will seeusing properties makes it easy to do data validation inside method (which is just function whose first argument is the instance on which it is called to operate)several kinds of variables are potentially accessible the object' instance variables can be accessed by qualifying their name with the instance itself local variables can be created inside the methodthese are accessed without qualification class variables (sometimes called static variablescan be accessed by qualifying their name with the class nameand global variablesthat ismodule variablesare accessed without qualification some of the python literature uses the concept of namespacea mapping from names to objects modules are namespaces--for exampleafter the statement import math we can access objects in the math module by qualifying them with their namespace name ( math pi and math sin()similarlyclasses and objects are also namespacesfor exampleif we have complex( )the object' namespace has two attributes which we can access ( real and imagone of the advantages of object orientation is that if we have classwe can specialize it this means that we make new class that inherits all the attributes (data and methodsfrom the original classusually so that we can add or replace methods or add more instance variables we can subclass (another term for specialize)any python classwhether built-in or from the standard libraryor one of our own custom classes the ability to subclass is one of the great advantages offered by object-oriented programming since it makes it straightforward to use an existing class that has tried and tested functionality as the basis for new class that extends the originaladding new data attributes or new functionality in very clean and direct way furthermorewe can pass objects of our new class to functions and methods that were written for the original class and they will work correctly we use the term base class to refer to class that is inheriteda base class may be the immediate ancestoror may be further up the inheritance tree another term for base class is super class we use the term subclassderived some library classes that are implemented in cannot be subclassedsuch classes specify this in their documentation |
8,777 | object-oriented programming some object-oriented languages have two features that python does not provide the first is overloadingthat ishaving methods with the same name but with different parameter lists in the same class thanks to python' versatile argument-handling capabilities this is never limitation in practice the second is access control--there are no bulletproof mechanisms for enforcing data privacy howeverif we create attributes (instance variables or methodsthat begin with two leading underscorespython will prevent unintentional accesses so that they can be considered to be private (this is done by name manglingwe will see an example in just as we use an uppercase letter as the first letter of custom moduleswe will do the same thing for custom classes we can define as many classes as we likeeither directly in program or in modules--class names don' have to match module namesand modules may contain as many class definitions as we like now that we have seen some of the problems that classes can solveintroduced the necessary terminologyand covered some background matterswe can begin to create some custom classes custom classes ||in earlier we created custom classescustom exceptions here are two new syntaxes for creating custom classesclass classnamesuite class classname(base_classes)suite since the exception subclasses we created did not add any new attributes (no instance data or methodswe used suite of pass ( nothing added)and since the suite was just one statement we put it on the same line as the class statement itself note that just like def statementsclass is statementso we can create classes dynamically if we want to class' methods are created using def statements in the class' suite class instances are created by calling the class with any necessary argumentsfor examplex complex( creates complex number and sets to be an object reference to it attributes and methods |let' start with very simple classpointthat holds an (xycoordinate the class is in file shape pyand its complete implementation (excluding docstringsis show hereclass point |
8,778 | def __init__(selfx= = )self self def distance_from_origin(self)return math hypot(self xself ydef __eq__(selfother)return self =other and self =other def __repr__(self)return "point({ ! }{ ! })format(selfdef __str__(self)return "({ ! }{ ! })format(selfsince no base classes are specifiedpoint is direct subclass of objectjust as though we had written class point(objectbefore we discuss each of the methodslet' see some examples of their useimport shape shape point(repr(ab shape point( str(bb distance_from_origin( - str(ba =ba ! returns'point( )returns'( )returns returns'(- )returns(falsetruethe point class has two data attributesself and self yand five methods (not counting inherited methods)four of which are special methodsthey are illustrated in figure once the shape module is importedthe point class can be used like any other the data attributes can be accessed directly ( )and the class integrates nicely with all of python' other classes by providing support for the equality operator (==and for producing strings in representational and string forms and python is smart enough to supply the inequality operator (!=based on the equality operator (it is also possible to specify each operator individually if we want total controlfor exampleif they are not exact opposites of each other python automatically supplies the first argument in method calls--it is an object reference to the object itself (called this in +and javawe must include this argument in the parameter listand by convention the parameter is called self all object attributes (data and method attributesmust be qualified by self this requires little bit more typing compared with some other languagesbut has the advantage of providing absolute claritywe always know that we are accessing an object attribute if we qualify with self |
8,779 | object-oriented programming object __new__(__init__(__eq__(__repr__(__str__(key inherited implemented reimplemented point __new__(__init__(distance_from_origin(__eq__(__repr__(__str__(figure the point class' inheritance hierarchy to create an objecttwo steps are necessary first raw or uninitialized object must be createdand then the object must be initializedready for use some object-oriented languages (such as +and javacombine these two steps into onebut python keeps them separate when an object is created ( shape point())first the special method __new__(is called to create the objectand then the special method __init__(is called to initialize it in practice almost every python class we create will require us to reimplement only the __init__(methodsince the object __new__(method is almost always sufficient and is automatically called if we don' provide our own __new__(method (later in this we will show rare example where we do need to reimplement __new__(not having to reimplement methods in subclass is another benefit of object-oriented programming--if the base class method is sufficient we don' have to reimplement it in our subclass this works because if we call method on an object and the object' class does not have an implementation of that methodpython will automatically go through the object' base classesand their base classesand so onuntil it finds the method--and if the method is not found an attributeerror exception is raised for exampleif we execute shape point()python begins by looking for the method point __new__(since we have not reimplemented this methodpython looks for the method in point' base classes in this case there is only one base classobjectand this has the required methodso python calls object __new__(and creates raw uninitialized object then python looks for the initializer__init__()and since we have reimplemented itpython doesn' need to look further and calls point __init__(finallypython sets to be an object reference to the newly created and initialized object of type point because they are so short and few pages awayfor convenience we will show each method again before discussing it alternative fuzzybool |
8,780 | def __init__(selfx= = )self self the two instance variablesself and self yare created in the initializerand assigned the values of the and parameters since python will find this initializer when we create new point objectthe object __init__(method will not be called this is because as soon as python has found the required method it calls it and doesn' look further object-oriented purists might start the method off with call to the base class __init__(method by calling super(__init__(the effect of calling the super(function like this is to call the base class' __init__(method for classes that directly inherit object there is no need to do thisand in this book we call base class methods only when necessary--for examplewhen creating classes that are designed to be subclassedor when creating classes that don' directly inherit object this is to some extent matter of coding style--it is perfectly reasonable to always call super(__init__(at the start of custom class' __init__(method def distance_from_origin(self)return math hypot(self xself ythis is conventional method that performs computation based on the object' instance variables it is quite common for methods to be fairly short and to have only the object they are called on as an argumentsince often all the data the method needs is available inside the object def __eq__(selfother)return self =other and self =other methods should not have names that begin and end with two underscores--unless they are one of the predefined special methods python provides special methods for all the comparison operators as shown in table all instances of custom classes support =by defaultand the comparison returns false--unless we compare custom object with itself we can override this behavior by reimplementing the __eq__(special method as we have done here python will supply the __ne__((not equalinequality operator (!=automatically if we implement __eq__(but don' implement __ne__(by defaultall instances of custom classes are hashableso hash(can be called on them and they can be used as dictionary keys and stored in sets but if we reimplement __eq__()instances are no longer hashable we will see how to fix this when we discuss the fuzzybool class later on by implementing this special method we can compare point objectsbut if we were to try to compare point with an object of different type--sayint--we fuzzybool |
8,781 | object-oriented programming table comparison special methods special method usage description __lt__(selfotherx __le__(selfotherx < returns true if is less than or equal to __eq__(selfotherx = returns true if is equal to __ne__(selfotherx ! returns true if is not equal to __ge__(selfotherx > returns true if is greater than or equal to __gt__(selfotherx returns true if is less than returns true if is greater than would get an attributeerror exception (since ints don' have an attributeon the other handwe can compare point objects with other objects that coincidentally just happen to have an attribute (thanks to python' duck typing)but this may lead to surprising results if we want to avoid inappropriate comparisons there are few approaches we can take one is to use an assertionfor exampleassert isinstance(otherpointanother is to raise typeerror to indicate that comparisons between the two types are not supportedfor exampleif not isinstance(otherpoint)raise typeerror(the third way (which is also the most pythonically correctis to do thisif not isinstance(otherpoint)return notimplemented in this third caseif notimplemented is returnedpython will then try calling other __eq__(selfto see whether the other type supports the comparison with the point typeand if there is no such method or if that method also returns notimplementedpython will give up and raise typeerror exception (note that only reimplementations of the comparison special methods listed in table may return notimplemented the built-in isinstance(function takes an object and class (or tuple of classes)and returns true if the object is of the given class (or of one of the tuple of classes)or of one of the class' (or one of the tuple of classes'base classes def __repr__(self)return "point({ ! }{ ! })format(selfstr format( the built-in repr(function calls the __repr__(special method for the object it is given and returns the result the string returned is one of two kinds one kind is where the string returned can be evaluated using the built-in eval(function to produce an object equivalent to the one repr(was called on the other kind is used where this is not possiblewe will see an example later on here is how we can go from point object to string and back to point object |
8,782 | shape point( repr(pq eval( __module__ repr( )repr(qimport returns'point( )returns'point( )we must give the module name when eval()-ing if we used import shape (this would not be necessary if we had done the import differentlyfor examplefrom shape import point python provides every object with few private attributesone of which is __module__a string that holds the object' module namewhich in this example is "shapeat the end of this snippet we have two point objectsp and qboth with the same attribute valuesso they compare as equal the eval(function returns the result of executing the string it is given--which must contain valid python statement def __str__(self)return "({ ! }{ ! })format(selfthe built-in str(function works like the repr(functionexcept that it calls the object' __str__(special method the result is intended to be understandable to human readers and is not expected to be suitable for passing to the eval(function continuing the previous examplestr( (or str( )would return the string '( )we have now covered the simple point class--and also covered lot of behindthe-scenes details that are important to know but which can mostly be left in the background the point class holds an (xycoordinate-- fundamental part of what we need to represent circleas we discussed at the beginning of the in the next subsection we will see how to create custom circle classinheriting from point so that we don' have to duplicate the code for the and attributes or for the distance_from_origin(method inheritance and polymorphism |the circle class builds on the point class using inheritance the circle class adds one additional data attribute (radius)and three new methods it also reimplements few of point' methods here is the complete class definitionclass circle(point)def __init__(selfradiusx= = )super(__init__(xyself radius radius def edge_distance_from_origin(self)return abs(self distance_from_origin(self radiusdynamic code execution |
8,783 | of its computation since the circle class does not provide an implementation of the distance_from_origin(methodthe one provided by the point base class will be found and used contrast this with the reimplementation of the __eq__(method this method compares this circle' radius with the other circle' radiusand if they are equal it then explicitly calls the base class' __eq__(method using super(if we did not use super(we would have infinite recursionsince circle __eq__(would then just keep calling itself notice also that we don' have to pass the self argument in the super(calls since python automatically passes it for us here are couple of usage examplesp shape point( shape circle( distance_from_origin( distance_from_origin(returns returns we can call the distance_from_origin(method on point or on circlesince circles can stand in for points polymorphism means that any object of given class can be used as though it were an object of any of its class' base classes this is why when we create subclass we need to implement only the additional methods we require and have to reimplement only those existing methods we want to replace and when reimplementing methodswe can use the base class' implementation if necessary by using super(inside the reimplementation in the circle' case we have implemented additional methodssuch as area(and circumference()and reimplemented methods we needed to change the reimplementations of __repr__(and __str__(are necessary because without them the base class methods will be used and the strings returned will be of points instead of circles the reimplementations of __init__(and __eq__(are necessary because we must account for the fact that circles have an additional attributeand in both cases we make use of the base class implementations of the methods to minimize the work we must do shallow and deep copying the point and circle classes are as complete as we need them to be we could provide additional methodssuch as other comparison special methods if we wanted to be able to order points or circles another thing that we might want to do for which no method is provided is to copy point or circle most python classes don' provide copy(method (exceptions being dict copy(and set copy()if we want to copy point or circle we can easily do so by importing the copy module and using the copy copy(function (there is no need to use copy deepcopy(for point and circle objects since they contain only immutable instance variables |
8,784 | object-oriented programming using properties to control attribute access |in the previous subsection the point class included distance_from_origin(methodand the circle class had the area()circumference()and edge_distance_from_origin(methods all these methods return single float valueso from the point of view of user of these classes they could just as well be data attributesbut read-onlyof course in the shapealt py file alternative implementations of point and circle are providedand all the methods mentioned here are provided as properties this allows us to write code like thiscircle shape circle( circle radius circle edge_distance_from_origin assumesimport shapealt as shape returns returns here are the implementations of the getter methods for the shapealt circle class' area and edge_ distance_from_origin properties@property def area(self)return math pi (self radius * @property def edge_distance_from_origin(self)return abs(self distance_from_origin self radiusif we provide only getters as we have done herethe properties are read-only the code for the area property is the same as for the previous area(method the edge_distance_from_origin' code is slightly different from before because it now accesses the base class' distance_from_origin property instead of calling distance_from_origin(method the most notable difference to both is the property decorator decorator is function that takes function or method as its argument and returns "decoratedversionthat isa version of the function or method that is modified in some way decorator is indicated by preceding its name with an at symbol (@for nowjust treat decorators as syntax--in we will see how to create custom decorators the property(decorator function is built-in and takes up to four argumentsa getter functiona setter functiona deleter functionand docstring the effect of using @property is the same as calling the property(function with just one argumentthe getter function we could have created the area property like thisdef area(self)return math pi (self radius * area property(areawe rarely use this syntaxsince using decorator is shorter and clearer |
8,785 | in the previous subsection we noted that no validation is performed on the circle' radius attribute we can provide validation by making radius into property this does not require any changes to the circle __init__(methodand any code that accesses the circle radius attribute will continue to work unchanged--only now the radius will be validated whenever it is set python programmers normally use properties rather than the explicit getters and setters ( getradius(and setradius()that are so commonly used in other object-oriented languages this is because it is so easy to change data attribute into property without affecting the use of the class to turn an attribute into readable/writable property we must create private attribute where the data is actually held and supply getter and setter methods here is the radius' gettersetterand docstring in full@property def radius(self)"""the circle' radius circle circle(- traceback (most recent call last)assertionerrorradius must be nonzero and non-negative circle circle( circle radius - traceback (most recent call last)assertionerrorradius must be nonzero and non-negative circle radius ""return self __radius @radius setter def radius(selfradius)assert radius "radius must be nonzero and non-negativeself __radius radius we use an assert to ensure nonzero and non-negative radius and store the radius' value in the private attribute self __radius notice that the getter and setter (and deleter if we needed oneall have the same name--it is the decorators that distinguish themand the decorators rename them appropriately so that no name conflicts occur the decorator for the setter may look strange at first sight every property that is created has gettersetterand deleter attributeso once the radius property is created using @propertythe radius getterradius setterand radius deleter attributes become available the radius getter is set to the |
8,786 | object-oriented programming getter method by the @property decorator the other two are set up by python so that they do nothing (so the attribute cannot be written to or deleted)unless they are used as decoratorsin which case they in effect replace themselves with the method they are used to decorate the circle' initializercircle __init__()includes the statement self radius radiusthis will call the radius property' setterso if an invalid radius is given when circle is created an assertionerror exception will be raised similarlyif an attempt is made to set an existing circle' radius to an invalid valueagain the setter will be called and an exception raised the docstring includes doctests to test that the exception is correctly raised in these cases (testing is covered more fully in both the point and circle types are custom data types that have sufficient functionality to be useful most of the data types that we are likely to create are like thisbut occasionally it is necessary to create custom data type that is complete in every respect we will see examples of this in the next subsection creating complete fully integrated data types |when creating complete data type two possibilities are open to us one is to create the data type from scratch although the data type will inherit object (as all python classes do)every data attribute and method that the data type requires (apart from __new__()must be provided the other possibility is to inherit from an existing data type that is similar to the one we want to create in this case the work usually involves reimplementing those methods we want to behave differently and "unimplementingthose methods we don' want at all in the following subsubsection we will implement fuzzybool data type from scratchand in the subsubsection after that we will implement the same type but will use inheritance to reduce the work we must do the built-in bool type is two-valued (true and false)but in some areas of ai (artificial intelligence)fuzzy booleans are usedwhich have values corresponding to "trueand "false"and also to intermediates between them in our implementations we will use floating-point values with denoting false and denoting true in this system means percent trueand means percent trueand so on here are some usage examples (they work the same with either implementation) fuzzybool fuzzybool fuzzybool fuzzybool > bool( )bool( ~ returnstrue returns(truefalsereturnsfuzzybool( |
8,787 | |fuzzybool fuzzybool " ={ % ={ %}format(ab returnsfuzzybool( is nowfuzzybool( returns' = = %we want the fuzzybool type to support the complete set of comparison operators (=>)and the three basic logical operationsnot (~)and (&)and or (|in addition to the logical operations we want to provide couple of other logical methodsconjunction(and disjunction()that take as many fuzzybools as we like and return the appropriate resultant fuzzybool and to complete the data type we want to provide conversions to types boolintfloatand strand have an eval()-able representational form the final requirements are that fuzzybool supports str format(format specificationsthat fuzzybools can be used as dictionary keys or as members of setsand that fuzzybools are immutable--but with the provision of augmented assignment operators (&and |=to ensure that they are convenient to use table ( lists the comparison special methodstable lists the fundamental special methodsand table lists the numeric special methods--these include the bitwise operators (~&and |which fuzzybools use for their logical operatorsand also arithmetic operators such as and which fuzzybool does not implement because they are inappropriate creating data types from scratch to create the fuzzybool type from scratch means that we must provide an attribute to hold the fuzzybool' value and all the methods that we require here are the class line and the initializertaken from fuzzybool pyclass fuzzybooldef __init__(selfvalue= )self __value value if <value < else shapealt circle radius property we have made the value attribute private because we want fuzzybool to behave like immutablesso allowing access to the attribute would be wrong alsoif an out-of-range value is given we force it to take fail-safe value of (falsein the previous subsection' shapealt circle class we used stricter policyraising an exception if an invalid radius value was used when creating new circle object the fuzzybool' inheritance tree is shown in figure the simplest logical operator is logical notfor which we have coopted the bitwise inversion operator (~)def __invert__(self)return fuzzybool( self __value |
8,788 | object __new__(__init__(__eq__(__repr__(__str__(__hash__(__format__(key inherited implemented reimplemented fuzzybool __value __new__(__init__(__eq__(__repr__(__str__(__hash__(__format__(__bool__(__float__(__invert__(__and__(__iand__(conjunction(static figure the fuzzybool class' inheritance hierarchy def __iand__(selfother)self __value min(self __valueother __valuereturn self the bitwise and operator returns new fuzzybool based on this one and the other onewhereas the augmented assignment (in-placeversion updates the private value strictly speakingthis is not immutable behaviorbut it does match the behavior of some other python immutablessuch as intwherefor exampleusing +looks like the left-hand operand is being changed but in fact it is re-bound to refer to new int object that holds the result of the addition in this case no rebinding is needed because we really do change the fuzzybool itself and we return self to support the chaining of operations we could also implement __rand__(this method is called when self and other are of different types and the __and__(method is not implemented for that particular pair of types this isn' needed for the fuzzybool class most of the special methods for binary operators have both " (in-placeand " (reflectthat isswap operandsversions we have not shown the implementation for __or__(which provides the bitwise operatoror for __ior__(which provides the in-place |operatorsince both are the same as the equivalent and methods except that we take the maximum value instead of the minimum value of self and other def __repr__(self)return ("{ }({ })format(self __class__ __name__self __value) |
8,789 | object-oriented programming we have created an eval()-able representational form for examplegiven fuzzybool fuzzybool )repr(fwill produce the string 'fuzzybool( )all objects have some special attributes automatically supplied by pythonone of which is called __class__a reference to the object' class all classes have private __name__ attributeagain provided automatically we have used these attributes to provide the class name used for the representation form this means that if the fuzzybool class is subclassed just to add extra methodsthe inherited __repr__(method will work correctly without needing to be reimplementedsince it will pick up the subclass' class name def __str__(self)return str(self __valuefor the string form we just return the floating-point value formatted as string we don' have to use super(to avoid infinite recursion because we call str(on the self __value attributenot on the instance itself def __bool__(self)return self __value def __int__(self)return round(self __valuedef __float__(self)return self __value the __bool__(special method converts the instance to booleanso it must always return either true or false the __int__(special method provides integer conversion we have used the built-in round(function because int(simply truncates (so would return for any fuzzybool value except floating-point conversion is easy because the value is already floating-point number def __lt__(selfother)return self __value other __value def __eq__(selfother)return self __value =other __value to provide the complete set of comparisons (=>it is necessary to implement at least three of themfrom from <we have shown only two representative methods here since all of them are very similar def __hash__(self)return hash(id(self)in factwe implemented only the __lt__(and __eq__(methods quoted here--the other comparison methods were automatically generatedwe will see how in complete comparisons |
8,790 | table numeric and bitwise special methods special method usage special method usage __abs__(selfabs(x__complex__(selfcomplex(x__float__(selffloat(x__int__(selfint(x__index__(selfbin(xoct(x__round__(selfhex(xdigitsround(xdigits__pos__(self+ __neg__(self- __add__(selfotherx __sub__(selfotherx __iadd__(selfotherx + __isub__(selfotherx - __radd__(selfothery __rsub__(selfothery __mul__(selfotherx __mod__(selfotherx __imul__(selfotherx * __imod__(selfotherx % __rmul__(selfothery __rmod__(selfothery __floordiv__(selfotherx / __truediv__(selfotherx __ifloordiv__(selfotherx // __itruediv__(selfotherx / __rfloordiv__(selfothery / __rtruediv__(selfothery __divmod__(selfotherdivmod(xy__rdivmod__(selfotherdivmod(yx__pow__(selfotherx * __and__(selfotherx __ipow__(selfotherx ** __iand__(selfotherx & __rpow__(selfothery * __rand__(selfothery __xor__(selfotherx __or__(selfotherx __ixor__(selfotherx ^ __ior__(selfotherx | __rxor__(selfothery __ror__(selfothery __lshift__(selfotherx < __rshift__(selfotherx > __ilshift__(selfotherx << __irshift__(selfotherx >> __rlshift__(selfothery < __rrshift__(selfothery > __invert__(self~ |
8,791 | object-oriented programming by defaultinstances of custom classes support operator =(which always returns false)and are hashable (so can be dictionary keys and can be added to setsbut if we reimplement the __eq__(special method to provide proper equality testinginstances are no longer hashable this can be fixed by providing __hash__(special method as we have done here python provides hash functions for stringsnumbersfrozen setsand other classes here we have simply used the built-in hash(function (which can operate on any type which has __hash__(special method)and given it the object' unique id from which to calculate the hash (we can' use the private self __value since that can change as result of augmented assignmentwhereas an object' hash value must never change the built-in id(function returns unique integer for the object it is given as its argument this integer is usually the object' address in memorybut all that we can assume is that no two objects have the same id behind the scenes the is operator uses the id(function to determine whether two object references refer to the same object def __format__(selfformat_spec)return format(self __valueformat_specthe built-in format(function is only really needed in class definitions it takes single object and an optional format specification and returns string with the object suitably formatted fuzzybool usage examples when an object is used in format string the object' __format__(method is called with the object and the format specification as arguments the method returns the instance suitably formatted as we saw earlier all the built-in classes already have suitable __format__(methodshere we make use of the float __format__(method by passing the floating-point value and the format string we have been given we could have achieved exactly the same thing like thisdef __format__(selfformat_spec)return self __value __format__(format_specusing the format(function requires tiny bit less typing and is clearer to read nothing forces us to use the format(function at allso we could invent our own format specification language and interpret it inside the __format__(methodas long as we return string @staticmethod def conjunction(*fuzzies)return fuzzybool(min([float(xfor in fuzzies]) |
8,792 | the built-in staticmethod(function is designed to be used as decorator as we have done here static methods are simply methods that do not get self or any other first argument specially passed by python the operator can be chainedso given fuzzybool' fgand hwe can get the conjunction of all of them by writing this works fine for small numbers of fuzzyboolsbut if we have dozen or more it starts to become rather inefficient since each represents function call with the method given here we can achieve the same thing using single function call of fuzzybool fuzzybool conjunction(fghthis can be written more concisely using fuzzybool instancebut since static methods don' get selfif we call one using an instance and we want to process that instance we must pass it ourselves--for examplef conjunction(fghwe have not shown the corresponding disjunction(method since it differs only in its name and that it uses max(rather than min(some python programmers consider the use of static methods to be un-pythonicand use them only if they are converting code from another language (such as +or java)or if they have method that does not use self in pythonrather than using static methods it is usually better to create module function insteadas we will see in the next subsubsectionor class methodas we will see in the last section in similar veincreating variable inside class definition but outside any method creates static (classvariable for constants it is usually more convenient to use private module globalsbut class variables can often be useful for sharing data among all of class' instances we have now completed the implementation of the fuzzybool class "from scratchwe have had to reimplement methods ( if we had done the minimum of all four comparison operators)and have implemented two static methods in the following subsubsection we will show an alternative implementationthis time based on the inheritance of float it involves the reimplementations of just eight methods and the implementation of two module functions--and the "unimplementationof methods in most object-oriented languages inheritance is used to create new classes that have all the methods and attributes of the classes they inheritas well as the additional methods and attributes that we want the new class to have python fully supports thisallowing us to add new methodsor to reimplement inherited methods so as to modify their behavior but in additionpython allows us to effectively unimplement methodsthat isto make the new class behave as though it does not have some of the methods that it inherits doing this might not appeal to object-oriented purists since it breaks polymorphismbut in python at leastit can occasionally be useful technique |
8,793 | object-oriented programming creating data types from other data types the fuzzybool implementation in this subsubsection is in the file fuzzyboolalt py one immediate difference from the previous version is that instead of providing static methods for conjunction(and disjunction()we have provided them as module functions for exampledef conjunction(*fuzzies)return fuzzybool(min(fuzzies)the code for this is much simpler than before because fuzzyboolalt fuzzybool objects are float subclassesand so can be used directly in place of float without needing any conversion (the inheritance tree is shown in figure accessing the function is also cleaner than before instead of having to specify both the module and the class (or using an instance)having done import fuzzyboolalt we can just write fuzzyboolalt conjunction(object float fuzzybool __new__(__init__(__eq__(__repr__(__str__(__new__(__init__(__eq__(__repr__(__str__(__hash__(__format__(__new__(__init__(__eq__(__repr__(__str__(__hash__(__format__(__bool__(__invert__(__and__(__iand__(key inherited implemented reimplemented figure the alternative fuzzybool class' inheritance hierarchy here is the fuzzybool' class line and its __new__(methodclass fuzzybool(float)def __new__(clsvalue= )return super(__new__(clsvalue if <value < else when we create new class it is usually mutable and relies on object __new__(to create the raw uninitialized object but in the case of immutable classes we need to do the creation and initialization in one step since once an immutable object has been created it cannot be changed |
8,794 | the __new__(method is called before any object has been created (since object creation is what __new__(does)so it cannot have self object passed to it since one doesn' yet exist in fact__new__(is class method--these are similar to normal methods except that they are called on the class rather than on an instance and python supplies as their first argument the class they are called on the variable name cls for class is just conventionin the same way that self is the conventional name for the object itself so when we write fuzzybool( )under the hood python calls fuzzybool __new__(fuzzybool to create new object--sayfuzzy--and then calls fuzzy __init__(to do any further initializationand finally returns an object reference to the fuzzy object--it is this object reference that is set to most of __new__()' work is passed on to the base class implementationobject __new__()all we do is make sure that the value is in range class methods are set up by using the built-in classmethod(function used as decorator but as convenience we don' have to bother writing @classmethod before def __new__(because python already knows that this method is always class method we do need to use the decorator if we want to create other class methodsthoughas we will see in the final section now that we have seen class method we can clarify the different kinds of methods that python provides class methods have their first argument added by python and it is the method' classnormal methods have their first argument added by python and it is the instance the method was called onand static methods have no first argument added and all the kinds of methods get any arguments we pass to them (as their second and subsequent arguments in the case of class and normal methodsand as their first and subsequent arguments for static methodsdef __invert__(self)return fuzzybool( float(self)this method is used to provide support for the bitwise not operator (~just the same as before notice that instead of accessing private attribute that holds the fuzzybool' value we use self directly this is thanks to inheriting float which means that fuzzybool can be used wherever float is expected--providing none of the fuzzybool' "unimplementedmethods are usedof course def __and__(selfother)return fuzzybool(min(selfother)def __iand__(selfother)return fuzzybool(min(selfother)the logic for these is also the same as before (although the code is subtly different)and just like the __invert__(method we can use both self and other |
8,795 | object-oriented programming directly as though they were floats we have omitted the or versions since they differ only in their names (__or__(and __ior__()and that they use max(rather than min(def __repr__(self)return ("{ }({ })format(self __class__ __name__super(__repr__())we must reimplement the __repr__(method since the base class version float __repr__(just returns the number as stringwhereas we need the class name to make the representation eval()-able for the str format()' second argument we cannot just pass self since that will result in an infinite recursion of calls to this __repr__(methodso instead we call the base class implementation we don' have to reimplement the __str__(method because the base class versionfloat __str__()is sufficient and will be used in the absence of fuzzybool __str__(reimplementation def __bool__(self)return self def __int__(self)return round(selfwhen float is used in boolean context it is false if its value is and true otherwise this is not the appropriate behavior for fuzzyboolsso we have had to reimplement this method similarlyusing int(selfwould simply truncateturning everything but into so here we use round(to produce for values up to and for values up to and including the maximum of we have not reimplemented the __hash__(methodthe __format__(methodor any of the methods that are used to provide the comparison operatorssince all those provided by the float base class work correctly for fuzzybools the methods we have reimplemented provide complete implementation of the fuzzybool class--and have required far less code than the implementation presented in the previous subsubsection howeverthis new fuzzybool class has inherited more than methods which don' make sense for fuzzybools for examplenone of the basic numeric and bitwise shift operators (+-*/<<>>etc can sensibly be applied to fuzzybools here is how we could begin to "unimplementadditiondef __add__(selfother)raise notimplementederror(we would also have to write the same code for the __iadd__(and __radd__(methods to completely prevent addition (note that notimplementederror is standard exception and is different from the built-in notimplemented object an |
8,796 | alternative to raising notimplementederror exceptionespecially if we want to more closely mimic the behavior of python' built-in classesis to raise typeerror here is how we can make fuzzybool __add__(behave just like built-in classes that are faced with an invalid operationdef __add__(selfother)raise typeerror("unsupported operand type(sfor +"'{ }and '{ }'formatself __class__ __name__other __class__ __name__)for unary operationswe want to unimplement in way that mimics the behavior of built-in typesthe code is slightly easierdef __neg__(self)raise typeerror("bad operand type for unary -'{ }'formatself __class__ __name__)for comparison operatorsthere is much simpler idiom for exampleto unimplement ==we would writedef __eq__(selfother)return notimplemented if method implementing comparison operator (=>)returns the built-in notimplemented object and an attempt is made to use the methodpython will first try the reverse comparison by swapping the operands (in case the other object has suitable comparison method since the self object does not)and if that doesn' work python raises typeerror exception with message that explains that the operation is not supported for operands of the types used but for all noncomparison methods that we don' wantwe must raise either notimplementederror or typeerror exception as we did for the __add__(and __neg__(methods shown earlier it would be tedious to unimplement every method we don' want as we have done herealthough it does work and has the virtue of being easy to understand here we will look at more advanced technique for unimplementing methods--it is used in the fuzzyboolalt module--but it is probably best to skip to the next section and return here only if the need arises in practice here is the code for unimplementing the two unary operations we don' wantfor nameoperator in (("__neg__""-")("__index__""index()"))message ("bad operand type for unary { }'{{self}}'format(operator)exec("def { }(self)raise typeerror(\"{ }\format("self=self __class__ __name__))format(namemessage) |
8,797 | object-oriented programming the built-in exec(function dynamically executes the code passed to it from the object it is given in this case we have given it stringbut it is also possible to pass some other kinds of objects by defaultthe code is executed in the context of the enclosing scopein this case within the definition of the fuzzybool classso the def statements that are executed create fuzzybool methods which is what we want the code is executed just oncewhen the fuzzyboolalt module is imported here is the code that is generated for the first tuple ("__neg__""-")def __neg__(self)raise typeerror("bad operand type for unary -'{self}'format(self=self __class__ __name__)we have made the exception and error message match those that python uses for its own types the code for handling binary methods and -ary functions (such as pow()follows similar pattern but with different error message for completenesshere is the code we have usedfor nameoperator in (("__xor__""^")("__ixor__""^=")("__add__""+")("__iadd__""+=")("__radd__""+")("__sub__""-")("__isub__""-=")("__rsub__""-")("__mul__""*")("__imul__""*=")("__rmul__""*")("__pow__""**")("__ipow__""**=")("__rpow__""**")("__floordiv__""//")("__ifloordiv__""//=")("__rfloordiv__""//")("__truediv__""/")("__itruediv__""/=")("__rtruediv__""/")("__divmod__""divmod()")("__rdivmod__""divmod()")("__mod__""%")("__imod__""%=")("__rmod__""%")("__lshift__""<<")("__ilshift__""<<=")("__rlshift__"">")("__irshift__"">>=")("__rrshift__"">>"))message ("unsupported operand type(sfor { }"'{{self}}'{{join}{{args}}format(operator)exec("def { }(self*args):\ntypes [\"'\arg __class__ __name__ \"'\"for arg in args]\nraise typeerror(\"{ }\format("self=self __class__ __name__"join=(\and\if len(args= else \",\"),"args=\"\join(types)))format(namemessage)this code is slightly more complicated than before because for binary operators we must output messages where the two types are listed as type and type but for three or more types we must list them as type type type to mimic dynamic programming |
8,798 | the built-in behavior here is the code that is generated for the first tuple ("__xor__""^")def __xor__(self*args)types ["'arg __class__ __name__ "'for arg in argsraise typeerror("unsupported operand type(sfor ^"'{self}'{join{args}formatself=self __class__ __name__join=(andif len(args= else ",")args="join(types))the two for in loop blocks we have used here can be simply cut and pastedand then we can add or remove unary operators and methods from the first one and binary or -ary operators and methods from the second one to unimplement whatever methods are not required with this last piece of code in placeif we had two fuzzyboolsf and gand tried to add them using gwe would get typeerror exception with the message "unsupported operand type(sfor +'fuzzybooland 'fuzzybool'"which is exactly the behavior we want creating classes the way we did for the first fuzzybool implementation is much more common and is sufficient for almost every purpose howeverif we need to create an immutable classthe way to do it is to reimplement object __new__(having inherited one of python' immutable types such as floatintstror tupleand then implement all the other methods we need the disadvantage of doing this is that we may need to unimplement some methods--this breaks polymorphismso in most cases using aggregation as we did in the first fuzzybool implementation is much better approach custom collection classes ||in this section' subsections we will look at custom classes that are responsible for large amounts of data the first class we will reviewimageis one that holds image data this class is typical of many data-holding custom classes in that it not only provides in-memory access to its databut also has methods for saving and loading the data to and from disk the second and third classes we will studysortedlist and sorteddictare designed to fill rare and surprising gap in python' standard library for intrinsically sorted collection data types creating classes that aggregate collections | simple way of representing color image is as two-dimensional array with each array element being color so to represent image we must store colors for the image class (in file image py)we will take |
8,799 | object-oriented programming potentially more efficient approach an image stores single background colorplus the colors of those points in the image that differ from the background color this is done by using dictionary as kind of sparse arraywith each key being an (xycoordinate and the corresponding value being the color of that point if we had image and half its points are the background colorwe would need to store only colorsa considerable saving in memory the image py module follows what should now be familiar patternit starts with shebang linethen copyright information in commentsthen module docstring with some doctestsand then the importsin this case of the os and pickle modules we will briefly cover the use of the pickle module when we cover saving and loading images after the imports we create some custom exception classesclass imageerror(exception)pass class coordinateerror(imageerror)pass we have shown only the first two exception classesthe others (loaderrorsaveerrorexporterrorand nofilenameerrorare all created the same way and all inherit from imageerror users of the image class can choose to test for any of the specific exceptionsor just for the base class imageerror exception the rest of the module consists of the image class and at the end the standard three lines for running the module' doctests before looking at the class and its methodslet' look at how it can be usedborder_color "#ff red square_color "# ffblue widthheight midxmidy width / height / image image image(widthheight"square_eye img"for in range(width)for in range(height)if width or height image[xyborder_color elif midx midx and midy midy image[xysquare_color image save(image export("square_eye xpm"notice that we can use the item access operator ([]for setting colors in the image brackets can also be used for getting or deleting (effectively setting to the background colorthe color at particular (xycoordinate the coordinates are passed as single tuple object (thanks to the comma operator)the same as if we wrote image[(xy)achieving this kind of seamless syntax integration is easy in python--we just have to implement the appropriate special methodspickles |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.