id
int64
0
25.6k
text
stringlengths
0
4.59k
1,100
annotation valuesspecified as name:value (or name:value=default when defaults are presentthis is simply additional syntax for arguments and does not augment or change the argument-ordering rules described here the function itself can also have an annotation valuegiven as def ()->value python attaches annotation values ...
1,101
is much more meaningful than call with three naked values separated by commasespecially in larger programs--the keywords serve as labels for the data in the call the second major use of keywords occurs in conjunction with defaultswhich we turn to next defaults we talked about defaults in brief earlierwhen discussing ne...
1,102
ham to the defaults specified in the headerdef func(spameggstoast= ham= )print((spameggstoastham)first required func( func( ham= eggs= func(spam= eggs= func(toast= eggs= spam= func( output( output( output( output( output( notice again that when keyword arguments are used in the callthe order in which the arguments are ...
1,103
( the *feature is similarbut it only works for keyword arguments--it collects them into new dictionarywhich can then be processed with normal dictionary tools in sensethe *form allows you to convert from keywords to dictionarieswhich you can then step through with keys callsdictionary iteratorsand the like (this is rou...
1,104
same as func( = = = = againwe can combine normalpositionaland keyword arguments in the call in very flexible waysfunc(*( )**{' ' ' ' } func( *( )**{' ' } func( = *( ,)**{' ' } func( *( ) = func( *( ,) = **{' ': } same as func( = = same as func( = same as func( = = same as func( = same as func( = = this sort of code is ...
1,105
actionargs func ( ,elseactionargs func ( etc action(*argscall func with one arg in this case call func with three args here dispatch generically this leverages both the formand the fact that functions are objects that may be both referenced byand called throughany variable more generallythis varargs call syntax is usef...
1,106
prior to python xthe effect of the *args and **args varargs call syntax could be achieved with built-in function named apply this original technique has been removed in because it is now redundant ( cleans up many such dusty tools that have been subsumed over the yearsit' still available in all python releasesthoughand...
1,107
python generalizes the ordering rules in function headers to allow us to specify keyword-only arguments--arguments that must be passed by keyword only and will never be filled in by positional argument this is useful if we want function to both process any number of arguments and accept possibly optional configuration ...
1,108
typeerrorkwonly(takes positional argument but were given in factkeyword-only arguments with defaults are optionalbut those without defaults effectively become required keywords for the functiondef kwonly( *bc='spam')print(abckwonly( ='eggs' eggs spam kwonly( ='eggs'typeerrorkwonly(missing required keyword-only argument...
1,109
( {' ' ' ' anywhere in keywords def (ac= * ** )print(abcdc is not keyword-only heref( = ( , {' ' in factsimilar ordering rules hold true in function callswhen keyword-only arguments are passedthey must appear before **args form the keyword-only argument can be coded either before or after the *argsthoughand may be incl...
1,110
since we're going to see more realistic example of this later in this in "emulating the python print function, 'll postpone the rest of this story until then for an additional example of keyword-only arguments in actionsee the iteration options timing case study in and for additional function definition enhancements in...
1,111
but the linear scans of the first two techniques may make them faster much of the time the file mins py contains the code for all three solutionsdef min (*args)res args[ for arg in args[ :]if arg resres arg return res def min (first*rest)for arg in restif arg firstfirst arg return first def min (*args)tmp list(argstmp ...
1,112
that triggers an error automatically)but in general it' better to assume that arguments will work in your functionscode and let python raise errors for you when they do not bonus points you can get bonus points here for changing these functions to compute the maximumrather than minimumvalues this one' easythe first two...
1,113
be useful in other scenarios generalized set functions let' look at more useful example of special argument-matching modes at work at the end of we wrote function that returned the intersection of two sequences (it picked out items that appeared in bothhere is version that intersects an arbitrary number of sequences (o...
1,114
[' '' '' '' '' '' 'to test more thoroughlythe following codes function to apply the two tools to arguments in different orders using simple shuffling technique that we saw in --it slices to move the first to the end on each loopuses to unpack argumentsand sorts so results are comparabledef tester(funcitemstrace=true)fo...
1,115
tooland the tester would be simpler if we delegated this to another functionone that would be free to create or generate argument combinations as it saw fitdef tester(funcitemstrace=true)for args in scramble(items)use args in fact we will--watch for this example to be revised in to address this last pointafter we've le...
1,116
file kargs get('file'sys stdoutoutput 'first true for arg in argsoutput +('if first else sepstr(argfirst false file write(output endto test itimport this into another file or the interactive promptand use it like the print function here is test scripttestprint py (notice that the function must be called "print "because...
1,117
for arg in argsoutput +('if first else sepstr(argfirst false file write(output endthis version works the same as the originaland it' prime example of how keywordonly arguments come in handy the original version assumes that all positional arguments are to be printedand all keywords are for options only that' almost suf...
1,118
as you can probably telladvanced argument-matching modes can be complex they are also largely optional in your codeyou can get by with just simple positional matchingand it' probably good idea to do so when you're starting out howeverbecause some python tools make use of themsome general knowledge of these modes is imp...
1,119
it' sent inchanging passed-in mutable in function can impact the caller the next continues our look at functions by exploring some more advanced function-related ideasfunction annotationsrecursionlambdasand functional tools such as map and filter many of these concepts stem from the fact that functions are normal objec...
1,120
lmn ntest your knowledgeanswers the output here is because and are passed to and by positionand is omitted in the call and defaults to the output this time is is passed to by positionand and are passed and by name (the left-to-right order doesn' matter when keyword arguments are used like this this code prints ( )becau...
1,121
advanced function topics this introduces collection of more advanced function-related topicsrecursive functionsfunction attributes and annotationsthe lambda expressionand functional programming tools such as map and filter these are all somewhat advanced tools thatdepending on your job descriptionyou may not encounter ...
1,122
( names in the enclosing moduleare usually poor way for functions to communicate they can create dependencies and timing issues that make programs difficult to debugchangeand reuse couplingdon' change mutable arguments unless the caller expects it functions can change parts of passed-in mutable objectsbut (as with glob...
1,123
figure - function execution environment functions may obtain input and produce output in variety of waysthough functions are usually easier to understand and maintain if you use arguments for input and return statements and anticipated mutable argument changes for output in python onlyoutputs may also take the form of ...
1,124
at each levelthis function calls itself recursively to compute the sum of the rest of the listwhich is later added to the item at the front the recursive loop ends and zero is returned when the list becomes empty when using recursion like thiseach open level of call to the function has its own copy of the function' loc...
1,125
mysum([ ] mysum((' '' '' '' ')'spammysum(['spam''ham''eggs']'spamhameggsmysum([]fails in last but various types now work run these on your own for more insight if you study these three variantsyou'll find thatthe latter two also work on single string argument ( mysum('spam'))because strings are sequences of one-charact...
1,126
better yetfor loops iterate for us automaticallymaking recursion largely extraneous in many cases (andin all likelihoodless efficient in terms of memory space and execution time) [ sum for in lsum + sum with looping statementswe don' require fresh copy of local scope on the call stack for each iterationand we avoid the...
1,127
their nested lists recursion versus queues and stacks it sometimes helps to understand that internallypython implements recursion by pushing information on call stack at each recursive callso it remembers where it must return and continue later in factit' generally possible to implement recursive-style procedures witho...
1,128
in generalthoughonce you get the hang of recursive callsthey are more natural than the explicit scheduling lists they automateand are generally preferred unless you need to traverse structure in specialized ways some programsfor exampleperform bestfirst search that requires an explicit search queue ordered by relevance...
1,129
and repeats in later examples listed in the next section some programs may also need to record complete paths for each state followed so they can report solutions when finished in such caseseach item in the nonrecursive scheme' stack or queue may be full path list that suffices for record of states visitedand contains ...
1,130
python functions are more flexible than you might think as we've seen in this part of the bookfunctions in python are much more than code-generation specifications for compiler--python functions are full-blown objectsstored in pieces of memory all their own as suchthey can be freely passed around program and called ind...
1,131
or strings the followingfor exampleembeds the function twice in list of tuplesas sort of actions table because python compound types like these can contain any sort of objectthere' no special case hereeitherschedule (echo'spam!')(echo'ham!'for (funcargin schedulefunc(argcall functions embedded in containers spamhamthis...
1,132
'__repr__''__setattr__''__sizeof__''__str__''__subclasshook__'introspection tools allow us to explore implementation details too--functions have attached code objectsfor examplewhich provide details on aspects such as the functionslocal variables and argumentsfunc __code__ "line dir(func __code__['__class__''__delattr_...
1,133
run on your own to see len(dir( ) [ for in dir(fif not startswith('__')[ :\codepy - def ()pass dir(frun on your own to see len(dir( ) [ for in dir(fif not startswith('__')['func_closure''func_code''func_defaults''func_dict''func_doc''func_globals''func_name'if you're careful not to name attributes the same wayyou can s...
1,134
syntacticallyfunction annotations are coded in def header linesas arbitrary expressions associated with arguments and return values for argumentsthey appear after colon immediately following the argument' namefor return valuesthey are written after -following the arguments list this codefor exampleannotates all three o...
1,135
(keywords work normally func __annotations__ {' '' '( )' ''spam''return'secondnote that the blank spaces in the prior example are all optional--you can use spaces between components in function headers or notbut omitting them might degrade your code' readability to some observers (and probably improve it to others!)def...
1,136
the lambda' general form is the keyword lambdafollowed by one or more arguments (exactly like the arguments list you enclose in parentheses in def header)followed by an expression after colonlambda argument argument argumentn expression using arguments function objects returned by running lambda expressions work exactl...
1,137
def lambda expressions introduce local scope much like nested defwhich automatically sees names in enclosing functionsthe moduleand the built-in scope (via the legb ruleand per )def knights()title 'siraction (lambda xtitle xreturn action act knights(msg act('robin'msg 'sir robintitle in enclosing def scope return funct...
1,138
because it is statementnot an expression the equivalent def coding would require temporary function names (which might clash with othersand function definitions outside the context of intended use (which might be hundreds of lines away)def ( )return * def ( )return * def ( )return * define named functions [ reference b...
1,139
functions that may clash with other names in this file (perhaps unlikelybut always possible lambdas also come in handy in function-call argument lists as way to inline temporary function definitions not used anywhere else in your programwe'll see some examples of such other uses later in this when we study map how (not...
1,140
like map calls and list comprehension expressions--tools we met in earlier and will revisit in this and the next import sys showall lambda xlist(map(sys stdout writex) xmust use list showall(['spam\ ''toast\ ''eggs\ '] xcan use print spam toast eggs showall lambda [sys stdout write(linefor line in xt showall(('bright\ ...
1,141
act action( act( ((lambda (lambda yx ))( ))( herethe nested lambda structure makes function that makes function when called in both casesthe nested lambda' code has access to the variable in the enclosing lambda this worksbut it seems fairly convoluted codein the interest of readabilitynested lambdas are generally best...
1,142
by most definitionstoday' python blends support for multiple programming paradigmsprocedural (with its basic statements)object-oriented (with its classes)and functional for the latter of thesepython includes set of built-ins used for functional programming--tools that apply functions to sequences and other iterables th...
1,143
this isn' necessary in (see if you've forgotten this requirementbecause map expects function to be passed in and appliedit also happens to be one of the places where lambda commonly appearslist(map((lambda xx )counters)[ function expression herethe function adds to each item in the counters listas this little function ...
1,144
less general tooland often requires extra helper functions or lambdas moreoverwrapping comprehension in parentheses instead of square brackets creates an object that generates values on request to save memory and increase responsivenessmuch like map in -- topic we'll take up in the next selecting items in iterablesfilt...
1,145
reduce((lambda xyx )[ ] reduce((lambda xyx )[ ] import in xnot in at each stepreduce passes the current sum or productalong with the next item from the listto the passed-in lambda function by defaultthe first item in the sequence initializes the starting value to illustratehere' the for loop equivalent to the first of ...
1,146
this took us on tour of advanced function-related conceptsrecursive functionsfunction annotationslambda expression functionsfunctional tools such as mapfilterand reduceand general function design ideas the next continues the advanced topics motif with look at generators and reprisal of iterables and list comprehensions...
1,147
module in xnot the built-in scopereduce is built-in in function annotationsavailable in ( and later)are syntactic embellishments of function' arguments and resultwhich are collected into dictionary assigned to the function' __annotations__ attribute python places no semantic meaning on these annotationsbut simply packa...
1,148
comprehensions and generations this continues the advanced function topics themewith reprisal of the comprehension and iteration concepts previewed in and introduced in because comprehensions are as much related to the prior functional tools ( map and filteras they are to for loopswe'll revisit them in this context her...
1,149
comprehension was extended to other roles--setsdictionariesand even the value generator expressions we'll explore in this it' not just for lists anymore we first met list comprehensions in ' previewand studied them further in in conjunction with looping statements because they're also related to functional programming ...
1,150
the brackets you code an expression that names variable followed by what looks like for loop header that names the same variable python then collects the expression' results for each iteration of the implied loop the effect of the preceding example is similar to that of the manual for loop and the map call list compreh...
1,151
[ all of these use the modulus (remainder of divisionoperator%to detect even numbersif there is no remainder after dividing number by it must be even the filter call here is not much longer than the list comprehension either howeverwe can combine an if clause and an arbitrary expression in our list comprehensionto give...
1,152
res append( yres [ although list comprehensions construct list resultsremember that they can iterate over any sequence or other iterable type here' similar bit of code that traverses strings instead of lists of numbersand so collects concatenation results[ for in 'spamfor in 'spam'['ss''sp''sa''sm''ps''pp''pa''pm''as''...
1,153
nestedso won' even try showing it here 'll leave its coding as an exercise for zen mastersex-lisp programmersand the criminally insaneexamplelist comprehensions and matrixes not all list comprehensions are so artificialof course let' look at one more application to stretch few synapses as we saw in and one basic way to...
1,154
differ) [[ ][ ]for in range(len( ))for in range(len( [ ])) [ ][ + update in place [[ ][ ]we can' really do the same with list comprehensionsas they make new listsbut we could always assign their results to the original name for similar effect for examplewe can apply an operation to every item in matrixproducing results...
1,155
[[ ][ ][ ][ [row][coln[row][colfor row in range( for col in range( )[ [[ [row][coln[row][colfor col in range( )for row in range( )[[ ][ ][ ]this last expression works because the row iteration is an outer loop againit' equivalent to this statement-based coderes [for row in range( )tmp [for col in range( )tmp append( [r...
1,156
using complicated and tricky code where not warranted is both bad engineering and bad software citizenship to repurpose line from the first programming is not about being clever and obscure--it' about how clearly your program communicates its purpose orto quote from python' import this mottosimple is better than comple...
1,157
here can depend on call patternsas well as changes and optimizations in python itself recent python releases have sped up the simple for loop statementfor example on some codethoughlist comprehensions are still substantially faster than for loops and even faster than mapthough map can still win when the alternatives mu...
1,158
[ the first of these makes use of tuple assignment to unpack row tuples in the listand the second uses indexing in python (but not in --see the note on argument unpacking in )map can use tuple unpacking on its argumenttoo only list(map((lambda (nameagejob)age)listoftuple)[ see other books and resources for more on pyth...
1,159
expect generator functionsyield versus return in this part of the bookwe've learned about coding normal functions that receive input parameters and send back single result immediately it is also possiblehoweverto write functions that may send back value and later be resumedpicking up where they left off such functionsa...
1,160
through sequence or value generatorif the protocol is supported (if notiteration falls back on repeatedly indexing sequences insteadany object that supports this interface works in all iteration tools to support this protocolfunctions containing yield statement are compiled specially as generators--they are not normal ...
1,161
to end the generation of valuesfunctions either use return statement with no value or simply allow control to fall off the end of the function body to most peoplethis process seems bit implicit (if not magicalon first encounter it' actually quite tangiblethough if you really want to see what is going on inside the forc...
1,162
given the simple examples we're using to illustrate fundamentalsyou might be wondering just why you' ever care to code generator at all in this section' examplefor instancewe could also simply build the list of yielded values all at oncedef buildsquares( )res [for in range( )res append( * return res for in buildsquares...
1,163
for sub in line split(',')yield sub upper(tuple(ups('aaa,bbb,ccc')('aaa''bbb''ccc'substring generator all iteration contexts {is for (isin enumerate(ups('aaa,bbb,ccc')){ 'aaa' 'bbb' 'ccc'in moment we'll see the same assets for generator expressions-- tool that trades function flexibility for comprehension conciseness l...
1,164
being processed inside the generator in additiongenerators in and later also support throw(typemethod to raise an exception inside the generator at the latest yieldand close method that raises special generatorexit exception inside the generator to terminate the iteration entirely these are advanced features that we wo...
1,165
generator' code location the net effect is much like that of generator functionsbut in the context of comprehension expressionwe get back an object that remembers where it left off after each part of its result is returned also like generator functionslooking under the hood at the protocol that these objects automatica...
1,166
('aaa\ ''ccc\ 'notice how the join call in the preceding doesn' require extra parentheses around the generator syntacticallyparentheses are not required around generator expression that is the sole item already enclosed in parentheses used for other purposes--like those of function call parentheses are required in all ...
1,167
[ list( for in ( )[ nonfunction case simpler as generatorthe same holds true for text-processing use cases like the join call we saw earlier-- list comprehension makes an extra temporary list of resultswhich is completely pointless in this context because the list is not retainedand map loses simplicity points compared...
1,168
arbitrarily mixed and deepthough some may be more valid than otherslist(map(absmap(absmap(abs(- ))))nesting gone bad[ list(abs(xfor in (abs(xfor in (abs(xfor in (- )))[ these last examples illustrate how general generators can bebut are also coded in an intentionally complex form to underscore that generator expression...
1,169
like list comprehensionsthere is always statement-based equivalent to generator expressionthough it sometimes renders substantially more code'join( upper(for in line split(if len( 'aabbbres 'for in line split()if len( res + upper(statement equivalentthis is also join res 'aabbbin this casethoughthe statement form isn' ...
1,170
needed in factthis is essentially the same as the prior tradeoff between lambda and def--expression conciseness versus statement powerdef timesfour( )for in syield timesfour('spam'list( ['ssss''pppp''aaaa''mmmm'generator function iterate automatically to clientsthe two are more similar than different both expressions a...
1,171
simple statement equivalent shown earlier may be difficult to justifyexcept on stylistic grounds on the other handtrading four lines for one may to many seem fairly compelling stylistic groundsgenerators are single-iteration objects subtle but important pointboth generator functions and generator expressions are their ...
1,172
iter(gis true iter( )iter(gnext( 'ssssnext( 'ppppnext( 'aaaagenerator functions work the same way at same position as this is different from the behavior of some built-in typeswhich support multiple iterators and passes and reflect their in-place changes in active iteratorsl [ iter( )iter(lnext( next( next( del [ :next...
1,173
the usual generator usage contextsdef both( )yield from range(nyield from ( * for in range( )list(both( )[ join(str(ifor in both( )' in more advanced roleshoweverthis extension allows subgenerators to receive sent and thrown values directly from the calling scopeand return final value to the outer generator the net eff...
1,174
flesh wound while built-in type iterables are bound to specific type of value generationthe concept is similar to the multipurpose generators we code with expressions and functions iteration contexts like for loops accept any iterable that has the expected methodswhether user-defined or built-in generators and library ...
1,175
(*range( ) and (*( for in range( )) and unpack range valuesiterable in unpack generator expression values this applies to dictionaries and views too (though dict values is also list in xand order is arbitrary when passing values by position) dict( ='bob' ='dev' = ) {' ''dev'' ' ' ''bob' ( ='bob' ='dev' = normal keyword...
1,176
alternativelya user-defined iterable class' method functions can sometimes use yield to transform themselves into generatorswith an automatically created __next__ method-- common application of yield we'll meet in that is both wildly implicit and potentially usefula __getitem__ indexing method is also available as fall...
1,177
[ : [: print(lend='slice so any sequence type works [ [ [ alternativelyas we saw in we get the same results by moving an entire front section to the endthough the order of the results varies slightlyfor in range(len( )) [ : [:iprint(xend='for positions rear part front part (same effectspam pams amsp mspa simple functio...
1,178
yield seq def scramble(seq)for in range(len(seq))yield seq[ :seq[:ilist(scramble('spam')['spam''pams''amsp''mspa'list(scramble(( ))[( )( )( )for in scramble(( ))print(xend='generator function assignments work here generator function yield one item per iteration list()generates all results any sequence type works for lo...
1,179
tester client finallywe can use either the generator function or its expression equivalent in ' tester to produce scrambled arguments--the sequence scrambling function becomes tool we can use in other contextsfile scramble py def scramble(seq)for in range(len(seq))yield seq[ :seq[:igenerator function yield one item per...
1,180
elseres [for in range(len(seq))rest seq[:iseq[ + :for in permute (rest)res append(seq[ : + xreturn res def permute (seq)if not seqyield seq elsefor in range(len(seq))rest seq[:iseq[ + :for in permute (rest)yield seq[ : + empty sequence delete current node permute the others add node at front shuffle any sequencegenerat...
1,181
both space usage and delays for results for larger itemsthe set of all permutations is much larger than the simpler scrambler'spermute ('spam'=list(permute ('spam')true len(list(permute ('spam')))len(list(scramble('spam'))( list(scramble('spam')['spam''pams''amsp''mspa'list(permute ('spam')['spam''spma''sapm''samp''smp...
1,182
alternatives alwayskeep it simple unless it must be complicatedon the other handspace and timeconcisenessexpressiveness that being saidthere are specific use cases that generators can address well they can reduce memory footprint in some programsreduce delays in othersand can occasionally make the impossible possible c...
1,183
for more fun--and to yield results that are more variable and less obviously deterministic--we could also use python' random module of to randomly shuffle the sequence to be permuted before the permuter begins its work (in factwe might be able to use the random shuffler as permutation generator in generalas long as we ...
1,184
to help you evaluate their roles furtherlet' take quick look at one more example of generators in action that illustrates just how expressive they can be once you know about comprehensionsgeneratorsand other iteration toolsit turns out that emulating many of python' functional built-ins is both straightforward and inst...
1,185
print(mymap(abs[- - ])print(mymap(pow[ ][ ])this version relies heavily upon the special *args argument-passing syntax--it collects multiple sequence (reallyiterableargumentsunpacks them as zip arguments to combineand then unpacks the paired zip results as arguments to the passed-in function that iswe're using the fact...
1,186
the iteration protocol the generators returned by these functions themselvesas well as that returned by the python flavor of the zip built-in they useproduce results only on demand coding your own zipand map(noneof coursemuch of the magic in the examples shown so far lies in their use of the zip built-in to pair argume...
1,187
functions are runthe following results are printed-- zipand two padding maps[(' '' ')(' '' ')(' '' ')[(' '' ')(' '' ')(' '' ')(none' ')(none' ')(none' ')[(' '' ')(' '' ')(' '' ')( ' ')( ' ')( ' ')these functions aren' amenable to list comprehension translation because their loops are too specific as beforethoughwhile o...
1,188
comprehensions (passed to tuplestep through the passed-in sequences to pull out arguments in parallel when they're runthe results are as before most strikinglygenerators and iterators seem to run rampant in this example the arguments passed to min and max are generator expressionswhich run to completion before the nest...
1,189
yield tuple(resbecause this code uses iter and nextit works on any type of iterable note that there is no reason to catch the stopiteration raised by the next(itinside the comprehension here when any one of the argumentsiterators is exhausted--allowing it to pass ends this generator function and has the same effect tha...
1,190
generator expressionproduces items parens are often optional { for in range( ){ set comprehension and {xyis set in these versions too {xx for in range( )dictionary comprehension and { scopes and comprehension variables now that we've seen all comprehension formsbe sure to also review ' overview of the localization of l...
1,191
localize names as in xc:\codepy - ( for in range( )at ee nameerrorname 'xis not defined [ for in range( )[ for in range( )pass xlist does not localize its nameslike for for loops do not localize names in or if you care about version portabilityand symmetry with the for loop statementuse unique names for variables in co...
1,192
res { res {for in range( )res[xx dict comprehension equivalent res { localized in comprehension expressionsbut not in loop statements notice that although both set and dictionary comprehensions accept and scan iterablesthey have no notion of generating results on demand--both forms build complete objects all at once if...
1,193
{'ac''bd''bc''ad'{ (ord( )ord( )for in 'abfor in 'cd'{'ac'( )'bd'( )'bc'( )'ad'( ){ for in ['spam''ham''sausage'if [ =' '{'sausagesausage''spamspam'{ upper() for in ['spam''ham''sausage'if [ =' '{'sausage''sausagesausage''spam''spamspam'for more detailsexperiment with these tools on your own they may or may not have pe...
1,194
once insteadgenerator expressions return generator objectwhich yields one item in the result at time when used in an iteration context generators are iterable objects that support the iteration protocol automatically-they have an iterator with __next__ method (next in xthat repeatedly advances to the next item in serie...
1,195
the benchmarking interlude now that we know about coding functions and iteration toolswe're going to take short side trip to put both of them to work this closes out the function part of this book with larger case study that times the relative performance of the iteration tools we've met so far along the waythis case s...
1,196
luckilypython makes it easy to time code for exampleto get the total time taken to run multiple calls to function with arbitrary positional argumentsthe following firstcut function might sufficefile timer py import time def timer(func*args)start time clock(for in range( )func(*argsreturn time clock(start simplistic tim...
1,197
""total time to run func(reps times returns (total timelast result""repslist list(range(reps)start timer(for in repslistret func(*pargs**kargselapsed timer(start return (elapsedretdef bestof(repsfunc*pargs**kargs)""quickest func(among reps runs returns (best timelast result""best * for in range(reps)start timer(ret fun...
1,198
any number of both positional and keyword arguments are collected with starredargument syntaxso they must be sent individuallynot in sequence or dictionary if neededcallers can unpack argument collections into individual arguments with stars in the callas done by the bestoftotal function at the end see for refresher if...
1,199
min(timer total( str upper'spam'for in range( )( 'spam'taking the min of an iteration of total results this way has similar effect because the times in the result tuples dominate comparisons made by min (they are leftmost in the tuplewe could use this in our module too (and will in later variations)it varies slightly b...