id
int64
0
25.6k
text
stringlengths
0
4.59k
1,200
may differ in resolutiontrytimer time perf_counter or process_time except attributeerrortimer time clock if sys platform[: ='winelse time time if were writing this book for python readers onlyi' use the new and apparently improved calls hereand you should in your work too if they apply to you the newer calls won' work ...
1,201
(test __name__bestofresult[ ]result[- ])this script tests five alternative ways to build lists of results as shownits reported times reflect on the order of million steps for each of the five test functions--each builds list of , items , times this process is repeated times to get the best-of time for each of the test ...
1,202
(though we're also effectively timing the list call for the generator test)return [abs(xfor in repslistreturn list(abs(xfor in repslist seconds secondsdiffers internally though the exact cause would require deeper analysis (and possibly source code study)this seems to make sense given that the generator expression must...
1,203
results are so much quicker today seems the larger point here on cpythonmap is still quickest so far the impact of function callsmap watch what happensthoughif we change this script to perform an inline operation on each iterationsuch as additioninstead of calling built-in function like abs (the omitted parts of the fo...
1,204
code like this is very tricky affair without numbersthoughit' virtually impossible to guess which method will perform the best--the best you can do is time your own codeon your computerwith your version of python in this casewhat we can say for certain is that on this pythonusing user-defined function in map calls seem...
1,205
allowing the repeat count to be passed in as keyword argument named _repsfile timer py ( and ""total(spam = = _reps= calls and times spam( = = _reps timesand returns total time for all runswith final result bestof(spam = = _reps= runs best-of- timer to attempt to filter out system load variationand returns best time am...
1,206
to test with this new timer moduleyou can change the timing scripts as followsor use the precoded version in the book' examples file timeseqs_timer pythe results are essentially the same as before (this is primarily just an api change)so won' list them again hereimport systimer for test in (forlooplistcompmapcallgenexp...
1,207
one last point on this threadwe can also make use of python keyword-only arguments here to simplify the timer module' code as we learned in keywordonly arguments are ideal for configuration options such as our functions_reps argument they must be coded after and before *in the function headerand in function call they m...
1,208
other suggestions for more insighttry modifying the repetition counts used by these modulesor explore the alternative timeit module in python' standard librarywhich automates timing of codesupports command-line usage modesand finesses some platform-specific issues --in factwe'll put it to work in the next section you m...
1,209
let' start with this module' fundamentals before leveraging them in larger scripts with timeittests are specified by either callable objects or statement stringsthe latter can hold multiple statements if they use separators or \ characters for line breaksand spaces or tabs to indent statements in nested blocks ( \ \tte...
1,210
the latter varies between linescpython has single integer typeand cpython has both short and long integers this may explain part of the size of the differencebut the results are valid nonetheless noninteger tests yield similar rankings ( floating-point test in the solutions to this part' exercises)and integer math matt...
1,211
:\codepypy - timeit - - - "[ * for in range( )] loopsbest of usec per loop :\codepy - - timeit - - - "[abs(xfor in range( )] loopsbest of usec per loop :\codepy - - timeit - - - "[abs(xfor in range( )] loopsbest of usec per loop :\codepypy - timeit - - - "[abs(xfor in range( )] loopsbest of usec per loop these results ...
1,212
later reindents for its own statement nesting purposes leading spaces may work better for indentation than tabs in this modeand be sure to quote the code arguments if required by your shellc:\codepy - - timeit - - " [ , , , , ]" = "while len( ): [ + + loopsbest of usec per loop :\codepy - - timeit - - " [ , , , , ]" [ ...
1,213
callable objects instead of stringsaccept automatic loop countsand use class-based techniques and additional command-line switches and api argument options we don' have space to show here--consult python' library manual for more detailsc:\codepy - import timeit timeit timeit(stmt='[ * for in range( )]'number= total tim...
1,214
defnumdefrep may vary per stmt def runner(stmtspythons=nonetracecmd=false)""main logicrun tests per input listscaller handles usage modes stmts[(number?repeat?stmt-string)]replaces $listif in stmt pythonsnone=this python onlyor [(ispy ?python-executable-path)""print(sys versionfor (numberrepeatstmtin stmtsnumber number...
1,215
import pybenchsys pythons ( ' :\python \python')( ' :\python \python')( ' :\pypy\pypy- \pypy'(ispy ?pathstmts ( "[ * for in range( )]")( "res=[]\nfor in range( )res append( * )")( "$listif (map(lambda xx * range( )))")( "list( * for in range( ))")( " 'spam \nx [ [ifor in range( )]")( " '?'\nfor in range( ) +'?'")(num,r...
1,216
['(map(lambda xx * range( )))'['list( * for in range( ))'[" 'spam \nx [ [ifor in range( )]"[" '?'\nfor in range( ) +'?'"the following shows this script' output when run to test multiple python versions for each statement string in this mode the script itself is run by python but it launches shell command lines that sta...
1,217
loopsbest of usec per loop :\python \python loopsbest of usec per loop :\pypy\pypy- \pypy loopsbest of usec per loop [" '?'\nfor in range( ) +'?'" :\python \python loopsbest of msec per loop :\python \python loopsbest of msec per loop :\pypy\pypy- \pypy loopsbest of msec per loop as you can seein most of these testscpy...
1,218
for examplethe following tests in pybench_cases py measure the impact of charging other iteration operations with function callwhich improves map' chances of winning the day per this earlier note--map usually loses by its association with function calls in generalpybench_cases py pythons +( ' :\python \python')( ' :\py...
1,219
command line (this is just what pybench does internally) :\codepy - - timeit - - " =open(' :/python /lib/pdb py')"for line in fx=line" close()import timeit min(timeit repeat(number= repeat= stmt=" =open(' :/python /lib/pdb py')\nfor line in fx=line\nf close()")for another example that measures both list comprehensions ...
1,220
operation and uses the same repetition counts as pybench_cases pyc:\codepy - timeseqs py ( :bd afb ebf sep : : [msc bit (amd )forloop =[ listcomp =[ mapcall =[ genexpr =[ genfunc =[ :\codepy - pybench_cases py ( :bd afb ebf sep : : [msc bit (amd ) ['[ * for in range( )]' ['res=[]\nfor in range( )res append( * )' ['list...
1,221
if not pythonsbest min(timeit repeatsetup=setupstmt=stmtnumber=numberrepeat=repeat)elsesetup setup replace('\ ' setup join('- "% "line for line in setup split('\ ')for (ispy pythonin pythonscmd '% - timeit - % - % % % (pythonnumberrepeatsetupargspybench _cases py import pybench sys stmts (num,rpt,setup,stmt( """[ * for...
1,222
this has focused on code timing fundamentals that you can use on your own codethat apply to python benchmarking in generaland that served as common use case for developing larger examples for this book benchmarking python is broader and richer domain than so far impliedthough if you're interested in pursuing this topic...
1,223
releasesbut most have been known to trip up new users local names are detected statically as you knowpython classifies names assigned in function as locals by defaultthey live in the function' scope and exist only while the function is running what you may not realize is that python detects locals staticallywhen it com...
1,224
rememberthoughthat this means the assignment also changes the global xnot local within functionyou can' use both local and global versions of the same simple name if you really meant to print the global and then set local of the same nameyou' need to import the enclosing module and use module attribute notation to get ...
1,225
[ saver([ grows on each callsome see this behavior as feature--because mutable default arguments retain their state between function callsthey can serve some of the same roles as static local function variables in the language in sensethey work much like global variablesbut their names are local to the functions and so...
1,226
def saver()saver append( print(saver xsaver [saver([ saver([ saver([ the function name is global to the function itselfbut it need not be declared because it isn' changed directly within the function this isn' used in exactly the same waybut when coded like thisthe attachment of an object to the function is much more e...
1,227
here are two additional function-related gotchas--mostly reviewsbut common enough to reiterate enclosing scopes and loop variablesfactory functions we described this gotcha in ' discussion of enclosing function scopesbut as reminderwhen coding factory functions ( closures)be careful about relying on enclosing function ...
1,228
of class methods before moving on to modulesthoughbe sure to work through this quiz and the exercises for this part of the bookto practice what we've learned about functions here test your knowledgequiz what conclusions can you draw from this about the relative speed of python iteration tools what conclusions can you d...
1,229
in these exercisesyou're going to start coding more sophisticated programs be sure to check the solutions in part iv in appendix dand be sure to start writing your code in module files you won' want to retype these exercises if you make mistake the basics at the python interactive promptwrite function that prints its s...
1,230
in both its arguments (which are assumed to be dictionariesif the same key appears in both argumentsfeel free to pick value from either test your function by writing it in file and running the file as script what happens if you pass lists instead of dictionarieshow could you generalize your function to handle this case...
1,231
to if you need reminderwhat can you do about negativesand the values and how about speeding this upyour outputs should look something like this is prime is prime has factor has factor iterations and comprehensions write code to build new list containing the square roots of all the numbers in this list[ code this as for...
1,232
modules and packages
1,233
modulesthe big picture this begins our in-depth look at the python module--the highest-level program organization unitwhich packages program code and data for reuseand provides selfcontained namespaces that minimize variable name clashes across your programs in concrete termsmodules typically correspond to python progr...
1,234
saw in the last part of this bookimports give access to names in module' global scope that isthe module file' global scope morphs into the module object' attribute namespace when it is imported ultimatelypython' modules allow us to link individual files into larger program system more specificallymodules have at least ...
1,235
whole as we'll seepython fosters modular program structure that groups functionality into coherent and reusable unitsin ways that are naturaland almost automatic along the waywe'll also explore the central concepts of python modulesimportsand object attributes how to structure program at base levela python program cons...
1,236
script file (launched to run the program)and multiple module files (imported libraries of toolsscripts and modules are both text files containing python statementsthough the statements in modules usually just create objects to be used later python' standard library provides collection of precoded modules the first of t...
1,237
namethe notion of importing is also completely general throughout python any file can import tools from any other file for instancethe file py may import py to call its functionbut py might also import py to leverage different tools defined there import chains can go as deep as you likein this examplethe module can imp...
1,238
the prior section talked about importing modules without really explaining what happens when you do so because imports are at the heart of program structure in pythonthis section goes into more formal detail on the import operation to make this process less abstract some programmers like to compare the python module im...
1,239
after finding source code file that matches an import statement by traversing the module search pathpython next compiles it to byte codeif necessary we discussed byte code briefly in but it' bit richer than explained there during an import operation python checks both file modification times and the byte code' python v...
1,240
file are run at import time to create functions and assign attributes within the module to those functions the functions can then be called later in the program by the file' importers because this last import step actually runs the file' codeif any top-level code in module file does real workyou'll see its results at i...
1,241
that include text identifying the version of python that created them ( module cpython- pycthis avoids contention and recompilesbecause each version of python installed can have its own uniquely named version of byte code files in the __pycache__ subdirectoryrunning under given version doesn' overwrite the byte code of...
1,242
: am : am :\code\py xdir __pycache__ : am script py __pycache__ script cpython- pyc cruciallyunder the model used in and laterimporting the same file with different python creates different byte code fileinstead of overwriting the single file as done by the pre- model--in the newer modeleach python version and implemen...
1,243
pythonpath directories (if set standard library directories the contents of any pth files (if present the site-packages home of third-party extensions ultimatelythe concatenation of these four components becomes sys patha mutable list of directory name strings that 'll expand upon later in this section the first and th...
1,244
nextpython automatically searches the directories where the standard library modules are installed on your machine because these are always searchedthey normally do not need to be added to your pythonpath or included in path files (discussed nextpth path file directories (configurablenexta lesser-used feature of python...
1,245
the net effect of all of this is that both the pythonpath and path file components of the search path allow you to tailor the places where imports look for files the way you set environment variables and where you store path files varies per platform for instanceon windowsyou might use your control panel' system icon t...
1,246
name strings is the actual search path within pythonon importspython searches each directory in this list from left to rightand uses the first file match it finds reallysys path is the module search path python configures it at program startupautomatically merging the home directory of the top-level file (or an empty s...
1,247
for examplean import statement of the form import might today load or resolve toa source code file named py byte code file named pyc an optimized byte code file named pyo ( less common formata directory named bfor package imports (described in compiled extension modulecoded in cc++or another languageand dynamically lin...
1,248
from zip archivesarchived files are automatically extracted at import time when zip file is selected from the module import search path one of the standard library directories in the earlier sys path displayfor exampleis zip file today for more detailssee the python standard library manual' description of the built-in ...
1,249
and replacing it with newer distutils package in the python standard library the status of this is unclear--it was anticipated in but did not appear--so be sure to see python' "what' newdocuments for updates on this front that may emerge after this book is released summary in this we covered the basics of modulesattrib...
1,250
attributes of the module object you only need to set pythonpath to import from directories other than the one in which you are working ( the current directory when working interactivelyor the directory containing your top-level filein practicethis will be common case for nontrivial programs the five major components of...
1,251
module coding basics now that we've looked at the larger ideas behind moduleslet' turn to some examples of modules in action although some of the early topics in this will be review for linear readers who have already applied them in previous exampleswe'll find that they quickly lead us to further details surrounding p...
1,252
and allows you to import any of your files in the future because module names become variable names inside python program (without the py)they should also follow the normal variable name rules outlined in for instanceyou can create module file named if pybut you cannot import it because if is reserved word--when you tr...
1,253
in the first examplethe name module serves two different purposes--it identifies an external file to be loadedand it becomes variable in the scriptwhich references the module object after the file is loadedimport module module printer('hello world!'hello worldget module as whole (one or morequalify to get names the imp...
1,254
pattern matching to select subset of names (though you could with more work and loop through module' __dict__discussed aheadand that' it--modules really are simple to use to give you better understanding of what really happens when you define and use modulesthoughlet' move on to look at some of their properties in more...
1,255
import simple simple spam change attribute in module just fetches already loaded module code wasn' rerunattribute unchanged of coursesometimes you really want module' code to be rerun on subsequent import we'll see how to do this with python' reload function later in this import and from are assignments just like defim...
1,256
from assignments do with referencesflip back to figure - (function argument passing)and mentally replace "callerand "functionwith "importedand "importer the effect is the sameexcept that here we're dealing with names in modulesnot functions assignment works the same everywhere in python cross-file name changes recall f...
1,257
entire module into memory if it has not yet been importedregardless of how many names it copies out of the file there is no way to load just part of module file ( just one function)but because modules are byte code in python instead of machine codethe performance implications are generally negligible potential pitfalls...
1,258
when import is required the only time you really must use import instead of from is when you must use the same name defined in two different modules for exampleif two files define the same name differentlym py def func()do something py def func()do something else and you must use both versions of the name in your progr...
1,259
files generate namespaces 've mentioned that files morph into namespacesbut how does this actually happenthe short answer is that every name that is assigned value at the top level of module file ( not nested in function or class bodybecomes an attribute of that module for instancegiven an assignment statement such as ...
1,260
print('done loading 'the first time this module is imported (or run as program)python executes its statements from top to bottom some statements create names in the module' namespace as side effectbut others do actual work while the import is going on for instancethe two print statements in this file execute at import ...
1,261
assignsfilter out the double-underscore names as we've done beforein ' dir coverage and ' built-in scope coveragelist(name for name in module __dict__ keys(if not name startswith('__')['func''klass''name''sys'list(name for name in module __dict__ if not name startswith('__')['func''sys''name''klass'this time we're filt...
1,262
qualification works on all objects with attributesmodulesclassesc extension typesetc in part viwe'll see that attribute qualification means bit more for classes--it' also the place where something called inheritance happens--but in generalthe rules outlined here apply to all names in python imports versus scopes as we'...
1,263
piece of code are completely determined by the code' physical position in your file scopes are never influenced by function calls or module imports namespace nesting in some sensealthough imports do not nest namespaces upwardthey do nest downward that isalthough an imported module never has direct access to names in fi...
1,264
simply evaluates from left to rightfetching attributes from objects along the way note that mod can say import mod and then mod mod xbut it cannot say import mod mod --this syntax invokes something called package (directoryimportsdescribed in the next package imports also create module namespace nestingbut their import...
1,265
import or from statement is required to load this tool in only readers using can ignore these imports in this book' examplesor use them anyhow-- also has reload in its imp module to ease migration to reloading works the same regardless of its packaging reload basics unlike import and fromreload is function in pythonnot...
1,266
that use import qualify to fetch attributesthey'll find new values in the module object after reload reloads impact future from clients only clients that used from to fetch attributes in the past won' be affected by reloadthey'll still have references to the old objects fetched before the reload reloads apply to single...
1,267
forces new code to load/run changer printer(runs the new version now reloadedafter editing notice that reload actually returns the module object for us--its result is usually ignoredbut because expression results are printed at the interactive promptpython shows default representation two final notes herefirstif you us...
1,268
the from statement although we've already seen enough to handle module files in our programsthe next extends our coverage of the import model by presenting package imports-- way for our import statements to specify part of the directory path leading to the desired module as we'll seepackage imports give us hierarchy th...
1,269
seriously corrupt namespaces and obscure the meaning of variablesso it is probably best used sparingly what do you meanan african or european swallowtest your knowledgeanswers
1,270
module packages so farwhen we've imported moduleswe've been loading files this represents typical module usageand it' probably the technique you'll use for most imports you'll code early on in your python career howeverthe module import story is bit richer than have thus far implied in addition to module namean import ...
1,271
at base levelpackage imports are straightforward--in the place where you have been naming simple file in your import statementsyou can instead list path of names separated by periodsimport dir dir mod the same goes for from statementsfrom dir dir mod import the "dottedpath in these statements is assumed to correspond t...
1,272
prefixeswhich lead to the leftmost names in import and from statements these import statements themselves provide the remainder of the directory path in platform-neutral fashion as for simple file importsyou don' need to add the container directory dir to your module search path if it' already there--per it will be if ...
1,273
dir dir __init__ py dir __init__ py mod py container on module search path the __init__ py files can contain python codejust like normal module files their names are special because their code is run automatically the first time python program imports directoryand thus serves primarily as hook for performing initializa...
1,274
to find later files module namespace initialization in the package import modelthe directory paths in your script become real nested object paths after an import for instancein the preceding exampleafter the import the expression dir dir works and returns module object whose namespace contains all the names assigned by...
1,275
print('in mod py' heredir will be either an immediate subdirectory of the one we're working in ( the home directory)or an immediate subdirectory of directory that is listed on the module search path (technicallyon sys patheither waydir ' container does not need an __init__ py file import statements run each directory' ...
1,276
from versus import with packages import statements can be somewhat inconvenient to use with packagesbecause you may have to retype the paths frequently in your program in the prior section' examplefor instanceyou must retype and rerun the full path from dir each time you want to reach if you try to access dir or mod di...
1,277
imports make it more obvious what role module playsand so make your code more readable for examplea normal import of file in directory somewhere on the module search pathlike thisimport utilities offers much less information than an import that includes the pathimport database client utilities package imports can also ...
1,278
in factyou won' even need to configure the module search path to use these programs on your computer--because python always searches the home directory first (that isthe directory containing the top-level file)imports in either system' files will automatically see all the files in that system' directory for instanceif ...
1,279
nowadd just the common root directory to your search path if your code' imports are all relative to this common rootyou can import either system' utility file with package import--the enclosing directory name makes the path (and hencethe module referenceunique in factyou can import both utility files in the same module...
1,280
this line fetches names from the client module of the win com package--an install subdirectory package imports are also pervasive in code run under the jython java-based implementation of pythonbecause java libraries are organized into hierarchies as well in recent python releasesthe email and xml tools are likewise or...
1,281
the way import operations in packages work has changed slightly in python this change applies only to imports within files when files are used as part of package directoryimports in other usage modes work as before for imports in packagesthoughpython introduces two changesit modifies the module import search path seman...
1,282
imports within package are absolute-only by default--in the absence of any special dot syntaximports skip the containing package itself and look elsewhere on the sys path search path for examplein both python and statement of the formrelative to this package from import spam instructs python to import module named spam...
1,283
the package directory firstother dot-based relative reference patterns are possibletoo within module file located in package directory named mypkgthe following alternative import forms work as describedfrom string import name name from import string from import string imports names from mypkg string imports mypkg strin...
1,284
intended to be used it' better if the resolution can be made explicit in code the relative imports solution in to address this dilemmaimports run within packages have changed in python to be absolute-only (and can be made so as an option in xunder this modelan import statement of the following form in our example file ...
1,285
alternativelya file can sometimes name its own package explicitly in an absolute import statementrelative to directory on sys path for examplein the followingmypkg will be found in an absolute directory on sys pathfrom mypkg import string imports mypkg string (absolutehoweverthis relies on both the configuration and th...
1,286
the new from syntax for local package filesor full absolute paths module lookup rules summary with packages and relative importsthe module search story in python that we have seen so far can be summarized as followsbasic modules with simple names ( aare located by searching each directory on the sys path listfrom left ...
1,287
first of allas mentioned previouslythis feature does not impact imports outside package thusthe following finds the standard library string module as expectedc:\codec:\python \python import string string but if we add module of the same name in the directory we're working init is selected insteadbecause the first entry...
1,288
have to pardon the shell commands hereand translate for your platform) :\codedel stringdel __pycache__\stringfor bytecode in :\codemkdir pkg :\codenotepad pkg\__init__ py code\pkg\spam py import eggs print(eggs <=works in but not xcode\pkg\eggs py import string print(stringthe first file in this package tries to import...
1,289
notice in the preceding example that the package modules still have access to standard library modules like string--their normal imports are still relative to the entries on the module search path in factif you add string module to the cwd againimports in package will find it there instead of in the standard library al...
1,290
--by using absolute or relative import syntax in xyou can either skip or select the package directory explicitly in factthis is the use case that the model addressescode\pkg\spam py from import string print(string<=relative in both and code\pkg\string py print('ni :\codec:\python \python import pkg spam nininininininin...
1,291
print(string<=relative in both and code\pkg\string py print('ni when we import the string module with relative import syntax like thiswe get the version in the package in both and xas desiredc:\codec:\python \python same result in import pkg spam nininininininini when absolute syntax is usedthoughthe module we get vari...
1,292
now that you've learned about package-relative importsyou should also keep in mind that they may not always be your best option absolute package importswith complete directory path relative to directory on sys pathare still sometimes preferred over both implicit package-relative imports in python xand explicit package-...
1,293
and functionalbut we need to turn to more concrete code to see why the issue for examplein python it' common to use the same single directory as both program and packageusing normal undotted imports this relies on the script' home directory to resolve imports when used as programand the relative-then-absolute rule to r...
1,294
:\codepython import pkg spam eggseggseggseggs ok as package but not program in both and :\codepython pkg\main py systemerrorcannot perform relative import :\codepython pkg\spam py systemerrorcannot perform relative import fix package subdirectories in mixed-use case like thisone solution is to isolate all but the main ...
1,295
import pkg eggs <=full package paths work in all cases + code\pkg\eggs py print('eggs :\codeset pythonpath= :\code :\codepython pkg\main py from main scriptsame result in and eggseggseggseggs :\codepython import pkg spam eggseggseggseggs from elsewheresame result in and unlike the subdirectory fixfull path absolute imp...
1,296
import dualpkg :\codepy - import dualpkg :\codepy - dualpkg\ py :\codepy - dualpkg\ py ok ok failsfailsconverselya simple import statement works in nonpackage mode in both and xbut fails in package mode in onlybecause such statements do not search the package directory in xcode\dualpkg\ py import :\codepy - import dual...
1,297
this book covers python up to onlyat this writingthere is talk in pep of possibly addressing some package issues in python perhaps even allowing relative imports to be used in program mode on the other handthis initiative' scope and outcome is uncertain and would work only on and laterthe full path solution given here ...
1,298
as something of fallback optionrecognized only if normal modules and regular packages of the same name are not present on the module search path the rationale for namespace packages is rooted in package installation goals that may seem obscure unless you are responsible for such tasksand is better addressed by this fea...
1,299
with the next directory in the search path if none of the above was foundthe scan continues with the next directory in the search path if the search path scan completes without returning module or package by steps or and at least one directory was recorded by step then namespace package is created the creation of the n...