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 for users of any other pythonsthoughand that' still the majority of the python world today it would be easier to pretend that the past doesn' matterbut that would not only be evasive of realityit might also be just plain rude timing script nowto time iteration tool speed (our original goal)run the following script--it uses the timer module we wrote to time the relative speeds of the list construction techniques we've studiedfile timeseqs py "test the relative speed of iteration tool alternatives import systimer reps repslist list(range(reps)import timer functions hoist outlist in both / def forloop()res [for in repslistres append(abs( )return res def listcomp()return [abs(xfor in repslistdef mapcall()return list(map(absrepslist)return map(absrepslistuse list(here in onlydef genexpr()return list(abs(xfor in repslistlist(required to force results def genfunc()def gen()for in repslistyield abs(xreturn list(gen()list(required to force results print(sys versionfor test in (forlooplistcompmapcallgenexprgenfunc)(bestof(totalresult)timer bestoftotal( test the benchmarking interlude |
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 functionsyielding whopping million total steps for the script at large (impressive but reasonable on most machines these daysnotice how we have to run the results of the generator expression and function through the built-in list call to force them to yield all of their valuesif we did notin both and we would just produce generators that never do any real work in python only we must do the same for the map resultsince it is now an iterable object as wellfor xthe list around map must be removed manually to avoid charging an extra list construction overhead per test (though its impact seems negligible in most testsin similar waythe inner loopsrange result is hoisted out to the top of the module to remove its construction cost from total timeand wrapped in list call so that its traversal cost isn' skewed by being generator in only (much as we did in the timer module toothis may be overshadowed by the cost of the inner iterations loopbut it' best to remove as many variables as we can also notice how the code at the bottom steps through tuple of five function objects and prints the __name__ of eachas we've seenthis is built-in attribute that gives function' name timing results when the script of the prior section is run under python get these results on my windows laptop--map is slightly faster than list comprehensionsboth are quicker than for loopsand generator expressions and functions place in the middle (times here are total time in seconds) :\codec:\python \python timeseqs py ( :bd afb ebf sep : : [msc bit (amd )forloop =[ listcomp =[ mapcall =[ genexpr =[ genfunc =[ if you study this code and its output long enoughyou'll notice that generator expressions run slower than list comprehensions today although wrapping generator ex previewnotice how we must pass functions into the timer manually here in and we'll see decorator-based timer alternatives with which timed functions are called normallybut require extra "@syntax where defined decorators may be more useful to instrument functions with timing logic when they are already being used within larger systemand don' as easily support the more isolated test call patterns assumed here--when decoratedevery call to the function runs the timing logicwhich is either plus or minus depending on your goals timing iteration alternatives |
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 do extra work to save and restore its state during value productionthe list comprehension does notand runs quicker by small constant here and in later tests interestinglywhen ran this on windows vista under python for the fourth edition of this bookand on windows xp with python for the thirdthe results were relatively similar--list comprehensions were nearly twice as fast as equivalent for loop statementsand map was slightly quicker than list comprehensions when mapping function such as the abs (absolute valuebuilt-in this way python ' absolute times were roughly four to five times slower than the current outputbut this likely reflects quicker laptops much more than any improvements in python in factmost of the python results for this script are slightly quicker than on this same machine today-- removed the list call from the map test in the following to avoid creating the results list twice in that testthough it adds only very small constant time if left inc:\codec:\python \python timeseqs py (defaultapr : : [msc bit (amd )forloop =[ listcomp =[ mapcall =[ genexpr =[ genfunc =[ for comparisonfollowing are the same testsspeed results under the current pypythe optimized python implementation discussed in whose current release implements the python language pypy is roughly (an order of magnitudequicker hereit will do even better when we revisit python version comparisons later in this using tools with different code structures (though it will lose on few other tests as well) :\codec:\pypy\pypy- \pypy exe timeseqs py ( ffjun : : [pypy with msc bitforloop =[ listcomp =[ mapcall =[ genexpr =[ genfunc =[ the benchmarking interlude |
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 following file are the same as beforeand put list back in around map for testing on only)file timeseqs py (differing partsdef forloop()res [for in repslistres append( return res def listcomp()return [ for in repslistdef mapcall()return list(map((lambda xx )repslist)list(in only def genexpr()return list( for in repslistlist(in def genfunc()def gen()for in repslistyield return list(gen()list in now the need to call user-defined function for the map call makes it slower than the for loop statementsdespite the fact that the looping statements version is larger in terms of code--or equivalentlythe removal of function calls may make the others quicker (more on this in an upcoming noteon python :\codec:\python \python timeseqs py ( :bd afb ebf sep : : [msc bit (amd )forloop =[ listcomp =[ mapcall =[ genexpr =[ genfunc =[ these results have also been consistent in cpython the prior edition' python results on slower machine were again relatively similarthough about twice as slow due to test machine differences (python results on an even slower machine were again four to five times as slow as the current resultstiming iteration alternatives |
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 seems to slow performance substantially (though may also be slower than trivial abs)and that list comprehensions run quickest in this case (though slower than map in some otherslist comprehensions seem consistently twice as fast as for loopsbut even this must be qualified--the list comprehension' relative speed might be affected by its extra syntax ( if filters)python changesand usage modes we did not time here as 've mentioned beforehoweverperformance should not be your primary concern when writing python code--the first thing you should do to optimize python code is to not optimize python codewrite for readability and simplicity firstthen optimize laterif and only if needed it could very well be that any of the five alternatives is quick enough for the data sets your program needs to processif soprogram clarity should be the chief goal for deeper truthchange this code to apply simple user-defined function in all five iteration techniques timed for instance (from timeseqs py of the book' examples)def ( )return def listcomp()return [ (xfor in repslistdef mapcall()return list(map(frepslist)the resultsin file timeseqs-results txtare then relatively similar to using built-in function like abs--at least in cpythonmap is quickest more generallyamong the five iteration techniquesmap is fastest today if all five call any functionbuilt in or notbut slowest when the others do not that ismap appears to be slower simply because it requires function callsand function calls are relatively slow in general since map can' avoid calling functionsit can lose simply by associationthe other iteration tools win because they can operate without function calls we'll prove this finding in tests run under the timeit module ahead timing module alternatives the timing module of the preceding section worksbut it could be bit more userfriendly most obviouslyits functions require passing in repetitions count as first argumentand provide no default for it-- minor pointperhapsbut less than ideal in general-purpose tool we could also leverage the min technique we saw earlier to simplify the return value slightly and remove minor overhead charge the benchmarking interlude |
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 among _reps tests bestoftotal(spam = = _rep = reps= runs best-of-totals testwhich takes the best among _reps runs of (the total of _reps runs)""import timesys timer time clock if sys platform[: ='winelse time time def total(func*pargs**kargs)_reps kargs pop('_reps' repslist list(range(_reps)start timer(for in repslistret func(*pargs**kargselapsed timer(start return (elapsedretpassed-in or default reps hoist range out for lists def bestof(func*pargs**kargs)_reps kargs pop('_reps' best * for in range(_reps)start timer(ret func(*pargs**kargselapsed timer(start if elapsed bestbest elapsed return (bestretdef bestoftotal(func*pargs**kargs)_reps kargs pop('_reps ' return min(total(func*pargs**kargsfor in range(_reps )this module' docstring at the top of the file describes its intended usage it uses dictionary pop operations to remove the _reps argument from arguments intended for the test function and provide it with default (it has an unusual name to avoid clashing with real keyword arguments meant for the function being timednotice how the best of totals here uses the min and generator scheme we saw earlier instead of nested callsin part because this simplifies results and avoids minor time overhead in the prior version (whose code fetches best of time after total time has been computed)but also because it must support two distinct repetition keywords with defaults--total and bestof can' both use the same argument name add argument prints in the code if it would help to trace its operation timing iteration alternatives |
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 (forlooplistcompmapcallgenexprgenfunc)(totalresulttimer bestoftotal(test_reps = _reps= or(totalresulttimer bestoftotal(test(totalresulttimer bestof(test_reps= (totalresulttimer total(test_reps= (bestof(totalresult)timer bestof(timer totaltest_reps= print ('%- =[% % ](test __name__totalresult[ ]result[- ])you can also run few interactive tests as we did for the original version--the results are again essentially the same as beforebut we pass in the repetition counts as keywords that provide defaults if omittedin python from timer import totalbestofbestoftotal total(pow )[ total(pow _reps= )[ total(pow _reps= )[ bestof(pow )[ bestof(pow _reps= )[ * dflt reps * reps * reps * dflt reps * mbest of bestoftotal(str upper'spam'_reps = _reps= best of tot of ( 'spam'bestof(totalstr upper'spam'_reps= nested calls work too ( ( 'spam')to see how keywords are supported nowdefine function with more arguments and pass some by namedef spam(abcd)return total(spam = = _reps= ( bestof(spam = = _reps= ( - bestoftotal(spam = = _reps = _reps= ( bestoftotal(spam*( )_reps = _reps= **dict( = = )( the benchmarking interlude |
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 must be passed by keyword and appear before the *if used the following is keyword-only-based alternative to the prior module though simplerit compiles and runs under python onlynot xfile timer py ( only""same usage as timer pybut uses keyword-only default arguments instead of dict pops for simpler code no need to hoist range(out of tests in xalways generator in xand this can' run on ""import timesys timer time clock if sys platform[: ='winelse time time def total(func*pargs_reps= **kargs)start timer(for in range(_reps)ret func(*pargs**kargselapsed timer(start return (elapsedretdef bestof(func*pargs_reps= **kargs)best * for in range(_reps)start timer(ret func(*pargs**kargselapsed timer(start if elapsed bestbest elapsed return (bestretdef bestoftotal(func*pargs_reps = **kargs)return min(total(func*pargs**kargsfor in range(_reps )this version is used the same way as the prior version and produces identical resultsso won' relist its outputs on the same tests hereexperiment on your own as you wish if you dopay attention to the argument ordering rules in calls former bes tof that ran totalfor instancecalled like this(elapsedrettotal(func*pargs_reps= **kargssee for more on keyword-only arguments in xthey can simplify code for configurable tools like this one but are not backward compatible with pythons if you want to compare and speedor support programmers using either python linethe prior version is likely better choice also keep in mind that for trivial functions like some of those tested for the prior versionthe costs of the timer' code may sometimes be as significant as those of simple timed functionso you should not take timer results too absolutely the timer' results can timing iteration alternatives |
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 might also want to look at the profile standard library module for complete source code profiler tool we'll learn more about it in in the context of development tools for large projects in generalyou should profile code to isolate bottlenecks before recoding and timing alternatives as we've done here you might try modifying or emulating the timing script to measure the speed of the and set and dictionary comprehensions shown in the preceding and their for loop equivalents using them is less common in python programs than building lists of resultsso we'll leave this task in the suggested exercise column (pleaseno wagering )the next section will partly spoil the surprise finallykeep the timing module we wrote here filed away for future reference--we'll repurpose it to measure performance of alternative numeric square root operations in an exercise at the end of this if you're interested in pursuing this topic furtherwe'll also experiment with techniques for timing dictionary comprehensions versus for loops interactively in the exercises timing iterations and pythons with timeit the preceding section used homegrown timing functions to compare code speed as mentioned therethe standard library also ships with module named timeit that can be used in similar waysbut offers added flexibility and may better insulate clients from some platform differences as usual in pythonit' important to understand fundamental principles like those illustrated in the prior section python' "batteries includedapproach means you'll usually find precoded options as wellthough you still need to know the ideas underlying them to use them properly indeedthis module is prime example of this--it seems to have had history of being misused by people who don' yet understand the principles it embodies now that we've learned the basicsthoughlet' move ahead to tool that can automate much of our work the benchmarking interlude |
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 ( \ \ttests may also give setup actionsand can be launched from both command lines and api callsand from both scripts and the interactive prompt interactive usage and api calls for examplethe timeit module' repeat call returns list giving the total time taken to run test number of timesfor each of repeat runs--the min of this list yields the best time among the runsand helps filter out system load fluctuations that can otherwise skew timing results artificially high the following shows this call in actiontiming list comprehension on two versions of cpython and the optimized pypy implementation of python described in (it currently supports python codethe results here give the best total time in seconds among runs that each execute the code string , timesthe code string itself constructs , -item list of integers each time through (see appendix for the windows launcher used for variety in the first two of these commands) :\codepy - python ( :bd afb ebf sep : : [msc bit import timeit min(timeit repeat(stmt="[ * for in range( )]"number= repeat= ) :\codepy - python (defaultapr : : [msc bit (amd )on win import timeit min(timeit repeat(stmt="[ * for in range( )]"number= repeat= ) :\codec:\pypy\pypy- \pypy exe python ( ffjun : : [pypy with msc biton win import timeit min(timeit repeat(stmt="[ * for in range( )]"number= repeat= ) you'll notice that pypy checks in at faster than cpython hereand whopping faster than cpython despite the fact that pypy is potentially slower -bit build this is small artificial benchmarkof coursebut seems arguably stunning nonethelessand reflects relative speed ranking that is generally supported by other tests run in this book (though as we'll seecpython still beats pypy on some types of codetiming iterations and pythons with timeit |
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 matters-the one and two order of magnitude (power of speedups here will be realized by many real programsbecause integers and iterations are ubiquitous in python code these results also differ from the preceding section' relative version speedswhere cpython was slightly quicker than and pypy was quicker overalla figure affirmed by most other tests in this book too apart from the different type of code being timed herethe different coding structure inside timeit may have an effect too-for code strings like those tested heretimeit buildscompilesand executes function def statement string that embeds the test stringthereby avoiding function call per inner loop as we'll see in the next sectionthoughthis appears irrelevant from relative-speed perspective command-line usage the timeit module has reasonable defaults and can be also run as scripteither by explicit filename or automatically located on the module search path with python' - flag (see appendix aall the following run python ( cpython in this mode timeit reports the average time for single - loopin either microseconds (labeled "usec")milliseconds ("msec")or seconds ("sec")to compare results here to the total time values reported by other testsmultiply by the number of loops run- usec here , loops is msecor half second in total timec:\codec:\python \lib\timeit py - "[ * for in range( )] loopsbest of usec per loop :\codepython - timeit - "[ * for in range( )] loopsbest of usec per loop :\codepy - - timeit - - "[ * for in range( )] loopsbest of usec per loop as an examplewe can use command lines to verify that choice of timer call doesn' impact cross-version speed comparisons run in this so far-- uses its new calls by defaultand that might matter if timer precision differs widely to prove that this is irrelevantthe following uses the - flag to force timeit to use time clock in all versionsan option that ' manuals call deprecatedbut required to even the score with prior versions ( ' setting my system path to include pypy here for command brevity) :\codeset path=%path%; :\pypy\pypy- :\codepy - - timeit - - - "[ * for in range( )] loopsbest of usec per loop :\codepy - - timeit - - - "[ * for in range( )] the benchmarking interlude |
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 are essentially the same as those for earlier tests in this on the same types of code when applying * cpython and pypy are again and faster than cpython respectivelyshowing that timer choice isn' factor for the abs(xwe timed under the homegrown timer earlier (timeseqs py)these two pythons are faster than by small constant and just as beforeimplying that timeit' different code structure doesn' impact relative comparisons--the type of code being tested fully determines the size of speed differences subtle pointnotice that the results of the last three of these testswhich mimic tests run for the homegrown timer earlierare basically the same as beforebut seem to incur small net overhead for range usage differences--it was prebuilt list formerlybut here is either generator or list built anew on each inner total loop in other wordswe're not timing the exact same thingbut the relative speeds of the pythons tested are the same timing multiline statements to time larger multiline sections of code in api call modeuse line breaks and tabs or spaces to satisfy python' syntaxcode read from source file already will because you pass python string objects to python function in this modethere are no shell considerationsthough be careful to escape nested quotes if needed the followingfor instancetimes loop alternatives in python you can use the same pattern to time the file-line-reader alternatives in :\codepy - import timeit min(timeit repeat(number= repeat= stmt=" [ ]\nfor in range(len( )) [ + ") min(timeit repeat(number= repeat= stmt=" [ ]\ni= \nwhile len( ):\ \tl[ + \ \ti + ") min(timeit repeat(number= repeat= stmt=" [ ]\nm [ for in ]") to run multiline statements like these in command-line modeappease your shell by passing each statement line as separate argumentwith whitespace for indentation-timing iterations and pythons with timeit |
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 - - " [ , , , , ]" [ for in ] loopsbest of usec per loop other usage modessetuptotalsand objects the timeit module also allows you to provide setup code that is run in the main statement' scopebut whose time is not charged to the main statement' total--potentially useful for initialization code you wish to exclude from total timesuch as imports of required modulestest function definitionand test data creation because they're run in the same scopeany names created by setup code are available to the main test statementnames defined in the interactive shell generally are not to specify setup codeuse - in command-line mode (or many of these for multiline setupsand setup argument string in api call mode this can focus tests more sharplyas in the followingwhich splits list initialization off to setup statement to time just iteration as rule of thumbthoughthe more code you include in test statementthe more applicable its results will generally be to realistic codec:\codepython - timeit - - " [ , , , , ]" [ for in ] loopsbest of usec per loop :\codepython - timeit - - - " [ , , , , ]" [ for in ] loopsbest of usec per loop here' setup example in api call modei used the following type of code to time the sort-based option in ' minimum value example--ordered ranges sort much faster than random numbersand are faster sorted than scanned linearly in the example' code under (adjacent strings are concatenated here)from timeit import repeat min(repeat(number= repeat= setup='from mins import min min min \ 'vals=list(range( ))'stmt'min (*vals)') min(repeat(number= repeat= setup='from mins import min min min \ 'import random\nvals=[random random(for in range( )]'stmt'min (*vals)') the benchmarking interlude |
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 time timeit timer(stmt='[ * for in range( )]'timeit( class api timeit repeat(stmt='[ * for in range( )]'number= repeat= [ def testcase() [ * for in range( )callable objects or code strings min(timeit repeat(stmt=testcasenumber= repeat= ) benchmark module and scripttimeit rather than go into more details on this modulelet' study program that deploys it to time both coding alternatives and python versions the following filepybench pyis set up to time set of statements coded in scripts that import and use itunder either the version running its code or all python versions named in list it uses some application-level tools described ahead because it mostly applies ideas we've already learned and is amply documentedthoughi' going to list this as mostly self-study materialand an exercise in reading python code ""pybench pytest speed of one or more pythons on set of simple code-string benchmarks functionto allow stmts to vary this system itself runs on both and xand may spawn both uses timeit to test either the python running this script by api callsor set of pythons by reading spawned command-line outputs (os popenwith python' - flag to find timeit on module search path replaces $listif with list(around generators for and an empty string for xso does same work as in command-line mode onlymust split multiline statements into one separate quoted argument per line so all will be run (else might run/time first line only)and replace all \ in indentation with spaces for uniformity caveatscommand-line mode (onlymay fail if test stmt embeds double quotesquoted stmt string is incompatible with shell in generalor command-line exceeds length limit on platform' shell--use api call mode or homegrown timerdoes not yet support setup statementas istime of all statements in the test stmt are charged to the total time ""timing iterations and pythons with timeit |
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 or defnum repeat repeat or defrep =default if not pythonsrun stmt on this pythonapi call no need to split lines or quote here ispy sys version[ =' stmt stmt replace('$listif ''listif ispy else ''best min(timeit repeat(stmt=stmtnumber=numberrepeat=repeat)print(' [% ](beststmt[: ])elserun stmt on all pythonscommand line split lines into quoted arguments print('- print('[% ]stmtfor (ispy pythonin pythonsstmt stmt replace('$listif ''listif ispy else ''stmt stmt replace('\ ' lines stmt split('\ 'args join('"% "line for line in linescmd '% - timeit - % - % % (pythonnumberrepeatargsprint(pythonif tracecmdprint(cmdprint('\tos popen(cmdread(rstrip()this file is really only half the picturethough testing scripts use this module' functionpassing in concrete though variable lists of statements and pythons to be testedas appropriate for the usage mode desired for examplethe following scriptpybench_cases pytests handful of statements and pythonsand allows command-line arguments to determine part of its operation- tests all listed pythons instead of just oneand an added - traces constructed command lines so you can see how multiline statements and indentation are handled per the command-line formats shown earlier (see both filesdocstrings for details)""pybench_cases pyrun pybench on set of pythons and statements select modes by editing this script or using command-line arguments (in sys argv) run " :\python \python pybench_cases pyto test just one specific version on stmts"pybench_cases py -ato test all pythons listedor "py - pybench_cases py - -tto trace command lines too the benchmarking interlude |
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,rpt,stmtiterations \ =multistmt \ \ =indent $=list or 'string ops tracecmd '-tin sys argv pythons pythons if '-ain sys argv else none pybench runner(stmtspythonstracecmd-ttrace command lines-aall in listelse onebenchmark script results here is this script' output when run to test specific version (the python running the script)--this mode uses direct api callsnot command lineswith total time listed in the left columnand the statement tested on the right ' again using the windows launcher in the first two of these tests to time cpython and and am running release of the pypy implementation in the thirdc:\codepy - pybench_cases py ( :bd afb ebf sep : : [msc bit (amd ) ['[ * for in range( )]' ['res=[]\nfor in range( )res append( * )' ['list(map(lambda xx * range( )))' ['list( * for in range( ))' [" 'spam \nx [ [ifor in range( )]" [" '?'\nfor in range( ) +'?'" :\codepy - pybench_cases py (defaultapr : : [msc bit (amd ) ['[ * for in range( )]' ['res=[]\nfor in range( )res append( * )' ['(map(lambda xx * range( )))' ['list( * for in range( ))' [" 'spam \nx [ [ifor in range( )]" [" '?'\nfor in range( ) +'?'" :\codec:\pypy\pypy- \pypy pybench_cases py ( ffjun : : [pypy with msc bit ['[ * for in range( )]' ['res=[]\nfor in range( )res append( * )'timing iterations and pythons with timeit |
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 start other pythons to run the timeit module on the test statement strings this mode must splitformatand quote multiline statements for use in command lines according to timeit expectations and shell requirements this mode also relies on the - python command-line flag to locate timeit on the module search path and run it as scriptand the os popen and sys argv standard library tools to run shell command and inspect command-line argumentsrespectively see python manuals and other sources for more on these callsos popen is also mentioned briefly in the files coverage of and demonstrated in the loops coverage in run with - flag to watch the command lines runc:\codepy - pybench_cases py - ( :bd afb ebf sep : : [msc bit (amd )['[ * for in range( )]' :\python \python loopsbest of usec per loop :\python \python loopsbest of usec per loop :\pypy\pypy- \pypy loopsbest of usec per loop ['res=[]\nfor in range( )res append( * )' :\python \python loopsbest of usec per loop :\python \python loopsbest of usec per loop :\pypy\pypy- \pypy loopsbest of usec per loop ['$listif (map(lambda xx * range( )))' :\python \python loopsbest of usec per loop :\python \python loopsbest of usec per loop :\pypy\pypy- \pypy loopsbest of usec per loop ['list( * for in range( ))' :\python \python loopsbest of usec per loop :\python \python loopsbest of usec per loop :\pypy\pypy- \pypy loopsbest of usec per loop [" 'spam \nx [ [ifor in range( )]" the benchmarking interlude |
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 testscpython is still quicker than cpython and pypy is noticeably faster than both of them--except on the last test where pypy is twice as slow as cpythonpresumably due to memory management differences on the other handtiming results are often relative at best in addition to other general timing caveats mentioned in this timeit may skew results in ways beyond our scope to explore here ( garbage collectionthere is baseline overheadwhich differs per python versionthat is ignored here (but appears trivialthis script runs very small statements that may or may not reflect real-world code (but are still validresults may occasionally vary in ways that seem random (using process time may help hereall results here are highly prone to change over time (in each new python releasein fact!in other wordsyou should draw your own conclusions from these numbersand run these tests on your pythons and machines for results more relevant to your needs to time the baseline overhead of each pythonrun timeit with no statement argumentor equivalentlywith pass statement more fun with benchmarks for more insighttry running the script on other python versions and other statement test strings the file pybench_cases py in this book' examples distribution adds more tests to see how cpython compares to how pypy' beta stacks up against its current releaseand how additional use cases fare timing iterations and pythons with timeit |
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')( ' :\pypy\pypy- -beta \pypy')stmts +use function callsmap wins ( "[ord(xfor in 'spam ]")( "res=[]\nfor in 'spam res append(ord( ))")( "$listif (map(ord'spam ))")( "list(ord(xfor in 'spam )")set and dicts ( "{ * for in range( )}")( " =set()\nfor in range( ) add( * )")( "{xx * for in range( )}")( " ={}\nfor in range( ) [xx * ")pathological digits ( "len(str( ** ))")pypy loses on this today here is the script' results on these statement tests on cpython xshowing how map is quickest when function calls level the playing field (it lost earlier when the other tests ran an inline * ) :\codepy - pybench_cases py ( :bd afb ebf sep : : [msc bit (amd ) ["[ord(xfor in 'spam ]" ["res=[]\nfor in 'spam res append(ord( ))" ["list(map(ord'spam ))" ["list(ord(xfor in 'spam )" ['{ * for in range( )}' [' =set()\nfor in range( ) add( * )' ['{xx * for in range( )}' [' ={}\nfor in range( ) [xx * ' ['len(str( ** ))'as beforeon these tests today clocks in faster than and pypy is faster still on all of these tests but the last--which it loses by full order of magnitude ( )though it wins all the other tests here by the same degree howeverif you run file tests precoded in pybench_cases py you'll see that pypy also loses to cpython when reading files line by lineas for the following test tuple on the stmts list( " =open(' :/python /lib/pdb py')\nfor line in fx=line\nf close()")this test opens and reads , -line text file line by line using file iterators its input loop presumably dominates overall test time on this testcpython is twice as fast as but pypy is again an order of magnitude slower than cpython in general the benchmarking interlude |
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 and pypy' current file speedsee the file listcomp-speed txt in the book examples packageit uses direct pypy command lines to run code from with similar resultspypy' line input is slower today by roughly factor of 'll omit other pythonsoutput here both for space and because these findings could very well change by the time you read these words as usualdifferent types of code can exhibit different types of performance while pypy may optimize much algorithmic codeit may or may not optimize yours you can find additional results in the book' examples packagebut you may be better served by running these tests on your own to verify these findings today or observe their possibly different results in the future the impact of function calls revisited as suggested earliermap also wins for added user-defined functions--the following tests prove the earlier note' claim that map wins the race in cpython if any function must be applied by its alternativesstmts ( "def ( )return \ [ (xfor in 'spam ]")( "def ( )return \nres=[]\nfor in 'spam res append( ( ))")( "def ( )return \ $listif (map( 'spam ))")( "def ( )return \nlist( (xfor in 'spam )") :\codepy - pybench_cases py ( :bd afb ebf sep : : [msc bit (amd ) ["def ( )return \ [ (xfor in 'spam ]" ["def ( )return \nres=[]\nfor in 'spam res append( ( ))" ["def ( )return \nlist(map( 'spam ))" ["def ( )return \nlist( (xfor in 'spam )"compare this with the preceding section' ord teststhough user-defined functions may be slower than built-insthe larger speed hit today seems to be functions in generalwhether they are built-in or not notice that the total time here includes the cost of making helper functionthough only one for every , inner loop repetitions-- negligible factor per both common sense and additional tests run comparing techniqueshomegrown versus batteries for perspectivelet' see how this section' timeit-based results compare to the homegrown-based timer results of the prior sectionby running the file timeseqs py in this timing iterations and pythons with timeit |
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(map(lambda xx * range( )))' ['list( * for in range( ))' [" 'spam \nx [ [ifor in range( )]" [" '?'\nfor in range( ) +'?'"the homegrown timer results are very similar to the pybench-based results of this section that use timeitthough it' not entirely apples-to-apples--the homegrown timerbased timeseqs py incurs function call per its middle totals loop and slight overhead in best of logic of the timer itselfbut also uses prebuilt list instead of range generator in its inner loopwhich seems to make it slightly net faster on comparable tests (and ' call this example "sanity check,but ' not sure the term applies in benchmarking!room for improvementsetup like most softwarethis section' program is open-ended and could be expanded arbitrarily as one examplethe files pybench py and pybench _cases py in the book' examples package add support for timeit' setup statement option described earlierin both api call and command-line modes this feature was omitted initially for brevityand franklybecause my tests didn' seem to require it--timing more code gives more complete picture when comparing pythonsand setup actions cost the same when timing alternatives on single python even soit' sometimes useful to provide setup code that is run once in the tested code' scopebut whose time is not charged to the statement' total-- module importobject initializationor helper function definitionfor example won' list these two files in wholebut here are their important varying bits as an example of software evolution at work--as for the test statementthe setup code statement is passed as is in api call modebut is split and space-indented in command-line mode and passed with one - argument per line ("$listif isn' used because setup code is not timed)pybench py def runner(stmtspythons=nonetracecmd=false) the benchmarking interlude |
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 in range( )]")( """res=[]\nfor in range( )res append( * )")( "def ( ):\ \treturn ""[ (xfor in 'spam ]")( "def ( ):\ \treturn ""res=[]\nfor in 'spam :\ \tres append( ( ))")( " [ ]""for in range(len( )) [ + ")( " [ ]"" = \nwhile len( ):\ \tl[ + \ \ti + ")pybench runner(stmtspythonstracecmdrun this script with the - and - command-line flags to see how command lines are constructed for setup code for instancethe following test specification tuple generates the command line that follows it for --not nice to look atperhapsbut sufficient to pass lines from windows to timeitto be concatenated with line breaks between and inserted into generated timing function with appropriate reindentation( "def ( ):\ \treturn ""res=[]\nfor in 'spam :\ \tres append( ( ))" :\python \python - timeit - - - "def ( ):- "for in 'spam :res append( ( ))return "res=[]in api call modecode strings are passed unchangedbecause there' no need to placate shelland embedded tabs and end-of-line characters suffice experiment on your own to uncover more about python code alternativesspeed you may eventually run into shell limitations for larger sections of code in command-line modebut both our homegrown timer and pybench' timeit-based api call mode support more arbitrary code benchmarks can be great sportbut we'll have to leave future improvements as suggested exercises timing iterations and pythons with timeit |
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 furthersearch the web for links among the topics you'll findpystone py-- program designed for measuring python speed across range of code that ships with python in its lib\test directory benchmarks partially emulating the pystone testfor exampleis based on language benchmark program that was translated to python by python original creator guido van rossum it provides another way to measure the relative speeds of python implementationsand seems to generally support our findings herec:\python \lib\testcd :\python \lib\test :\python \lib\testpy - pystone py pystone( time for passes this machine benchmarks at pystones/second :\python \lib\testcd :\python \lib\test :\python \lib\testpy - pystone py pystone( time for passes this machine benchmarks at pystones/second :\python \lib\testc:\pypy\pypy- \pypy pystone py pystone( time for passes this machine benchmarks at pystones/second since it' time to wrap up this this will have to suffice as independent confirmation of our testsresults analyzing the meaning of pystone' results is left as suggested exerciseits code is not identical across and xbut appears to differ today only in terms of print operations and an initialization of global also keep in mind that benchmarking is just one of many aspects of python code analysisfor pointers on options in related domains ( testing)see ' review of python development tools function gotchas now that we've reached the end of the function storylet' review some common pitfalls functions have some jagged edges that you might not expect they're all relatively the benchmarking interlude |
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 compiles the def' coderather than by noticing assignments as they happen at runtime this leads to one of the most common oddities posted on the python newsgroup by beginners normallya name that isn' assigned in function is looked up in the enclosing modulex def selector()print(xx used but not assigned found in global scope selector( herethe in the function resolves to the in the module but watch what happens if you add an assignment to after the referencedef selector()print(xx does not yet existx classified as local name (everywherecan also happen for "import ""def xselector(unboundlocalerrorlocal variable 'xreferenced before assignment you get the name usage error shown herebut the reason is subtle python reads and compiles this code when it' typed interactively or imported from module while compilingpython sees the assignment to and decides that will be local name everywhere in the function but when the function is actually runbecause the assignment hasn' yet happened when the print executespython says you're using an undefined name according to its name rulesit should say thisthe local is used before being assigned in factany assignment in function body makes name local imports=nested defsnested classesand so on are all susceptible to this behavior the problem occurs because assigned names are treated as locals everywhere in functionnot just after the statements where they're assigned reallythe previous example is ambiguouswas the intention to print the global and create local xor is this real programming errorbecause python treats as local everywhereit' seen as an errorif you mean to print the global xyou need to declare it in global statementdef selector()global print(xx force to be global (everywherefunction gotchas |
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 to the global versionx def selector()import __main__ print(__main__ xx print(ximport enclosing module qualify to get to global version of name unqualified classified as local prints local version of name selector( qualification (the partfetches value from namespace object the interactive namespace is module called __main__so __main__ reaches the global version of if that isn' clearcheck out in recent versions python has improved on this story somewhat by issuing for this case the more specific "unbound localerror message shown in the example listing (it used to simply raise generic name error)this gotcha is still present in generalthough defaults and mutable objects as noted briefly in and mutable values for default arguments can retain state between callsthough this is often unexpected in generaldefault argument values are evaluated and saved once when def statement is runnot each time the resulting function is later called internallypython saves one object per default argument attached to the function itself that' usually what you want--because defaults are evaluated at def timeit lets you save values from the enclosing scopeif needed (functions defined within loops by factories may even depend on this behavior--see aheadbut because default retains an object between callsyou have to be careful about changing mutable defaults for instancethe following function uses an empty list as default valueand then changes it in place each time the function is calleddef saver( =[]) append( print(xsaves away list object changes same object each timesaver([ ][ saver([ default not used the benchmarking interlude default used |
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 will not clash with names elsewhere in program to other observersthoughthis seems like gotchaespecially the first time they run into it there are better ways to retain state between calls in python ( using the nested scope closures we met in this part and the classes we will study in part vimoreovermutable defaults are tricky to remember (and to understand at allthey depend upon the timing of default object construction in the prior examplethere is just one list object for the default value--the one created when the def is executed you don' get new list every time the function is calledso the list grows with each new appendit is not reset to empty on each call if that' not the behavior you wantsimply make copy of the default at the start of the function bodyor move the default value expression into the function body as long as the value resides in code that' actually executed each time the function runsyou'll get new object each time throughdef saver( =none)if is nonex [ append( print(xsaver([ ][ saver([ saver([ no argument passedrun code to make new list each time changes new list object doesn' grow here by the waythe if statement in this example could almost be replaced by the assignment or []which takes advantage of the fact that python' or returns one of its operand objectsif no argument was passedx would default to noneso the or would return the new empty list on the right howeverthis isn' exactly the same if an empty list were passed inthe or expression would cause the function to extend and return newly created listrather than extending and returning the passed-in list like the if version (the expression becomes [or []which evaluates to the new empty list on the rightsee the section "truth testsif you don' recall why real program requirements may call for either behavior function gotchas |
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 explicit (and arguably less magicalfunctions without returns in python functionsreturn (and yieldstatements are optional when function doesn' return value explicitlythe function exits when control falls off the end of the function body technicallyall functions return valueif you don' provide return statementyour function returns the none object automaticallydef proc( )print(xno return is none return proc('testing 'testing print(xnone functions such as this without return are python' equivalent of what are called "proceduresin some languages they're usually invoked as statementsand the none results are ignoredas they do their business without computing useful result this is worth knowingbecause python won' tell you if you try to use the result of function that doesn' return one as we noted in for instanceassigning the result of list append method won' raise an errorbut you'll get back nonenot the modified listlist [ list list append( print(listnone append is "procedureappend changes list in place ' section "common coding gotchason page discusses this more broadly in generalany functions that do their business as side effect are usually designed to be run as statementsnot expressions the benchmarking interlude |
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 scope lookup for variables that are changed by enclosing loops --when generated function is later calledall such references will remember the value of the last loop iteration in the enclosing function' scope in this caseyou must use defaults to save loop variable values instead of relying on automatic lookup in enclosing scopes see "loop variables may require defaultsnot scopeson page in for more details on this topic hiding built-ins by assignmentshadowing also in we saw how it' possible to reassign built-in names in closer local or global scopethe reassignment effectively hides and replaces that built-in' name for the remainder of the scope where the assignment occurs this means you won' be able to use the original built-in value for the name as long as you don' need the built-in value of the name you're assigningthis isn' an issue--many names are built inand they may be freely reused howeverif you reassign built-in name your code relies onyou may have problems so either don' do thator use tools like pychecker that can warn you if you do the good news is that the built-ins you commonly use will soon become second natureand python' error trapping will alert you early in testing if your built-in name is not what you think it is summary this rounded out our look at functions and built-in iteration tools with larger case study that measured the performance of iteration alternatives and pythonsand closed with review of common function-related mistakes to help you avoid pitfalls the iteration story has one last sequel in part viwhere we'll learn how to code userdefined iterable objects that generate values with classes and __iter__in ' operator overloading coverage this concludes the functions part of this book in the next partwe will expand on what we already know about modules--files of tools that form the topmost organizational unit in pythonand the structure in which our functions always live after thatwe will explore classestools that are largely packages of functions with special first arguments as we'll seeuser-defined classes can implement objects that tap into the iteration protocoljust like the generators and iterables we met here in facteverything we have summary |
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 draw from this about the relative speed of the pythons timedtest your knowledgeanswers in generallist comprehensions are usually the quickest of the bunchmap beats list comprehensions in python only when all tools must call functionsfor loops tend to be slower than comprehensionsand generator functions and expressions are slower than comprehensions by constant factor under pypysome of these findings differmap often turns in different relative performancefor exampleand list comprehensions seem always quickestperhaps due to function-level optimizations at least that' the case today on the python versions testedon the test machine usedand for the type of code timed--these results may vary if any of these three variables differ use the homegrown timer or standard library timeit to test your use cases for more relevant results also keep in mind that iteration is just one component of program' timemore code gives more complete picture in generalpypy (implementing python is typically faster than cpython and cpython is often faster than cpython in most cases timedpypy is some faster than cpythonand cpython is often small constant faster than cpython in cases that use integer mathcpython can be faster than cpython and pypy can be faster than in other cases ( string operations and file iterators)pypy can be slower than cpython by xthough timeit and memory management differences may influence some results the pystone benchmark confirms these relative rankingsthough the sizes of the differences it reports differ due to the code timed at least that' the case today on the python versions testedon the test machine usedand for the type of code timed--these results may vary if any of these three variables differ use the homegrown timer or standard library timeit to test your use cases for more relevant results this is especially true when timing python implementationswhich may be arbitrarily optimized in each new release the benchmarking interlude |
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 single argument to the screen and call it interactivelypassing variety of object typesstringintegerlistdictionary thentry calling it without passing any argument what happenswhat happens when you pass two arguments arguments write function called adder in python module file the function should accept two arguments and return the sum (or concatenationof the two thenadd code at the bottom of the file to call the adder function with variety of object types (two stringstwo liststwo floating points)and run this file as script from the system command line do you have to print the call statement results to see results on your screen varargs generalize the adder function you wrote in the last exercise to compute the sum of an arbitrary number of argumentsand change the calls to pass more or fewer than two arguments what type is the return value sum(hintsa slice such as [: returns an empty sequence of the same type as sand the type builtin function can test typesbut see the manually coded min examples in for simpler approach what happens if you pass in arguments of different typeswhat about passing in dictionaries keywords change the adder function from exercise to accept and sum/concatenate three argumentsdef adder(goodbaduglynowprovide default values for each argumentand experiment with calling the function interactively try passing onetwothreeand four arguments thentry passing keyword arguments does the call adder(ugly= good= workwhyfinallygeneralize the new adder to accept and sum/concatenate an arbitrary number of keyword arguments this is similar to what you did in exercise but you'll need to iterate over dictionarynot tuple (hintthe dict keys method returns list you can step through with for or whilebut be sure to wrap it in list call to index it in xdict values may help here too dictionary tools write function called copydict(dictthat copies its dictionary argument it should return new dictionary containing all the items in its argument use the dictionary keys method to iterate (orin python and laterstep over dictionary' keys without calling keyscopying sequences is easy ( [:makes top-level copy)does this work for dictionariestooas explained in this exercise' solutionbecause dictionaries now come with similar toolsthis and the next exercise are just coding exercises but still serve as representative function examples dictionary tools write function called adddict(dict dict that computes the union of two dictionaries it should return new dictionary containing all the items test your knowledgepart iv exercises |
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 casetoo(hintsee the type built-in function used earlier does the order of the arguments passed in matter more argument-matching examples firstdefine the following six functions (either interactively or in module file that can be imported)def (ab)print(abdef ( * )print(abnormal args positional varargs def ( ** )print(abkeyword varargs def ( * ** )print(abcmixed modes def (ab= = )print(abcdefaults def (ab= * )print(abcdefaults and positional varargs nowtest the following calls interactivelyand try to explain each resultin some casesyou'll probably need to fall back on the matching algorithm shown in do you think mixing matching modes is good idea in generalcan you think of cases where it would be usefulf ( ( = = ( ( = = ( = = ( ( ( ( primes revisited recall the following code snippet from which simplistically determines whether positive integer is primex / while if = print( 'has factor'xbreak - elseprint( 'is prime'for some remainder skip else normal exit package this code as reusable function in module file ( should be passed-in argument)and add some calls to the function at the bottom of your file while you're at itexperiment with replacing the first line' /operator with to see how the benchmarking interlude |
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 loop firstthen as map callthen as list comprehensionand finally as generator expression use the sqrt function in the built-in math module to do the calculation ( import math and say math sqrt( )of the fourwhich approach do you like best timing tools in we saw three ways to compute square rootsmath sqrt( ) * and pow( if your programs run lot of thesetheir relative performance might become important to see which is quickestrepurpose the timerseqs py script we wrote in this to time each of these three tools use the bestof or bestoftotal functions in one of this timer modules to test (you can use either the originalthe -only keyword-only variantor the versionand may use python' timeit module as wellyou might also want to repackage the testing code in this script for better reusability--by passing test functions tuple to general tester functionfor example (for this exercise copyand-modify approach is finewhich of the three square root tools seems to run fastest on your machine and python in generalfinallyhow might you go about interactively timing the speed of dictionary comprehensions versus for loops recursive functions write simple recursion function named countdown that prints numbers as it counts down to zero for examplea call countdown( will print stop there' no obvious reason to code this with an explicit stack or queuebut what about nonfunction approachwould generator make sense here computing factorials finallya computer science classic (but demonstrative nonethelesswe employed the notion of factorials in ' coverage of permutationsn!computed as *( - )*( - ) for instance is * * * * * or code and time four functions thatfor call fact( )each return ncode these four functions ( as recursive countdown per ( using the functional reduce call per ( with simple iterative counter loop per and ( using the math factorial library tool per use ' timeit to time each of your functions what conclusions can you draw from your resultstest your knowledgepart iv exercises |
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 program files each file is moduleand modules import other modules to use the names they define modules might also correspond to extensions coded in external languages such as cjavaor #and even to directories in package imports modules are processed with two statements and one important functionimport lets client (importerfetch module as whole from allows clients to fetch particular names from module imp reload (reload in xprovides way to reload module' code without stopping python introduced module fundamentalsand we've been using them ever since the goal here is to expand on the core module concepts you're already familiar withand move on to explore more advanced module usage this first reviews module basicsand offers general look at the role of modules in overall program structure in the that followwe'll dig into the coding details behind the theory along the waywe'll flesh out module details omitted so far--you'll learn about reloadsthe __name__ and __all__ attributespackage importsrelative import syntax namespace packagesand so on because modules and classes are really just glorified namespaceswe'll formalize namespace concepts here as well why use modulesin shortmodules provide an easy way to organize components into system by serving as self-contained packages of variables known as namespaces all the names defined at |
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 three rolescode reuse as discussed in modules let you save code in files permanently unlike code you type at the python interactive promptwhich goes away when you exit pythoncode in module files is persistent--it can be reloaded and rerun as many times as needed just as importantlymodules are place to define namesknown as attributeswhich may be referenced by multiple external clients when used wellthis supports modular program design that groups functionality into reusable units system namespace partitioning modules are also the highest-level program organization unit in python although they are fundamentally just packages of namesthese packages are also self-contained--you can never see name in another fileunless you explicitly import that file much like the local scopes of functionsthis helps avoid name clashes across your programs in factyou can' avoid this feature--everything "livesin moduleboth the code you run and the objects you create are always implicitly enclosed in modules because of thatmodules are natural tools for grouping system components implementing shared services or data from an operational perspectivemodules are also useful for implementing components that are shared across system and hence require only single copy for instanceif you need to provide global object that' used by more than one function or fileyou can code it in module that can then be imported by many clients at least that' the abstract story--for you to truly understand the role of modules in python systemwe need to digress for moment and explore the general structure of python program python program architecture so far in this booki've sugarcoated some of the complexity in my descriptions of python programs in practiceprograms usually involve more than just one file for all but the simplest scriptsyour programs will take the form of multifile systems--as the code timing programs of the preceding illustrate even if you can get by with coding single file yourselfyou will almost certainly wind up using external files that someone else has already written modulesthe big picture |
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 consists of text files containing python statementswith one main top-level fileand zero or more supplemental files known as modules here' how this works the top-level ( scriptfile contains the main flow of control of your program--this is the file you run to launch your application the module files are libraries of tools used to collect components used by the top-level fileand possibly elsewhere top-level files use tools defined in module filesand modules use tools defined in other modules although they are files of code toomodule files generally don' do anything when run directlyratherthey define tools intended for use in other files file imports module to gain access to the tools it defineswhich are known as its attributes--variable names attached to objects such as functions ultimatelywe import modules and access their attributes to use their tools imports and attributes let' make this bit more concrete figure - sketches the structure of python program composed of three filesa pyb pyand py the file py is chosen to be the top-level fileit will be simple text file of statementswhich is executed from top to bottom when launched the files py and py are modulesthey are simple text files of statements as wellbut they are not usually launched directly insteadas explained previouslymodules are normally imported by other files that wish to use the tools the modules define for instancesuppose the file py in figure - defines function called spamfor external use as we learned when studying functions in part ivb py will contain python def statement to generate the functionwhich you can later run by passing zero or more values in parentheses after the function' namedef spam(text)print(text'spam'file py nowsuppose py wants to use spam to this endit might contain python statements such as the followingimport spam('gumby'file py prints "gumby spampython program architecture |
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 thesea python import statementgives the file py access to everything defined by top-level code in the file py the code import roughly meansload the file py (unless it' already loaded)and give me access to all its attributes through the name to satisfy such goalsimport (andas you'll see laterfromstatements execute and load other files on request more formallyin pythoncross-file module linking is not resolved until such import statements are executed at runtimetheir net effect is to assign module names--simple variables like --to loaded module objects in factthe module name used in an import statement serves two purposesit identifies the external file to be loadedbut it also becomes variable assigned to the loaded module similarlyobjects defined by module are also created at runtimeas the import is executingimport literally runs statements in the target file one at time to create its contents along the wayevery name assigned at the top-level of the file becomes an attribute of the moduleaccessible to importers for examplethe second of the statements in py calls the function spam defined in the module --created by running its def statement during the import--using object attribute notation the code spam meansfetch the value of the name spam that lives within the object this happens to be callable function in our exampleso we pass string in parentheses ('gumby'if you actually type these filessave themand run pythe words "gumby spamwill be printed as we've seenthe object attribute notation appears throughout python code--most objects have useful attributes that are fetched with the operator some reference callable objects like functions that take action ( salary computer)and others are modulesthe big picture |
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 import bwhich can import cwhich can import againand so on besides serving as the highest organizational structuremodules (and module packagesdescribed in are also the highest level of code reuse in python coding components in module files makes them useful in your original programand in any other programs you may write later for instanceif after coding the program in figure - we discover that the function spam is general-purpose toolwe can reuse it in completely different programall we have to do is import the file py again from the other program' files standard library modules notice the rightmost portion of figure - some of the modules that your programs will import are provided by python itself and are not files you will code python automatically comes with large collection of utility modules known as the standard library this collectionover modules large at last countcontains platform-independent support for common programming tasksoperating system interfacesobject persistencetext pattern matchingnetwork and internet scriptinggui constructionand much more none of these tools are part of the python language itselfbut you can use them by importing the appropriate modules on any standard python installation because they are standard library modulesyou can also be reasonably sure that they will be available and will work portably on most platforms on which you will run python this book' examples employ few of the standard library' modules--timeitsysand os in last codefor instance--but we'll really only scratch the surface of the libraries story here for complete lookyou should browse the standard python library reference manualavailable either online at python installation (via idle or python' start button menu on some windowsthe pydoc tool discussed in is another way to explore standard library modules because there are so many modulesthis is really the only way to get feel for what tools are available you can also find tutorials on python library tools in commercial books that cover application-level programmingsuch as 'reilly' programming pythonbut the manuals are freeviewable in any web browser (in html format)viewable in other formats ( windows help)and updated each time python is rereleased see for more pointers python program architecture |
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 import operation to #includebut they really shouldn' --in pythonimports are not just textual insertions of one file into another they are really runtime operations that perform three distinct steps the first time program imports given file find the module' file compile it to byte code (if needed run the module' code to build the objects it defines to better understand module importswe'll explore these steps in turn bear in mind that all three of these steps are carried out only the first time module is imported during program' executionlater imports of the same module in program run bypass all of these steps and simply fetch the already loaded module object in memory technicallypython does this by storing loaded modules in table named sys mod ules and checking there at the start of an import operation if the module is not presenta three-step process begins find it firstpython must locate the module file referenced by an import statement notice that the import statement in the prior section' example names the file without py extension and without its directory pathit just says import binstead of something like import :\dir \ py path and extension details are omitted on purposeinsteadpython uses standard module search path and known file types to locate the module file corresponding to an import statement because this is the main part of the import operation that programmers must know aboutwe'll return to this topic in moment it' syntactically illegal to include path and extension details in standard import howeverpackage importswhich we'll discuss in allow import statements to include part of the directory path leading to file as set of period-separated names package importsthoughstill rely on the normal module search path to locate the leftmost directory in package path ( they are relative to directory in the search paththey also cannot make use of any platform-specific directory syntax in the import statementssuch syntax only works on the search path alsonote that module file search path issues are not as relevant when you run frozen executables (discussed in )which typically embed byte code in the binary image modulesthe big picture |
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 version number to decide how to proceed the former uses file "timestamps,and the latter uses either "magicnumber embedded in the byte code or filenamedepending on the python release being used this step chooses an action as followscompile if the byte code file is older than the source file ( if you've changed the sourceor was created by different python versionpython automatically regenerates the byte code when the program is run as discussed aheadthis model is modified somewhat in python and later-byte code files are segregated in __pycache__ subdirectory and named with their python version to avoid contention and recompiles when multiple pythons are installed this obviates the need to check version numbers in the byte codebut the timestamp check is still used to detect changes in the source don' compile ifon the other handpython finds pyc byte code file that is not older than the corresponding py source file and was created by the same python versionit skips the source-to-byte-code compile step in additionif python finds only byte code file on the search path and no sourceit simply loads the byte code directlythis means you can ship program as just byte code files and avoid sending source in other wordsthe compile step is bypassed if possible to speed program startup notice that compilation happens when file is being imported because of thisyou will not usually see pyc byte code file for the top-level file of your programunless it is also imported elsewhere--only imported files leave behind pyc files on your machine the byte code of top-level files is used internally and discardedbyte code of imported files is saved in files to speed future imports top-level files are often designed to be executed directly and not imported at all laterwe'll see that it is possible to design file that serves both as the top-level code of program and as module of tools to be imported such file may be both executed and importedand thus does generate pyc to learn how this workswatch for the discussion of the special __name__ attribute and __main__ in run it the final step of an import operation executes the byte code of the module all statements in the file are run in turnfrom top to bottomand any assignments made to names during this step generate attributes of the resulting module object this is how how imports work |
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 import time for exampletop-level print statements in module show output when the file is imported function def statements simply define objects for later use as you can seeimport operations involve quite bit of work--they search for filespossibly run compilerand run python code because of thisany given module is imported only once per process by default future imports skip all three import steps and reuse the already loaded module in memory if you need to import file again after it has already been loaded (for exampleto support dynamic end-user customizations)you have to force the issue with an imp reload call-- tool we'll meet in the next byte code files__pycache__ in python as mentioned brieflythe way that python stores files to retain the byte code that results from compiling your source has changed in python and later first of allif python cannot write file to save this on your computer for any reasonyour program still runs fine--python simply creates and uses the byte code in memory and discards it on exit to speed startupsthoughit will try to save byte code in file in order to skip the compile step next time around the way it does this varies per python versionin python and earlier (including all of python xbyte code is stored in files in the same directory as the corresponding source filesnormally with the filename extension pyc ( module pycbyte code files are also stamped internally with the version of python that created them (known as "magicfield to developersso python knows to recompile when this differs in the version of python running your program for instanceif you upgrade to new python whose byte code differsall your byte code files will be recompiled automatically due to version number mismatcheven if you haven' changed your source code in python and later byte code is instead stored in files in subdirectory named __pycache__which python creates if neededand which is located in the directory containing the corresponding source files this helps avoid clutter in your source directories by segregating the byte code files in their own directory in additionalthough byte code as described earlierpython keeps already imported modules in the built-in sys modules dictionary so it can keep track of what' been loaded in factif you want to see which modules are loadedyou can import sys and print list(sys modules keys()there' more on other uses for this internal table in modulesthe big picture |
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 anotherand doesn' require recompiles technicallybyte code filenames also include the name of the python that created themso cpythonjythonand other implementations mentioned in the preface and can coexist on the same machine without stepping on each other' work (once they support this modelin both modelspython always recreates the byte code file if you've changed the source code file since the last compilebut version differences are handled differently--by magic numbers and replacement prior to and by filenames that allow for multiple copies in and later byte code file models in action the following is quick example of these two models in action under and 've omitted much of the text displayed by the dir directory listing on windows here to save spaceand the script used here isn' listed because it is not relevant to this discussion (it' from and simply prints two valuesprior to byte code files show up alongside their source files after being created by import operationsc:\code\py xdir : am script py :\code\py xc:\python \python import script hello world ^ :\code\py xdir : am : am script py script pyc howeverin and later byte code files are saved in the __pycache__ subdirectory and include versions and python implementation details in their names to avoid clutter and contention among the pythons on your computerc:\code\py xcd \py :\code\py xdir : am script py :\code\py xc:\python \python import script hello world ^ byte code files__pycache__ in python |
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 implementation has its own byte code filesready to be loaded on the next program run (earlier pythons will happily continue using their scheme on the same machine) :\code\py xc:\python \python import script hello world ^ :\code\py xdir __pycache__ : pm : am script cpython- pyc script cpython- pyc python ' newer byte code file model is probably superioras it avoids recompiles when there is more than one python on your machine-- common case in today' mixed / world on the other handit is not without potential incompatibilities in programs that rely on the prior file and directory structure this may be compatibility issue in some tools programsfor instancethough most well-behaved tools should work as before see python ' "what' new?document for details on potential impacts also keep in mind that this process is completely automatic--it' side effect of running programs--and most programmers probably won' care about or even notice the differenceapart from faster startups due to fewer recompiles the module search path as mentioned earlierthe part of the import procedure that most programmers will need to care about is usually the first--locating the file to be imported (the "find itpartbecause you may need to tell python where to look to find files to importyou need to know how to tap into its search path in order to extend it in many casesyou can rely on the automatic nature of the module import search path and won' need to configure this path at all if you want to be able to import userdefined files across directory boundariesthoughyou will need to know how the search path works in order to customize it roughlypython' module search path is composed of the concatenation of these major componentssome of which are preset for you and some of which you can tailor to tell python where to look modulesthe big picture |
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 third elements of the search path are defined automatically because python searches the concatenation of these components from first to lastthoughthe second and fourth elements can be used to extend the path to include your own source code directories here is how python uses each of these path componentshome directory (automaticpython first looks for the imported file in the home directory the meaning of this entry depends on how you are running the code when you're running programthis entry is the directory containing your program' top-level script file when you're working interactivelythis entry is the directory in which you are working ( the current working directorybecause this directory is always searched firstif program is located entirely in single directoryall of its imports will work automatically with no path configuration required on the other handbecause this directory is searched firstits files will also override modules of the same name in directories elsewhere on the pathbe careful not to accidentally hide library modules this way if you need them in your programor use package tools we'll meet later that can partially sidestep this issue pythonpath directories (configurablenextpython searches all directories listed in your pythonpath environment variable settingfrom left to right (assuming you have set this at allit' not preset for youin briefpythonpath is simply list of user-defined and platform-specific names of directories that contain python code files you can add all the directories from which you wish to be able to importand python will extend the module search path to include all the directories your pythonpath lists because python searches the home directory firstthis setting is only important when importing files across directory boundaries--that isif you need to import file that is stored in different directory from the file that imports it you'll probably want to set your pythonpath variable once you start writing substantial programsbut when you're first starting outas long as you save all your module files in the directory in which you're working ( the home directorylike the :\code used in this bookyour imports will work without you needing to worry about this setting at all the module search path |
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 allows users to add directories to the module search path by simply listing themone per linein text file whose name ends with pth suffix (for "path"these path configuration files are somewhat advanced installation-related featurewe won' cover them fully herebut they provide an alternative to pythonpath settings in shorttext files of directory names dropped in an appropriate directory can serve roughly the same role as the pythonpath environment variable setting for instanceif you're running windows and python file named myconfig pth may be placed at the top level of the python install directory ( :\python or in the sitepackages subdirectory of the standard library there ( :\python \lib\site-packagesto extend the module search path on unix-like systemsthis file might be located in usr/local/lib/python /site-packages or /usr/local/lib/site-python instead when such file is presentpython will add the directories listed on each line of the filefrom first to lastnear the end of the module search path list--currentlyafter pythonpath and standard librariesbut before the site-packages directory where third-party extensions are often installed in factpython will collect the directory names in all the pth path files it finds and will filter out any duplicates and nonexistent directories because they are files rather than shell settingspath files can apply to all users of an installationinstead of just one user or shell moreoverfor some users and applicationstext files may be simpler to code than environment settings this feature is more sophisticated than 've described here for more detailsconsult the python library manualand especially its documentation for the standard library module site--this module allows the locations of python libraries and path files to be configuredand its documentation describes the expected locations of path files in general recommend that beginners use pythonpath or perhaps single pth fileand then only if you must import across directories path files are used more often by third-party librarieswhich commonly install path file in python' site-packagesdescribed next the lib\site-packages directory of third-party extensions (automaticfinallypython automatically adds the site-packages subdirectory of its standard library to the module search path by conventionthis is the place that most thirdparty extensions are installedoften automatically by the distutils utility described in an upcoming sidebar because their install directory is always part of the module search pathclients can import the modules of such extensions without any path settings modulesthe big picture |
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 to set pythonpath to list of directories separated by semicolonslike thisc:\pycode\utilities; :\pycode\package or you might instead create text file called :\python \pydirs pthwhich looks like thisc:\pycode\utilities :\pycode\package these settings are analogous on other platformsbut the details can vary too widely for us to cover in this see appendix for pointers on extending your module search path with pythonpath or pth files on various platforms search path variations this description of the module search path is accuratebut genericthe exact configuration of the search path is prone to changing across platformspython releasesand even python implementations depending on your platformadditional directories may automatically be added to the module search path as well for instancesome pythons may add an entry for the current working directory--the directory from which you launched your program--in the search path before the pythonpath directories when you're launching from command linethe current working directory may not be the same as the home directory of your top-level file ( the directory where your program file resides)which is always added because the current working directory can vary each time your program runsyou normally shouldn' depend on its value for import purposes see for more on launching programs from command lines to see how your python configures the module search path on your platformyou can always inspect sys path--the topic of the next section the sys path list if you want to see how the module search path is truly configured on your machineyou can always inspect the path as python knows it by printing the built-in sys path also watch for ' discussion of the new relative import syntax and search rules in python xthey modify the search path for from statements in files inside packages when characters are used ( from import stringby defaulta package' own directory is not automatically searched by imports in python xunless such relative imports are used by files in the package itself the module search path |
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 string to designate the current working directory)any pythonpath directoriesthe contents of any pth file paths you've createdand all the standard library directories the result is list of directory name strings that python searches on each import of new file python exposes this list for two good reasons firstit provides way to verify the search path settings you've made--if you don' see your settings somewhere in this listyou need to recheck your work for examplehere is what my module search path looks like on windows under python with my pythonpath set to :\code and \python \mypath pth path file that lists :\users\mark the empty string at the front means current directoryand my two settings are merged inthe rest are standard library directories and files and the site-packages home for third-party extensionsimport sys sys path [''' :\\code'' :\\windows\\system \\python zip'' :\\python \\dlls'' :\\python \\lib'' :\\python '' :\\users\\mark'' :\\python \\lib\\site-packages'secondif you know what you're doingthis list provides way for scripts to tailor their search paths manually as you'll see by example later in this part of the bookby modifying the sys path listyou can modify the search path for all future imports made in program' run such changes last only for the duration of the scripthoweverpythonpath and pth files offer more permanent ways to modify the path--the first per userand the second per installation on the other handsome programs really do need to change sys path scripts that run on web serversfor exampleoften run as the user "nobodyto limit machine access because such scripts cannot usually depend on "nobodyto have set pythonpath in any particular waythey often set sys path manually to include required source directoriesprior to running any import statements sys path append or sys path insert will often sufficethough will endure for single program run only module file selection keep in mind that filename extensions ( pyare omitted from import statements intentionally python chooses the first file it can find on the search path that matches the imported name in factimports are the point of interface to host of external components--source codemultiple flavors of byte codecompiled extensionsand more python automatically selects any type that matches module' name modulesthe big picture |
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 linked when imported ( so on linuxor dll or pyd on cygwin and windowsa compiled built-in module coded in and statically linked into python zip file component that is automatically extracted when imported an in-memory imagefor frozen executables java classin the jython version of python net componentin the ironpython version of python extensionsjythonand package imports all extend imports beyond simple files to importersthoughdifferences in the loaded file type are completely irrelevantboth when importing and when fetching module attributes saying import gets whatever module isaccording to your module search pathand attr fetches an item in the modulebe it python variable or linked-in function some standard modules we will use in this book are actually coded in cnot pythonbecause they look just like python-coded module filestheir clients don' have to care selection priorities if you have both py and so in different directoriespython will always load the one found in the first (leftmostdirectory of your module search path during the leftto-right search of sys path but what happens if it finds both py and so in the same directoryin this casepython follows standard picking orderthough this order is not guaranteed to stay the same over time or across implementations in generalyou should not depend on which type of file python will choose within given directory-make your module names distinctor configure your module search path to make your module selection preferences explicit import hooks and zip files normallyimports work as described in this section--they find and load files on your machine howeverit is possible to redefine much of what an import operation does in pythonusing what are known as import hooks these hooks can be used to make imports do various useful thingssuch as loading files from archivesperforming decryptionand so on the module search path |
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 __import__ functionthe customizable tool that import statements actually run also see python ' "what' new?document for updates on this front that we'll mostly omit here for space in shortin this version and laterthe __import__ function is now implemented by impor tlib __import__in part to unify and more clearly expose its implementation the latter of these calls is also wrapped by importlib import_module- tool thatper python' current manualsis generally preferred over __import__ for direct calls to import by name stringa technique discussed in both calls still work todaythough the __import__ function supports customizing imports by replacement in the built-in scope (see )and other techniques support similar roles see the python library manuals for more details optimized byte code files finallypython also supports the notion of pyo optimized byte code filescreated and run with the - python command-line flagand automatically generated by some install tools because these run only slightly faster than normal pyc files (typically percent faster)howeverthey are infrequently used the pypy system (see and )for exampleprovides more substantial speedups see appendix and for more on pyo files third-party softwaredistutils this description of module search path settings is targeted mainly at userdefined source code that you write on your own third-party extensions for python typically use the distutils tools in the standard library to automatically install themselvesso no path configuration is required to use their code systems that use distutils generally come with setup py scriptwhich is run to install themthis script imports and uses distutils modules to place such systems in directory that is automatically part of the module search path (usually in the lib\site-packages subdirectory of the python install treewherever that resides on the target machinefor more details on distributing and installing with distutilssee the python standard manual setits use is beyond the scope of this book (for instanceit also provides ways to automatically compile -coded extensions on the target machinealso check out the third-party open source eggs systemwhich adds dependency checking for installed python software modulesthe big picture |
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 modulesattributesand imports and explored the operation of import statements we learned that imports find the designated file on the module search pathcompile it to byte codeand execute all of its statements to generate its contents we also learned how to configure the search path to be able to import from directories other than the home directory and the standard library directoriesprimarily with pythonpath settings as this demonstratedthe import operation and modules are at the heart of program architecture in python larger programs are divided into multiple fileswhich are linked together at runtime by imports imports in turn use the module search path to locate filesand modules define attributes for external use of coursethe whole point of imports and modules is to provide structure to your programwhich divides its logic into self-contained software components code in one module is isolated from code in anotherin factno file can ever see the names defined in anotherunless explicit import statements are run because of thismodules minimize name collisions between different parts of your program you'll see what this all means in terms of actual statements and code in the next before we move onthoughlet' run through the quiz test your knowledgequiz how does module source code file become module object why might you have to set your pythonpath environment variable name the five major components of the module import search path name four file types that python might load in response to an import operation what is namespaceand what does module' namespace containtest your knowledgeanswers module' source code file automatically becomes module object when that module is imported technicallythe module' source code is run during the imtest your knowledgeanswers |
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 the module import search path are the top-level script' home directory (the directory containing it)all directories listed in the pythonpath environment variablethe standard library directoriesall directories listed in pth path files located in standard placesand the site-packages root directory for third-party extension installs of theseprogrammers can customize pythonpath and pth files python might load source code pyfilea byte code pyc or pyofilea extension module ( so file on linux or dll or pyd file on windows)or directory of the same name for package imports imports may also load more exotic things such as zip file componentsjava classes under the jython version of pythonnet components under ironpythonand statically linked extensions that have no files present at all in factwith import hooksimports can load arbitrary items namespace is self-contained package of variableswhich are known as the attributes of the namespace object module' namespace contains all the names assigned by code at the top level of the module file ( not nested in def or class statementstechnicallya module' global scope morphs into the module object' attributes namespace module' namespace may also be altered by assignments from other files that import itthough this is generally frowned upon (see for more on the downsides of cross-file changes modulesthe big picture |
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 python' modules that we haven' yet metsuch as nestingreloadsscopesand more python modules are easy to createthey're just files of python program code created with text editor you don' need to write special syntax to tell python you're making modulealmost any text file will do because python handles all the details of finding and loading modulesmodules are also easy to useclients simply import moduleor specific names module definesand use the objects they reference module creation to define modulesimply use your text editor to type some python code into text fileand save it with pyextensionany such file is automatically considered python module all the names assigned at the top level of the module become its attributes (names associated with the module objectand are exported for clients to use --they morph from variable to module object attribute automatically for instanceif you type the following def into file called module py and import ityou create module object with one attribute--the name printerwhich happens to be reference to function objectdef printer( )print(xmodule attribute module filenames before we go oni should say few more words about module filenames you can call modules just about anything you likebut module filenames should end in py suffix if you plan to import them the py is technically optional for top-level files that will |
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 try to run import ifyou'll get syntax error in factboth the names of module files and the names of directories used in package imports (discussed in the next must conform to the rules for variable names presented in they mayfor instancecontain only lettersdigitsand underscores package directories also cannot contain platform-specific syntax such as spaces in their names when module is importedpython maps the internal module name to an external filename by adding directory path from the module search path to the frontand py or other extension at the end for instancea module named ultimately maps to some external file \ that contains the module' code other kinds of modules as mentioned in the preceding it is also possible to create python module by writing code in an external language such as cc++and others ( javain the jython implementation of the languagesuch modules are called extension modulesand they are generally used to wrap up external libraries for use in python scripts when imported by python codeextension modules look and feel the same as modules coded as python source code files--they are accessed with import statementsand they provide functions and objects as module attributes extension modules are beyond the scope of this booksee python' standard manuals or advanced texts such as programming python for more details module usage clients can use the simple module file we just wrote by running an import or from statement both statements findcompileand run module file' codeif it hasn' yet been loaded the chief difference is that import fetches the module as wholeso you must qualify to fetch its namesin contrastfrom fetches (or copiesspecific names out of the module let' see what this means in terms of code all of the following examples wind up calling the printer function defined in the prior section' module py module filebut in different ways module coding basics |
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 import statement simply lists one or more names of modules to loadseparated by commas because it gives name that refers to the whole module objectwe must go through the module name to fetch its attributes ( module printerthe from statement by contrastbecause from copies specific names from one file over to another scopeit allows us to use the copied names directly in the script without going through the module ( printer)from module import printer printer('hello world!'hello worldcopy out variable (one or moreno need to qualify name this form of from allows us to list one or more names to be copied outseparated by commas hereit has the same effect as the prior examplebut because the imported name is copied into the scope where the from statement appearsusing that name in the script requires less typing--we can use it directly instead of naming the enclosing module in factwe mustfrom doesn' assign the name of the module itself as you'll see in more detail laterthe from statement is really just minor extension to the import statement--it imports the module file as usual (running the full three-step procedure of the preceding but adds an extra step that copies one or more names (not objectsout of the file the entire file is loadedbut you're given names for more direct access to its parts the from statement finallythe next example uses special form of fromwhen we use instead of specific nameswe get copies of all names assigned at the top level of the referenced module here againwe can then use the copied name printer in our script without going through the module namefrom module import printer('hello world!'hello worldcopy out _all_ variables technicallyboth import and from statements invoke the same import operationthe from form simply adds an extra step that copies all the names in the module into the importing scope it essentially collapses one module' namespace into anotheragainmodule usage |
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 detail in python xthe from statement form described here can be used only at the top level of module filenot within function python allows it to be used within functionbut issues warning anyhow it' rare to see this statement used inside function in practicewhen presentit makes it impossible for python to detect variables staticallybefore the function runs best practice in all pythons recommends listing all your imports at the top of module fileit' not requiredbut makes them easier to spot imports happen only once one of the most common questions people seem to ask when they start using modules is"why won' my imports keep working?they often report that the first import works finebut later imports during an interactive session (or program runseem to have no effect in factthey're not supposed to this section explains why modules are loaded and run on the first import or fromand only the first this is on purpose--because importing is an expensive operationby default python does it just once per fileper process later import operations simply fetch the already loaded module object initialization code as one consequencebecause top-level code in module file is usually executed only onceyou can use it to initialize variables consider the file simple pyfor exampleprint('hello'spam initialize variable in this examplethe print and statements run the first time the module is importedand the variable spam is initialized at import timepython import simple hello simple spam first importloads and runs file' code assignment makes an attribute second and later imports don' rerun the module' codethey just fetch the already created module object from python' internal modules table thusthe variable spam is not reinitialized module coding basics |
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 defimport and from are executable statementsnot compile-time declarations they may be nested in if teststo select among optionsappear in function defsto be loaded only on calls (subject to the preceding note)be used in try statementsto provide defaultsand so on they are not resolved or run until python reaches them while executing your program in other wordsimported modules and names are not available until their associated import or from statements run changing mutables in modules alsolike defthe import and from are implicit assignmentsimport assigns an entire module object to single name from assigns one or more names to objects of the same names in another module all the things we've already discussed about assignment apply to module accesstoo for instancenames copied with from become references to shared objectsas with function argumentsreassigning copied name has no effect on the module from which it was copiedbut changing shared mutable object through copied name can also change it in the module from which it was imported to illustrateconsider the following filesmall pyx [ when importing with fromwe copy names to the importer' scope that initially share objects referenced by the module' namespython from small import xy [ copy two names out changes local only changes shared mutable in place herex is not shared mutable objectbut is the names in the importer and the importee both reference the same list objectso changing it from one place changes it in the otherimport small small small [ get module name (from doesn'tsmall' is not my but we share changed mutable module usage |
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 from the preceding example that the assignment to in the interactive session changed the name in that scope onlynot the in the file--there is no link from name copied with from back to the file it came from to really change global name in another fileyou must use importpython from small import xy copy two names out changes my only import small small get module name changes in other module this phenomenon was introduced in because changing variables in other modules like this is common source of confusion (and often bad design choice)we'll revisit this technique again later in this part of the book note that the change to [ in the prior session is differentit changes an objectnot nameand the name in both modules references the samechanged object import and from equivalence notice in the prior example that we have to execute an import statement after the from to access the small module name at all from only copies names from one module to anotherit does not assign the module name itself at least conceptuallya from statement like this onefrom module import name name copy these two names out (onlyis equivalent to this statement sequenceimport module name module name name module name del module fetch the module object copy names out by assignment get rid of the module name like all assignmentsthe from statement creates new variables in the importerwhich initially refer to objects of the same names in the imported file only the names are copied outthoughnot the objects they referenceand not the name of the module itself when we use the from form of this statement (from module import *)the equivalence is the samebut all the top-level names in the module are copied over to the importing scope this way module coding basics |
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 of the from statement because the from statement makes the location of variable more implicit and obscure (name is less meaningful to the reader than module name)some python users recommend using import instead of from most of the time ' not sure this advice is warrantedthoughfrom is commonly and widely usedwithout too many dire consequences in practicein realistic programsit' often convenient not to have to type module' name every time you wish to use one of its tools this is especially true for large modules that provide many attributes--the standard library' tkinter gui modulefor example it is true that the from statement has the potential to corrupt namespacesat least in principle--if you use it to import variables that happen to have the same names as existing variables in your scopeyour variables will be silently overwritten this problem doesn' occur with the simple import statement because you must always go through module' name to get to its contents (module attr will not clash with variable named attr in your scopeas long as you understand and expect that this can happen when using fromthoughthis isn' major concern in practiceespecially if you list the imported names explicitly ( from module import xyzon the other handthe from statement has more serious issues when used in conjunction with the reload callas imported names might reference prior versions of objects moreoverthe from module import form really can corrupt namespaces and make names difficult to understandespecially when applied to more than one file--in this casethere is no way to tell which module name came fromshort of searching the external source files in effectthe from form collapses one namespace into anotherand so defeats the namespace partitioning feature of modules we will explore these issues in more detail in the section "module gotchason page (see probably the best real-world advice here is to generally prefer import to from for simple modulesto explicitly list the variables you want in most from statementsand to limit the from form to just one import per file that wayany undefined names can be assumed to live in the module referenced with the from some care is required when using the from statementbut armed with little knowledgemost programmers find it to be convenient way to access modules module usage |
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 programthe from statement will fail--you can have only one assignment to the name in your scopeo py from import func from import func func(this overwrites the one we fetched from calls func onlyan import will work herethoughbecause including the name of the enclosing module makes the two names uniqueo py import mn func( func(get the whole modulesnot their names we can call both names now the module names make them unique this case is unusual enough that you're unlikely to encounter it very often in practice if you dothoughimport allows you to avoid the name collision another way out of this dilemma is using the as extensionwhich we'll cover in but is simple enough to introduce hereo py from import func as mfunc from import func as nfunc mfunc()nfunc(rename uniquely with "ascalls one or the other the as extension works in both import and from as simple renaming tool (it can also be used to give shorter synonym for long module name in import)more on this form in module namespaces modules are probably best understood as simply packages of names-- places to define names you want to make visible to the rest of system technicallymodules usually correspond to filesand python creates module object to contain all the names assigned in module file but in simple termsmodules are just namespaces (places where names are created)and the names that live in module are called its attributes this section expands on the details behind this model module coding basics |
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 at the top level of module file pythe name becomes an attribute of mwhich we can refer to from outside the module as the name also becomes global variable to other code inside pybut we need to consider the notion of module loading and scopes bit more formally to understand whymodule statements run on the first import the first time module is imported anywhere in systempython creates an empty module object and executes the statements in the module file one after anotherfrom the top of the file to the bottom top-level assignments create module attributes during an importstatements at the top level of the file not nested in def or class that assign names ( =defcreate attributes of the module objectassigned names are stored in the module' namespace module namespaces can be accessed via the attribute__dict__ or dir(mmodule namespaces created by imports are dictionariesthey may be accessed through the built-in __dict__ attribute associated with module objects and may be inspected with the dir function the dir function is roughly equivalent to the sorted keys list of an object' __dict__ attributebut it includes inherited names for classesmay not be completeand is prone to changing from release to release modules are single scope (local is globalas we saw in names at the top level of module follow the same reference/assignment rules as names in functionbut the local and global scopes are the same--ormore formallythey follow the legb scope rule we met in but without the and lookup layers cruciallythoughthe module' global scope becomes an attribute dictionary of module object after the module has been loaded unlike function scopeswhere the local namespace exists only while the function runsa module file' scope becomes module object' attribute namespace and lives on after the importproviding source of tools to importers here' demonstration of these ideas suppose we create the following module file in text editor and call it module pyprint('starting to load 'import sys name def func()pass module namespaces |
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 timeimport module starting to load done loading once the module is loadedits scope becomes an attribute namespace in the module object we get back from import we can then access attributes in this namespace by qualifying them with the name of the enclosing modulemodule sys module name module func module klass heresysnamefuncand klass were all assigned while the module' statements were being runso they are attributes after the import we'll talk about classes in part vibut notice the sys attribute--import statements really assign module objects to namesand any type of assignment to name at the top level of file generates module attribute namespace dictionaries__dict__ in factinternallymodule namespaces are stored as dictionary objects these are just normal dictionaries with all the usual methods when needed--for instanceto write tools that list module content generically as we will in --we can access module' namespace dictionary through the module' __dict__ attribute continuing the prior section' example (remember to wrap this in list call in python --it' view object thereand contents may vary outside used here)list(module __dict__ keys()['__loader__''func''klass''__builtins__''__doc__''__file__''__name__''name''__package__''sys''__initializing__''__cached__'the names we assigned in the module file become dictionary keys internallyso some of the names here reflect top-level assignments in our file howeverpython also adds some names in the module' namespace for usfor instance__file__ gives the name module coding basics |
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 filtering with generator instead of list comprehensionand can omit the keys(because dictionaries generate their keys automatically though implicitlythe effect is the same we'll see similar __dict__ dictionaries on class-related objects in part vi too in both casesattribute fetch is similar to dictionary indexingthough only the former kicks off inheritance in classesmodule namemodule __dict__['name'( attribute name qualification speaking of attribute fetchnow that you're becoming more familiar with moduleswe should firm up the notion of name qualification more formally too in pythonyou can access the attributes of any object that has attributes using the qualification ( attribute fetchsyntax object attribute qualification is really an expression that returns the value assigned to an attribute name associated with an object for examplethe expression module sys in the previous example fetches the value assigned to sys in module similarlyif we have built-in list object ll append returns the append method object associated with that list it' important to keep in mind that attribute qualification has nothing to do with the scope rules we studied in it' an independent concept when you use qualification to access namesyou give python an explicit object from which to fetch the specified names the legb scope rule applies only to bareunqualified names--it may be used for the leftmost name in name pathbut later names after dots search specific objects instead here are the rulessimple variables means search for the name in the current scopes (following the legb rule of qualification means find in the current scopesthen search for the attribute in the object (not in scopesqualification paths means look up the name in the object xthen look up in the object module namespaces |
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've learnedit is never possible to access names defined in another module file without first importing that file that isyou never automatically get to see names in another fileregardless of the structure of imports or function calls in your program variable' meaning is always determined by the locations of assignments in your source codeand attributes are always requested of an object explicitly for exampleconsider the following two simple modules the firstmoda pydefines variable global to code in its file onlyalong with function that changes the global in this filex def ()global my xglobal to this file only change this file' cannot see names in other modules the second modulemodb pydefines its own global variable and imports and calls the function in the first modulex my xglobal to this file only import moda moda (print(xmoda xgain access to names in moda sets moda xnot this file' when runmoda changes the in modanot the in modb the global scope for moda is always the file enclosing itregardless of which module it is ultimately called frompython modb py in other wordsimport operations never give upward visibility to code in imported files --an imported file cannot see names in the importing file more formallyfunctions can never see names in other functionsunless they are physically enclosing module code can never see names in other modulesunless they are explicitly imported module coding basics |
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 file that imports itusing attribute qualification paths it is possible to descend into arbitrarily nested modules and access their attributes for exampleconsider the next three files mod py defines single global name and attribute by assignmentx mod py in turn defines its own xthen imports mod and uses qualification to access the imported module' attributex import mod print(xend='print(mod xmy global mod ' mod py also defines its own xthen imports mod and fetches attributes in both the first and second filesx import mod print(xend='print(mod xend='print(mod mod xmy global mod ' nested mod ' reallywhen mod imports mod hereit sets up two-level namespace nesting by using the path of names mod mod xit can descend into mod which is nested in the imported mod the net effect is that mod can see the xs in all three filesand hence has access to all three global scopespython mod py the reversehoweveris not truemod cannot see names in mod and mod cannot see names in mod this example may be easier to grasp if you don' think in terms of namespaces and scopesbut instead focus on the objects involved within mod mod is just name that refers to an object with attributessome of which may refer to other some languages act differently and provide for dynamic scopingwhere scopes really may depend on runtime calls this tends to make code trickierthoughbecause the meaning of variable can differ over time in pythonscopes more simply correspond to the text of your program module namespaces |
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 statements are taken to reflect directory treesnot simple file import chains reloading modules as we've seena module' code is run only once per process by default to force module' code to be reloaded and rerunyou need to ask python to do so explicitly by calling the reload built-in function in this sectionwe'll explore how to use reloads to make your systems more dynamic in nutshellimports (via both import and from statementsload and run module' code only the first time the module is imported in process later imports use the already loaded module object without reloading or rerunning the file' code the reload function forces an already loaded module' code to be reloaded and rerun assignments in the file' new code change the existing module object in place why care about reloading modulesin shortdynamic customizationthe reload function allows parts of program to be changed without stopping the whole program with reloadthe effects of changes in components can be observed immediately reloading doesn' help in every situationbut where it doesit makes for much shorter development cycle for instanceimagine database program that must connect to server on startupbecause program changes or customizations can be tested immediately after reloadsyou need to connect only once while debugging long-running servers can update themselves this waytoo because python is interpreted (more or less)it already gets rid of the compile/link steps you need to go through to get program to runmodules are loaded dynamically when imported by running program reloading offers further performance advantage by allowing you to also change parts of running programs without stopping though beyond this book' scopenote that reload currently only works on modules written in pythoncompiled extension modules coded in language such as can be dynamically loaded at runtimetoobut they can' be reloaded (though most users probably prefer to code customizations in python anyhow! module coding basics |
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 statement reload is passed an existing module objectnot new name reload lives in module in python and must be imported itself because reload expects an objecta module must have been previously imported successfully before you can reload it (if the import was unsuccessful due to syntax or other erroryou may need to repeat it before you can reload the modulefurthermorethe syntax of import statements and reload calls differsas function reloads require parenthesesbut import statements do not abstractlyreloading looks like thisimport module use module attributes from imp import reload reload(moduleuse module attributes initial import nowgo change the module file get reload itself (in xget updated exports the typical usage pattern is that you import modulethen change its source code in text editorand then reload it this can occur when working interactivelybut also in larger programs that reload periodically when you call reloadpython rereads the module file' source code and reruns its toplevel statements perhaps the most important thing to know about reload is that it changes module object in placeit does not delete and re-create the module object because of thatevery reference to an entire module object anywhere in your program is automatically affected by reload here are the detailsreload runs module file' new code in the module' current namespace rerunning module file' code overwrites its existing namespacerather than deleting and re-creating it top-level assignments in the file replace names with new values for instancererunning def statement replaces the prior version of the function in the module' namespace by reassigning the function name reloading modules |
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 module only you must run them on each module you wish to updateunless you use code or tools that apply reloads transitively reload example to demonstratehere' more concrete example of reload in action in the followingwe'll change and reload module file without stopping the interactive python session reloads are used in many other scenariostoo (see the sidebar "why you will caremodule reloadson page )but we'll keep things simple for illustration here firstin the text editor of your choicewrite module file named changer py with the following contentsmessage "first versiondef printer()print(messagethis module creates and exports two names--one bound to stringand another to function nowstart the python interpreterimport the moduleand call the function it exports the function will print the value of the global message variablepython import changer changer printer(first version keeping the interpreter activenow edit the module file in another windowmodify changer py without stopping python notepad changer py change the global message variableas well as the printer function bodymessage "after editingdef printer()print('reloaded:'messagethenreturn to the python window and reload the module to fetch the new code notice in the following interaction that importing the module again has no effectwe get the original messageeven though the file' been changed we have to call reload in order to get the new versionback to the python interpreter import changer changer printer(first version from imp import reload module coding basics no effectuses loaded module |
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 use reloadyou'll probably want to pair it with import instead of fromas the latter isn' updated by reload operations--leaving your names in state that' strange enough to warrant postponing further elaboration until this part' "gotchasat the end of secondreload by itself updates only single modulebut it' straightforward to code function that applies it transitively to related modules--an extension we'll save for case study near the end of why you will caremodule reloads besides allowing you to reload (and hence rerunmodules at the interactive promptmodule reloads are also useful in larger systemsespecially when the cost of restarting the entire application is prohibitive for instancegame servers and systems that must connect to servers over network on startup are prime candidates for dynamic reloads they're also useful in gui work ( widget' callback action can be changed while the gui remains active)and when python is used as an embedded language in or cprogram (the enclosing program can request reload of the python code it runswithout having to stopsee programming python for more on reloading gui callbacks and embedded python code more generallyreloads allow programs to provide highly dynamic interfaces for instancepython is often used as customization language for larger systems--users can customize products by coding bits of python code onsitewithout having to recompile the entire product (or even having its source code at allin such worldsthe python code already adds dynamic flavor by itself to be even more dynamicthoughsuch systems can automatically reload the python customization code periodically at runtime that wayuserschanges are picked up while the system is runningthere is no need to stop and restart each time the python code is modified not all systems require such dynamic approachbut for those that domodule reloads provide an easy-to-use dynamic customization tool summary this delved into the essentials of module coding tools--the import and from statementsand the reload call we learned how the from statement simply adds an extra step that copies names out of file after it has been importedand how reload forces file to be imported again without stopping and restarting python we also surveyed namespace conceptssaw what happens when imports are nestedexplored summary |
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 that is useful in larger systems and allow us to break conflicts between same-named modules before we move onthoughhere' quick quiz on the concepts presented here test your knowledgequiz how do you make module how is the from statement related to the import statement how is the reload function related to imports when must you use import instead of from name three potential pitfalls of the from statement what is the airspeed velocity of an unladen swallowtest your knowledgeanswers to create moduleyou simply write text file containing python statementsevery source code file is automatically moduleand there is no syntax for declaring one import operations load module files into module objects in memory you can also make module by writing code in an external language like or javabut such extension modules are beyond the scope of this book the from statement imports an entire modulelike the import statementbut as an extra step it also copies one or more variables from the imported module into the scope where the from appears this enables you to use the imported names directly (nameinstead of having to go through the module (module name by defaulta module is imported only once per process the reload function forces module to be imported again it is mostly used to pick up new versions of module' source code during developmentand in dynamic customization scenarios you must use import instead of from only when you need to access the same name in two different modulesbecause you'll have to specify the names of the enclosing modulesthe two names will be unique the as extension can render from usable in this context as well the from statement can obscure the meaning of variable (which module it is defined in)can have problems with the reload call (names may reference prior versions of objects)and can corrupt namespaces (it might silently overwrite names module coding basics |
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 can name directory path directory of python code is said to be packageso such imports are known as package imports in effecta package import turns directory on your computer into another python namespacewith attributes corresponding to the subdirectories and module files that the directory contains this is somewhat advanced featurebut the hierarchy it provides turns out to be handy for organizing the files in large system and tends to simplify module search path settings as we'll seepackage imports are also sometimes required to resolve import ambiguities when multiple program files of the same name are installed on single machine because it is relevant to code in packages onlywe'll also introduce python' recent relative imports model and syntax here as we'll seethis model modifies search paths in xand extends the from statement for imports within packages in both and this model can make such intrapackage imports more explicit and succinctbut comes with some tradeoffs that can impact your programs finallyfor readers using python and laterits new namespace package model-which allows packages to span multiple directories and requires no initialization file-is also introduced here this new-style package model is optional and can be used in concert with the original (now known as "regular"package modelbut it upends some of the original model' basic ideas and rules because of thatwe'll explore regular packages here first for all readersand present namespace packages last as an optional topic |
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 to path through the directory hierarchy on your computerleading to the file mod py (or similarthe extension may varythat isthe preceding statements indicate that on your machine there is directory dir which has subdirectory dir which contains module file mod py (or similarfurthermorethese imports imply that dir resides within some container directory dir which is component of the normal python module search path in other wordsthese two import statements imply directory structure that looks something like this (shown with windows backslash separators)dir \dir \dir \mod py or mod pycmod soetc the container directory dir needs to be added to your module search path unless it' the home directory of the top-level fileexactly as if dir were simple module file more formallythe leftmost component in package import path is still relative to directory included in the sys path module search path list we explored in from there downthoughthe import statements in your script explicitly give the directory paths leading to modules in packages packages and search path settings if you use this featurekeep in mind that the directory paths in your import statements can be only variables separated by periods you cannot use any platform-specific path syntax in your import statementssuch as :\dir my documents dir or /dir -these do not work syntactically insteaduse any such platform-specific syntax in your module search path settings to name the container directories for instancein the prior exampledir --the directory name you add to your module search path--can be an arbitrarily long and platform-specific directory path leading up to dir you cannot use an invalid statement like thisimport :\mycode\dir \dir \mod errorillegal syntax but you can add :\mycode to your pythonpath variable or pth fileand say this in your scriptimport dir dir mod module packages |
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 it' the home directory of the top-level filethe directory you're working in interactivelya standard library directoryor the site-packages third-party install root one way or anotherthoughyour module search path must include all the directories containing leftmost components in your code' package import statements package __init__ py files if you choose to use package importsthere is one more constraint you must followat least until python each directory named within the path of package import statement must contain file named __init__ pyor your package imports will fail that isin the example we've been usingboth dir and dir must contain file called __init__ pythe container directory dir does not require such file because it' not listed in the import statement itself more formallyfor directory structure such as thisdir \dir \dir \mod py and an import statement of the formimport dir dir mod the following rules applydir and dir both must contain an __init__ py file dir the containerdoes not require an __init__ py filethis file will simply be ignored if present dir not dir \dir must be listed on the module search path sys path to satisfy the first two of these rulespackage creators must create files of the sort we'll explore here to satisfy the latter of thesedir must be an automatic path component (the homelibrariesor site-packages directories)or be given in pythonpath or pth file settings or manual sys path changes the dot path syntax was chosen partly for platform neutralitybut also because paths in import statements become real nested object paths this syntax also means that you may get odd error messages if you forget to omit the py in your import statements for exampleimport mod py is assumed to be directory path import--it loads mod pythen tries to load mod\py pyand ultimately issues potentially confusing "no module named pyerror message as of python this error message has been improved to say "no module named ' py' is not package package import basics |
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 initialization steps required by the package these files can also be completely emptythoughand sometimes have additional roles--as the next section explains as we'll see near the end of this the requirement of packages to have file named __init__ py has been lifted as of python in that release and laterdirectories of modules with no such file may be imported as single-directory namespace packageswhich work the same but run no initialization-time code file prior to python thoughand in all of python xpackages still require __init__ py files as described aheadin and later these files also provide performance advantage when used package initialization file roles in more detailthe __init__ py file serves as hook for package initialization-time actionsdeclares directory as python packagegenerates module namespace for directoryand implements the behavior of from ( from import *statements when used with directory importspackage initialization the first time python program imports through directoryit automatically runs all the code in the directory' __init__ py file because of thatthese files are natural place to put code to initialize the state required by files in package for instancea package might use its initialization file to create required data filesopen connections to databasesand so on typically__init__ py files are not meant to be useful if executed directlythey are run automatically when package is first accessed module usability declarations package __init__ py files are also partly present to declare that directory is python package in this rolethese files serve to prevent directories with common names from unintentionally hiding true modules that appear later on the module search path without this safeguardpython might pick directory that has nothing to do with your codejust because it appears nested in an earlier directory on the search path as we'll see laterpython ' namespace packages obviate much of module packages |
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 dir ' __init__ py initialization file such files provide namespace for module objects created for directorieswhich would otherwise have no real associated module file from statement behavior as an advanced featureyou can use __all__ lists in __init__ py files to define what is exported when directory is imported with the from statement form in an __init__ py filethe __all__ list is taken to be the list of submodule names that should be automatically imported when from is used on the package (directoryname if __all__ is not setthe from statement does not automatically load submodules nested in the directoryinsteadit loads just names defined by assignments in the directory' __init__ py fileincluding any submodules explicitly imported by code in this file for instancethe statement from submodule import in directory' __init__ py makes the name available in that directory' namespace (we'll see additional roles for __all__ in it serves to declare from exports of simple files as well you can also simply leave these files emptyif their roles are beyond your needs (and franklythey are often empty in practicethey must existthoughfor your directory imports to work at all don' confuse package __init__ py files with the class __init__ constructor methods we'll meet in the next part of the book the former are files of code run when imports first step through package directory in program runwhile the latter are called when an instance is created both have initialization rolesbut they are otherwise very different package import example let' actually code the example we've been talking about to show how initialization files and paths come into play the following three files are coded in directory dir and its subdirectory dir --comments give the pathnames of these filesdir \__init__ py print('dir init' dir \dir \__init__ py print('dir init' package import example |
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' initialization file the first time that directory is traversedas python descends the pathprint statements are included here to trace their executionc:\codepython import dir dir mod dir init dir init in mod py import dir dir mod run in dir ' container directory first imports run init files later imports do not just like module filesan already imported directory may be passed to reload to force reexecution of that single item as shown herereload accepts dotted pathname to reload nested directories and filesfrom imp import reload from needed in only reload(dir dir init reload(dir dir dir init once importedthe path in your import statement becomes nested object path in your script heremod is an object nested in the object dir which in turn is nested in the object dir dir dir dir dir dir mod in facteach directory name in the path becomes variable assigned to module object whose namespace is initialized by all the assignments in that directory' __init__ py file dir refers to the variable assigned in dir \__init__ pymuch as mod refers to the variable assigned in mod pydir dir dir module packages |
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 directlyyou'll get an errordir mod nameerrorname 'dir is not defined mod nameerrorname 'modis not defined it' often more convenientthereforeto use the from statement with packages to avoid retyping the paths at each access perhaps more importantlyif you ever restructure your directory treethe from statement requires just one path update in your codewhereas imports may require many the import as extensiondiscussed formally in the next can also help here by providing shorter synonym for the full pathand renaming tool when the same name appears in multiple modulesc:\codepython from dir dir import mod dir init dir init in mod py mod from dir dir mod import import dir dir mod as mod mod from dir dir mod import as modz modz code path here only don' repeat path use shorter name (see ditto if names clash (see why use package importsif you're new to pythonmake sure that you've mastered simple modules before stepping up to packagesas they are somewhat more advanced feature they do serve useful rolesthoughespecially in larger programsthey make imports more informativeserve as an organizational toolsimplify your module search pathand can resolve ambiguities first of allbecause package imports give some directory information in program filesthey both make it easier to locate your files and serve as an organizational tool without package pathsyou must often resort to consulting the module search path to find files why use package imports |
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 greatly simplify your pythonpath and pth file search path settings in factif you use explicit package imports for all your cross-directory importsand you make those package imports relative to common root directory where all your python code is storedyou really only need single entry on your search paththe common root finallypackage imports serve to resolve ambiguities by making explicit exactly which files you want to import--and resolve conflicts when the same module name appears in more than one place the next section explores this role in more detail tale of three systems the only time package imports are actually required is to resolve ambiguities that may arise when multiple programs with same-named files are installed on single machine this is something of an install issuebut it can also become concern in general practice --especially given the tendency of developers to use simple and similar names for module files let' turn to hypothetical scenario to illustrate suppose that programmer develops python program that contains file called utilities py for common utility codeand top-level file named main py that users launch to start the program all over this programits files say import utilities to load and use the common code when the program is shippedit arrives as single tar or zip file containing all the program' filesand when it is installedit unpacks all its files into single directory named system on the target machinesystem utilities py main py other py common utility functionsclasses launch this to start the program import utilities to load my tools nowsuppose that second programmer develops different program with files also called utilities py and main pyand again uses import utilities throughout the program to load the common code file when this second system is fetched and installed on the same computer as the first systemits files will unpack into new directory called system somewhere on the receiving machine--ensuring that they do not overwrite same-named files from the first systemsystem utilities py main py other py common utilities launch this to run imports utilities module packages |
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 you click on system \main pyall imports will search system first similarlyif you launch system \main pysystem will be searched first instead remembermodule search path settings are only needed to import across directory boundaries howeversuppose that after you've installed these two programs on your machineyou decide that you' like to use some of the code in each of the utilities py files in system of your own it' common utility codeafter alland python code by nature "wantsto be reused in this caseyou' like to be able to say the following from code that you're writing in third directory to load one of the two filesimport utilities utilities func('spam'now the problem starts to materialize to make this work at allyou'll have to set the module search path to include the directories containing the utilities py files but which directory do you put first in the path--system or system the problem is the linear nature of the search path it is always scanned from left to rightso no matter how long you ponder this dilemmayou will always get just one utilities py--from the directory listed first (leftmoston the search path as isyou'll never be able to import it from the other directory at all you could try changing sys path within your script before each import operationbut that' both extra work and highly error prone and changing pythonpath before each python program run is too tediousand won' allow you to use both versions in single file in an event by defaultyou're stuck this is the issue that packages actually fix rather than installing programs in independent directories listed on the module search path individuallyyou can package and install them as subdirectories under common root for instanceyou might organize all the code in this example as an install hierarchy that looks like thisrootsystem __init__ py utilities py main py other py system __init__ py utilities py main py other py system __init__ py myfile py here or elsewhere need __init__ py here only if imported elsewhere your new code here why use package imports |
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 moduleas long as you use an import statement and repeat the full path each time you reference the utility modulesimport system utilities import system utilities system utilities function('spam'system utilities function('eggs'the names of the enclosing directories here make the module references unique note that you have to use import instead of from with packages only if you need to access the same attribute name in two or more paths if the name of the called function here were different in each pathyou could use from statements to avoid repeating the full package path whenever you call one of the functionsas described earlierthe as extension in from can also be used to provide unique synonyms alsonotice in the install hierarchy shown earlier that __init__ py files were added to the system and system directories to make this workbut not to the root directory only directories listed within import statements in your code require these filesas we've seenthey are run automatically the first time the python process imports through package directory technicallyin this case the system directory doesn' have to be under root--just the packages of code from which you will import howeverbecause you never know when your own modules might be useful in other programsyou might as well place them under the common root directory as well to avoid similar name-collision problems in the future finallynotice that both of the two original systemsimports will keep working unchanged because their home directories are searched firstthe addition of the common root on the search path is irrelevant to code in system and system they can keep saying just import utilities and expect to find their own files when run as programs --though not when used as packages in xas the next section explains if you're careful to unpack all your python systems under common root like thispath configuration also becomes simpleyou'll only need to add the common root directory once why you will caremodule packages because packages are standard part of pythonit' common to see larger third-party extensions shipped as sets of package directoriesrather than flat lists of modules the win all windows extensions package for pythonfor instancewas one of the first to jump on the package bandwagon many of its utility modules reside in packages imported with paths for instanceto load client-side com toolsyou use statement like this module packages |
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 organized into package subdirectories in the standard libraryand python groups even more related modules into packages--including tkinter gui toolshttp networking toolsand more the following imports access various standard library tools in ( usage may vary)from email message import message from tkinter filedialog import askopenfilename from http server import cgihttprequesthandler whether you create package directories or notyou will probably import from them eventually package relative imports the coverage of package imports so far has focused mostly on importing package files from outside the package within the package itselfimports of same-package files can use the same full path syntax as imports from outside the package--and as we'll seesometimes should howeverpackage files can also make use of special intrapackage search rules to simplify import statements that israther than listing package import pathsimports within the package can be relative to the package the way this works is version-dependentpython implicitly searches package directories first on importswhile requires explicit relative import syntax in order to import from the package directory this change can enhance code readability by making same-package imports more obviousbut it' also incompatible with and may break some programs if you're starting out in python with version xyour focus in this section will likely be on its new import syntax and model if you've used other python packages in the pastthoughyou'll probably also be interested in how the model differs let' begin our tour with the latter perspective on this topic as we'll learn in this sectionuse of package relative imports can actually limit your filesroles in shortthey can no longer be used as executable program files in both and because of thisnormal package import paths may be better option in many cases stillthis feature has found its way into many python fileand merits review by most python programmers to better understand both its tradeoffs and motivation package relative imports |
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 semantics to skip the package' own directory by default imports check only paths on the sys path search path these are known as absolute imports it extends the syntax of from statements to allow them to explicitly request that imports search the package' directory onlywith leading dots this is known as relative import syntax these changes are fully present in python the new from statement relative syntax is also available in python xbut the default absolute search path change must be enabled as an option there enabling this can break programsbut is available for forward compatibility the impact of this change is that in (and optionally in )you must generally use special from dotted syntax to import modules located in the same package as the importerunless your imports list complete path relative to package root on sys pathor your imports are relative to the always-searched home directory of the program' top-level file (which is usually the current working directoryby defaultthoughyour package directory is not automatically searchedand intrapackage imports made by files in directory used as package will fail without the special from syntax as we'll seein this can affect the way you will structure imports or directories for modules meant for use in both top-level programs and importable packages firstthoughlet' take more detailed look at how this all works relative import basics in both python and xfrom statements can now use leading dots ("to specify that they require modules located within the same package (known as package relative imports)instead of modules located elsewhere on the module import search path (called absolute importsthat isimports with dotsin both python and xyou can use leading dots in from statementsmodule names to indicate that imports should be relative-only to the containing package--such imports will search for modules inside the package directory only and will not look for same-named modules located elsewhere on the import search path (sys paththe net effect is that package modules override outside modules imports without dotsin python xnormal imports in package' code without leading dots currently default to relative-then-absolute search path order--that module packages |
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 located in the same package directory as the file in which this statement appears similarlythis statementfrom spam import name means "from module named spam located in the same package as the file that contains this statementimport the variable name the behavior of statement without the leading dot depends on which version of python you use in xsuch an import will still default to the original relative-thenabsolute search path order ( searching the package' directory first)unless statement of the following form is included at the top of the importing file (as its first executable statement)from __future__ import absolute_import use relative import model in if presentthis statement enables the python absolute-only search path change in xand in when enabledan import without leading dot in the module name always causes python to skip the relative components of the module import search path and look instead in the absolute directories that sys path contains for instancein ' modela statement of the following form will always find string module somewhere on sys pathinstead of module of the same name in the packageimport string skip this package' version by contrastwithout the from __future__ statement in xif there' local string module in the packageit will be imported instead to get the same behavior in xand in when the absolute import change is enabledrun statement of the following form to force relative importfrom import string searches this package only this statement works in both python and today the only difference in the model is that it is required in order to load module that is located in the same package directory as the file in which this appearswhen the file is being used as part of package (and unless full package paths are spelled outnotice that leading dots can be used to force relative imports only with the from statementnot with the import statement in python xthe import modname statement is always absolute-onlyskipping the containing package' directory in xthis statement form still performs relative importssearching the package' directory first from statements without leading dots behave the same as import statements--absolute-only package relative imports |
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 string imports string sibling of mypkg to understand these latter forms betterand to justify all this added complexitywe need to take short detour to explore the rationale behind this change why relative importsbesides making intrapackage imports more explicitthis feature is designed in part to allow scripts to resolve ambiguities that can arise when same-named file appears in multiple places on the module search path consider the following package directorymypkg__init__ py main py string py this defines package named mypkg containing modules named mypkg main and mypkg string nowsuppose that the main module tries to import module named string in python and earlierpython will first look in the mypkg directory to perform relative import it will find and import the string py file located thereassigning it to the name string in the mypkg main module' namespace it could bethoughthat the intent of this import was to load the python standard library' string module instead unfortunatelyin these versions of pythonthere' no straightforward way to ignore mypkg string and look for the standard library' string module located on the module search path moreoverwe cannot resolve this with full package import pathsbecause we cannot depend on any extra package directory structure above the standard library being present on every machine in other wordssimple imports in packages can be both ambiguous and error-prone within packageit' not clear whether an import spam statement refers to module within or outside the package as one consequencea local module or package can hide another hanging directly off of sys pathwhether intentionally or not in practicepython users can avoid reusing the names of standard library modules they need for modules of their own (if you need the standard stringdon' name new module string!but this doesn' help if package accidentally hides standard modulemoreoverpython might add new standard library module in the future that has the same name as module of your own code that relies on relative imports is also module packages |
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 mypkg/main py will always find string module outside the packagevia an absolute import search of sys pathimport string imports string outside package (absolutea from import without leading-dot syntax is considered absolute as wellfrom string import name imports name from string outside package if you really want to import module from your package without giving its full path from the package rootthoughrelative imports are still possible if you use the dot syntax in the from statementfrom import string imports mypkg string here (relativethis form imports the string module relative to the current package only and is the relative equivalent to the prior import example' absolute form (both load module as wholewhen this special relative syntax is usedthe package' directory is the only directory searched we can also copy specific names from module with relative syntaxfrom string import name name imports names from mypkg string this statement again refers to the string module relative to the current package if this code appears in our mypkg main modulefor exampleit will import name and name from mypkg string in effectthe in relative import is taken to stand for the package directory containing the file in which the import appears an additional leading dot performs the relative import starting from the parent of the current package for examplethis statementfrom import spam imports sibling of mypkg will load sibling of mypkg-- the spam module located in the package' own container directorynext to mypkg more generallycode located in some module can use any of these formsfrom import from import imports means bimports means afrom import from import imports means bimports means apackage relative imports |
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 the order of the module search path settingswhile relative import dot syntax does not in factthis form requires that the directory immediately containing mypkg be included in the module search path it probably is if mypkg is the package root (or else the package couldn' be used from the outside in the first place!)but this directory may be nested in much larger package tree if mypkg isn' the package' rootabsolute import statements must list all the directories below the package' root entry in sys path when naming packages explicitly like thisfrom system section mypkg import string system container on sys path only in large or deep packagesthat could be substantially more work to code than dotfrom import string relative import syntax with this latter formthe containing package is searched automaticallyregardless of the search path settingssearch path orderand directory nesting on the other handthe full-path absolute form will work regardless of how the file is being used--as part of program or package--as we'll explore ahead the scope of relative imports relative imports can seem bit perplexing on first encounterbut it helps if you remember few key points about themrelative imports apply to imports within packages only keep in mind that this feature' module search path change applies only to import statements within module files used as part of package--that isintrapackage imports normal imports in files not used as part of package still work exactly as described earlierautomatically searching the directory containing the top-level script first relative imports apply to the from statement only also remember that this feature' new syntax applies only to from statementsnot import statements it' detected by the fact that the module name in from begins with one or more dots (periodsmodule names that contain embedded dots but don' have leading dot are package importsnot relative imports in other wordspackage relative imports in really boil down to just the removal of ' inclusive search path behavior for packagesalong with the addition of special from syntax to explicitly request that relative package-only behavior be used if you coded your package imports in the past so that they did not depend upon ' implicit relative lookup ( by always spelling out full paths from package root)this change module packages |
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 to right this list is constructed from both system defaults and user-configurable settings described in packages are simply directories of python modules with special __init__ py filewhich enables directory path syntax in imports in an import of cfor examplethe directory named is located relative to the normal module import search of sys pathb is another package subdirectory within aand is module or other importable item within within package' filesnormal import and from statements use the same sys path search rule as imports elsewhere imports in packages using from statements and leading dotshoweverare relative to the packagethat isonly the package directory is checkedand the normal sys path lookup is not used in from import afor examplethe module search is restricted to the directory containing the file in which this statement appears python works the sameexcept that normal imports without dots also automatically search the package directory first before proceeding on to sys path in sumpython imports select between relative (in the containing directoryand absolute (in directory on sys pathresolutions as followsdotted importsfrom import are relative-only in both and nondotted importsimport mfrom import are relative-then-absolute in xand absolute-only in as we'll see laterpython adds another flavor to modules--namespace packages-which is largely disjointed from the package-relative story we're covering here this newer model supports package-relative imports tooand is simply different way to construct package it augments the import search procedure to allow package content to be spread across multiple simple directories as last-resort resolution thereafterthoughthe composite package behaves the same in terms of relative import rules relative imports in action but enough theorylet' run some simple code to demonstrate the concepts behind relative imports package relative imports |
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 on the module search path is the current working directory (cwd)code\string py print('string :\codec:\python \python import string stringstringstringstringstringstringstringstring string in other wordsnormal imports are still relative to the "homedirectory (the top-level script' containeror the directory you're working inin factpackage relative import syntax is not even allowed in code that is not in file being used as part of packagefrom import string systemerrorparent module 'not loadedcannot perform relative import in this sectioncode entered at the interactive prompt behaves the same as it would if run in top-level scriptbecause the first entry on sys path is either the interactive working directory or the directory containing the top-level file the only difference is that the start of sys path is an absolute directorynot an empty stringcode\main py import string print(stringc:\codec:\python \python main py stringstringstringstringstringstringstringstring same code but in file equivalent results in similarlya from import string in this nonpackage file fails the same as it does at the interactive prompt--programs and packages are different file usage modes imports within packages nowlet' get rid of the local string module we coded in the cwd and build package directory there with two modulesincluding the required but empty test\pkg \__init__ py file package roots in this section are located in the cwd added automatically to sys pathso we don' need to set pythonpath 'll also largely omit empty module packages |
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 the second with normal import statement because this is taken to be relative in but absolute in xit fails in the latter that is searches the containing package firstbut does not this is the incompatible behavior you have to be aware of in xc:\codec:\python \python import pkg spam :\codec:\python \python import pkg spam importerrorno module named 'eggsto make this work in both and xchange the first file to use the special relative import syntaxso that its import searches the package directory in toocode\pkg\spam py from import eggs print(eggs <=use package relative import in or code\pkg\eggs py import string print(stringc:\codec:\python \python import pkg spam :\codec:\python \python import pkg spam package relative imports |
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 although you can skip the package directory with an absolute import in xyou still can' skip the home directory of the program that imports the packagecode\string py print('string code\pkg\spam py from import eggs print(eggs xcode\pkg\eggs py import string print(string<=gets string in cwdnot python libc:\codec:\python \python same result in import pkg spam stringstringstringstringstringstringstringstring selecting modules with relative and absolute imports to show how this applies to imports of standard library modulesreset the package again get rid of the local string moduleand define new one inside the package itselfc:\codedel stringdel __pycache__\stringfor bytecode in code\pkg\spam py import string print(string<=relative in xabsolute in code\pkg\string py print('ni nowwhich version of the string module you get depends on which python you use as before interprets the import in the first file as absolute and skips the packagebut does not--another example of the incompatible behavior in xc:\codec:\python \python import pkg spam :\codec:\python \python import pkg spam nininininininini module packages |
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 nininininininini :\codec:\python \python import pkg spam nininininininini relative imports search packages only it' also important to note that relative import syntax is really binding declarationnot just preference if we delete the string py file and any associated byte code in this example nowthe relative import in spam py fails in both and xinstead of falling back on the standard library (or any otherversion of this modulecode\pkg\spam py from import string <=fails in both and if no string py herec:\codedel pkg\stringc:\codec:\python \python import pkg spam importerrorcannot import name string :\codec:\python \python import pkg spam importerrorcannot import name string modules referenced by relative imports must exist in the package directory imports are still relative to the cwdagain although absolute imports let you skip package modules this waythey still rely on other components of sys path for one last testlet' define two string modules of our own in the followingthere is one module by that name in the cwdone in the packageand another in the standard librarycode\string py print('string code\pkg\spam py package relative imports |
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 varies per version again interprets this as relative to the package firstbut makes it "absolute,which in this case really just means it skips the package and loads the version relative to the cwd --not the version in the standard librarycode\string py print('string code\pkg\spam py import string print(string<=relative in "absolutein xcwdcode\pkg\string py print('ni :\codec:\python \python import pkg spam stringstringstringstringstringstringstringstring :\codec:\python \python import pkg spam nininininininini as you can seealthough packages can explicitly request modules within their own directories with dotstheir "absoluteimports are otherwise still relative to the rest of the normal module search path in this casea file in the program using the package hides the standard library module the package may want the change in simply allows package code to select files either inside or outside the package ( relatively or absolutelybecause import resolution can depend on an enclosing context that may not be foreseenthoughabsolute imports in are not guarantee of finding module in the standard library experiment with these examples on your own for more insight in practicethis is not usually as ad hoc as it might seemyou can generally structure your importssearch pathsand module names to work the way you wish during development you should keep in mindthoughthat imports in larger systems may depend upon context of useand the module import protocol is part of successful library' design module packages |
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-relative import dot syntax in both python and this issue may seem obscurebut will likely become important fairly soon after you start coding packages of your own as we've seenpython ' relative import syntax and absolute search rule default make intrapackage imports explicit and thus easier to notice and maintainand allow explicit choice in some name conflict scenarios howeverthere are also two major ramifications of this model that you should be aware ofin both python and xuse of package-relative import statements implicitly binds file to package directory and roleand precludes it from being used in other ways in python xthe new relative search rule change means that file can no longer serve as both script and package module as easily as it could in these constraint' causes are bit subtlebut because the following are simultaneously truepython and do not allow from relative syntax to be used unless the importer is being used as part of package ( is being imported from somewhere elsepython does not search package module' own directory for importsunless from relative syntax is used (or the module is in the current working directory or main script' home directoryuse of relative imports prevents you from creating directories that serve as both executable programs and externally importable packages in and moreoversome files can no longer serve as both script and package module in as they could in in terms of import statementsthe rules pan out as follows--the first is for package mode only in both pythonsand the second is for program mode only in xfrom import mod import mod not allowed in nonpackage mode in both and does not search file' own directory in package mode in the net effect is that for files to be used in either or xyou may need to choose single usage mode--package (with relative importsor program (with simple imports)and isolate true package module files in subdirectory apart from top-level script files alternativelyyou can attempt manual sys path changes ( generally brittle and errorprone task)or always use full package paths in absolute imports instead of either package-relative syntax or simple importsand assume the package root is on the module search pathfrom system section mypkg import mod works in both program and package mode package relative imports |
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 resolve intrapackage imports when used as package this won' quite work in xthough--in package modeplain imports do not load modules in the same directory anymoreunless that directory also happens to be the same as the main file' container or the current working directory (and hencebe on sys pathhere' what this looks like in actionstripped to bare minimum of code (for brevity in this section again omit __init__ py package directory files required prior to python and for variety use the windows launcher covered in appendix )code\pkg\main py import spam code\pkg\spam py import eggs <=works if in home of main script file code\pkg\eggs py print('eggs but won' load this file when used as pkg in xc:\codepython pkg\main py eggseggseggseggs :\codepython pkg\spam py eggseggseggseggs ok as programin both and :\codepy - import pkg spam eggseggseggseggs ok as package in xrelative-then-absolute xplain imports search package directory first :\codepy - but fails to find file hereabsolute only import pkg spam xplain imports search only cwd plus sys path importerrorno module named 'eggsyour next step might be to add the required relative import syntax for usebut it won' help here the following retains the single directory for both main top-level script and package modulesand adds the required dots--in both and this now works when the directory is imported as packagebut fails when it is used as program directory (including attempts to run module as script directly)code\pkg\main py import spam code\pkg\spam py from import eggs code\pkg\eggs py module packages <=not package if main file here (even if me) |
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 files used only by the program in subdirectory--this wayyour intrapackage imports still work in all pythonsyou can use the top directory as standalone programand the nested directory still serves as package for use from other programscode\pkg\main py import sub spam <=works if move modules to pkg below main file code\pkg\sub\spam py from import eggs package relative works nowin subdirectory code\pkg\sub\eggs py print('eggs :\codepython pkg\main py eggseggseggseggs from main scriptsame result in and :\codepython import pkg sub spam eggseggseggseggs from elsewheresame result in and the potential downside of this scheme is that you won' be able to run package modules directly to test them with embedded self-test codethough tests can be coded separately in their parent directory insteadc:\codepy - pkg\sub\spam py but individual modules can' be run to test systemerrorcannot perform relative import fix full path absolute import alternativelyfull path package import syntax would address this case too--it requires the directory above the package root to be in your paththough this is probably not an extra requirement for realistic software package most python packages will either require this settingor arrange for it to be handled automatically with install tools (such as distutilswhich may store package' code in directory on the default module search path such as the site-packages rootsee for more details)code\pkg\main py import spam package relative imports |
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 imports like these also allow you to run your modules standalone to testc:\codepython pkg\spam py eggseggseggseggs individual modules are runnable too in and exampleapplication to module self-test code (previewto summarizehere' another typical example of the issue and its full path resolution this uses common technique we'll expand on in the next but the idea is simple enough to include as preview here (though you may want to review this again later--the coverage makes more sense hereconsider the following two modules in package directorythe second of which includes self-test code in shorta module' __name__ attribute is the string "__main__when it is being run as top-level scriptbut not when it is being importedwhich allows it to be used as both module and scriptcode\dualpkg\ py def somefunc()print(' somefunc'code\dualpkg\ py import here replace me with real import statement def somefunc() somefunc(print(' somefunc'if __name__ ='__main__'somefunc(self-test or top-level script usage mode code the second of these needs to import the first where the import here placeholder appears replacing this line with relative import statement works when the file is used as packagebut is not allowed in nonpackage mode by either or (results and error messages are omitted here for spacesee the file dualpkg\results txt in the book' examples for the full listing)code\dualpkg\ py from import module packages |
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 dualpkg :\codepy - import dualpkg :\codepy - dualpkg\ py :\codepy - dualpkg\ py failsok ok ok and finallyusing full package paths works again in both usage modes and pythonsas long as the package' root is on the module search path (as it must be to be used elsewhere)code\dualpkg\ py import dualpkg as :\codepy - import dualpkg :\codepy - import dualpkg :\codepy - dualpkg\ py :\codepy - dualpkg\ py andset pythonpath= :\code ok ok ok ok in sumunless you're willing and able to isolate your modules in subdirectories below scriptsfull package path imports are probably preferable to package-relative imports --though they're more typingthey handle all casesand they work the same in and there may be additional workarounds that involve extra tasks ( manually setting sys path in your code)but we'll skip them here because they are more obscure and rely on import semanticswhich is error-pronefull package imports rely only on the basic package mechanism naturallythe extent to which this may impact your modules can vary per packageabsolute imports may also require changes when directories are reorganizedand relative imports may become invalid if local module is relocated package relative imports |
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 is version-neutraland is more than year away in any event that isyou can wait for change to change that limited functionalityor simply use triedand-true full package paths python namespace packages now that you've learned all about package and package-relative importsi need to explain that there' new option that modifies some of the ideas we just covered at least abstractlyas of release python has four import models from original to newestbasic module importsimport modfrom mod import attr the original modelimports of files and their contentsrelative to the sys path module search path package importsimport dir dir modfrom dir mod import attr imports that give directory path extensions relative to the sys path module search pathwhere each package is contained in single directory and has an initialization filein python and package-relative importsfrom import mod (relative)import mod (absolutethe model used for intrapackage imports of the prior sectionwith its relative or absolute lookup schemes for dotted and nondotted importsavailable but differing in python and namespace packagesimport splitdir mod the new namespace package model that we'll survey herewhich allows packages to span multiple directoriesand requires no initialization fileintroduced in python the first two of these are self-containedbut the third tightens up the search order and extends syntax for intrapackage importsand the fourth upends some of the core notions and requirements of the prior package model in factpython (and laternow has two flavors of packagesthe original modelnow known as regular packages the alternative modelknown as namespace packages this is similar in spirit to the "classicand "new styleclass model dichotomy we'll meet in the next part of this bookthough the new is more an addition to the old here the original and new package models are not mutually exclusiveand can be used module packages |
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 feature' pep document in shortthoughthey resolve potential for collision of multiple __init__ py files when package parts are mergedby removing this file completely moreoverby providing standard support for packages that can be split across multiple directories and located in multiple sys path entriesnamespace packages both enhance install flexibility and provide common mechanism to replace the multiple incompatible solutions that have arisen to address this goal though too early to judge their uptakeaverage python users may find namespace packages to be useful and alternative extension to the regular package model--one that does not require initialization filesand allows any directory of code to be used as an importable package to see whylet' move on to the details namespace package semantics namespace package is not fundamentally different from regular packageit is just different way of creating packages moreoverthey are still relative to sys path at the top levelthe leftmost component of dotted namespace package path must still be located in an entry on the normal module search path in terms of physical structurethoughthe two can differ substantially regular packages still must have an __init__ py file that is run automaticallyand reside in single directory as before by contrastnew-style namespace packages cannot contain an __init__ pyand may span multiple directories that are collected at import time in factnone of the directories that make up namespace package can have an __init__ pybut the content nested within each of them is treated as single package the import algorithm to truly understand namespace packageswe have to look under the hood to see how the import operation works in during importspython still iterates over each directory in the module search pathsys pathjust as in and earlier in thoughwhile looking for an imported module or package named spamfor each directory in the module search pathpython tests for wider variety of matching criteriain the following order if directory\spam\__init__ py is founda regular package is imported and returned if directory\spam {pypycor other module extensionis founda simple module is imported and returned python namespace packages |
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 namespace package happens immediatelyand is not deferred until sublevel import occurs the new namespace package has __path__ attribute set to an iterable of the directory path strings that were found and recorded during the scan by step but does not have __file__ the __path__ attribute is then used in laterdeeper accesses to search all package components--each recorded entry on namespace package' __path__ is searched whenever further nested items are requestedmuch like the sole directory of regular package viewed another waythe __path__ attribute of namespace package serves the same role for lower-level components that sys path does at the top for the leftmost component of package import pathsit becomes the "parent pathfor accessing lower items using the same four-step procedure just sketched the net result is that namespace package is sort of virtual concatenation of directories located via multiple sys path entries once namespace package is createdthoughthere is no functional difference between it and regular packageit supports everything we've learned for regular packagesincluding package-relative import syntax impacts on regular packagesoptional __init__ py as one consequence of this new import procedureas of python packages no longer require __init__ py files--when single-directory package does not have this fileit will be treated as single-directory namespace packageand no warning will be issued this is major relaxation of prior rulesbut commonly requested changemany packages require no initialization codeand it seemed extraneous to have to create an empty initialization file in such cases this is finally no longer required as of at the same timethe original regular package model is still fully supportedand automatically runs code in __init__ py as before as an initialization hook moreoverwhen it' known that package will never be portion of split namespace packagethere is performance advantage to coding it as regular package with an __init__ py creation and loading of regular package occurs immediately when it is located along the path with namespace packagesall entries in the path must be scanned before the package is created more formallyregular packages stop the prior section' algorithm at step namespace packages do not module packages |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.