id
int64
0
25.6k
text
stringlengths
0
4.59k
1,000
for in 'abc'for in 'lmn'res append( yres ['al''am''an''bl''bm''bn''cl''cm''cn'beyond this complexity levelthoughlist comprehension expressions can often become too compact for their own good in generalthey are intended for simple types of iterationsfor more involved worka simpler for statement structure will probably b...
1,001
import sys print(sys pathx print( * but also much more for instancelist comprehensions and the map built-in function use the same protocol as their for loop cousin when applied to filethey both leverage the file object' iterator automatically to scan line by linefetching an iterator with __iter__ and calling __next__ e...
1,002
in the prior filter and reduce are in ' functional programming domainso we'll defer their details for nowthe point to notice here is their use of the iteration protocol for files and other iterables we first saw the sorted function used here at work inand we used it for dictionaries in sorted is built-in that employs t...
1,003
[ 'import sys\ ''print(sys path)\ '' \ ''print( * )\ 'per extend iterates automaticallybut append does not--use the latter (or similarto add an iterable to list without iteratingwith the potential to be iterated across laterl [ append(open('script py')list append does not iterate [ list( [ ]['import sys\ ''print(sys pa...
1,004
but return single resultsum([ ] any(['spam''''ni']true all(['spam''''ni']false max([ ] min([ ] sum expects numbers only strictly speakingthe max and min functions can be applied to files as well--they automatically use the iteration protocol to scan the file and pick out the lines with the highest and lowest string val...
1,005
ab zip(*zip(xy) ( ( unzip zipstill other tools in pythonsuch as the range built-in and dictionary view objectsreturn iterables instead of processing them to see how these have been absorbed into the iteration protocol in python as wellwe need to move on to the next section new iterables in python one of the fundamental...
1,006
after single passm map(lambda *xrange( )for in mprint( for in mprint(iunlike listsone pass only (zip toosuch conversion isn' required in xbecause functions like zip return lists of results in xthoughthey return iterable objectsproducing results on demand this may break codeand means extra typing is required to display ...
1,007
next( __next__( continue taking from iteratorwhere left off next(becomes __next__()but use new next(version skew noteas first mentioned in the preceding python also has built-in called xrangewhich is like range but produces items on demand instead of building list of results in memory all at once since this is exactly ...
1,008
list(map(abs(- ))[ can force real list if needed the zip built-inintroduced in the prior is an iteration context itselfbut also returns an iterable with an iterator that works the same wayz zip(( )( ) zip is the samea one-pass iterator list( [( )( )( )for pair in zprint(pairz zip(( )( )for pair in zprint(pair( ( ( zip(...
1,009
it' important to see how the range object differs from the built-ins described in this section--it supports len and indexingit is not its own iterator (you make one with iter when iterating manually)and it supports multiple iterators over its result that remember their positions independentlyr range( range allows multi...
1,010
range in this regardsupporting just single active iteration scan in that we'll see some subtle implications of one-shot iterators in loops that attempt to scan multiple times--code that formerly treated these as lists may fail without manual list conversions dictionary view iterables finallyas we saw briefly in in pyth...
1,011
list( )[ list( items()[(' ' )(' ' )(' ' )for (kvin items()print(kvend=' in addition dictionaries still are iterables themselveswith an iterator that returns successive keys thusit' not often necessary to call keys directly in this contextd {' ' ' ' ' ' iter(dnext( 'anext( 'bdictionaries still produce an iterator return...
1,012
in particularuser-defined iterables defined with classes allow arbitrary objects and operations to be used in any of the iteration contexts we've met in this by supporting just single operation--iteration--objects may be used in wide variety of contexts and tools summary in this we explored concepts related to looping ...
1,013
initial iter call is extraneous but harmless both are iteration tools and contexts list comprehensions are concise and often efficient way to perform common for loop taskcollecting the results of applying an expression to all items in an iterable object it' always possible to translate list comprehension to for loopand...
1,014
the documentation interlude this part of the book concludes with look at techniques and tools used for documenting python code although python code is designed to be readablea few wellplaced human-accessible comments can do much to help others understand the workings of your programs as we'll seepython includes both sy...
1,015
form role comments in-file documentation the dir function lists of attributes available in objects docstrings__doc__ in-file documentation attached to objects pydocthe help function interactive help for objects pydochtml reports module documentation in browser sphinx third-party tool richer documentation for larger pro...
1,016
len(dir(sys) len([ for in dir(sysif not startswith('__')] len([ for in dir(sysif not [ =' '] number names in sys non __x names only non underscore names to find out what attributes are provided in objects of built-in typesrun dir on literal or an existing instance of the desired type for exampleto see list and string a...
1,017
of literaldir(str=dir(''true dir(list=dir([]true same resulttype name or literal this works because names like str and list that were once type converter functions are actually names of types in python todaycalling one of these invokes its constructor to generate an instance of that type part vi will have more to say a...
1,018
def square( )""function documentation can we have your liver then""return * square class employee"class documentationpass print(square( )print(square __doc__the whole point of this documentation protocol is that your comments are retained for inspection in __doc__ attributes after the file is imported thusto display th...
1,019
software beyond these guidelinesthoughyou still must decide what to write although some companies have internal standardsthere is no broad standard about what should go into the text of docstring there have been various markup language and template proposals ( html or xml)but they don' seem to have caught on in the pyt...
1,020
int( [base]-integer convert string or number to an integerif possible floating point argument will be truncated towards zero (this does not include more text omitted print(map __doc__map(func*iterables--map object make an iterator that computes the function using arguments from each of the iterables stops when the shor...
1,021
module' name as string--for examplehelp('re')help('email message')--but support for this and other modes may differ across python versions for larger objects such as modules and classesthe help display is broken down into multiple sectionsthe preambles of which are shown here run this interactively to see the full repo...
1,022
type or the usage of that methodhelp(dicthelp on class dict in module builtinsclass dict(objectdict(-new empty dictionary dict(mapping-new dictionary initialized from mapping object' more omitted help(str replacehelp on method_descriptorreplaces replace (oldnew[count]-str return copy of with all occurrences of substrin...
1,023
class employee(builtins objectclass documentation more omitted help(docstringshelp on module docstringsname docstrings description module documentation words go here classes builtins object employee class employee(builtins objectclass documentation more omitted functions square(xfunction documentation can we have your ...
1,024
well as the newer all-browser mode mandated as of because this book' audience is both users of the latest-and-greatest as well as the masses still using older tried-and-true pythonswe'll explore both schemes here as we dokeep in mind that the way these schemes differ pertains only to the top level of their user interfa...
1,025
and laterwhich as of replaces the former gui client in earlier pythons however you run this command linethe effect is to start pydoc as locally running web server on dedicated (but by default arbitrary unusedportand pop up web browser to act as clientdisplaying page giving links to documentation for all the modules imp...
1,026
file' code modules normally just define tools when runso this is usually irrelevant if you ask for documentation for top-level script filethoughthe shell window where you launched pydoc serves as the script' standard input and output for any user interaction the net effect is that the documentation page for script will...
1,027
displaying two modules we will be coding in the next part of this book (changing pydoc' colors you won' be able to tell in the paper version of this bookbut if you have an ebook or start pydoc liveyou'll notice that it chooses colors that may or may not be to your liking unfortunatelythere presently is no easy way to c...
1,028
in idlean edit/find for regular expression #\ { will locate color strings (this matches six alphanumeric characters after per python' re module pattern syntaxsee the library manual for detailsto pick colorsin most programs with color selection dialogs you can map to and from rgb valuesthe book' examples include gui scr...
1,029
module you want documentation forpress enterselect the moduleand then press "go to selected(or omit the module name and press "open browserto see all available modulesto start pydoc in this modeyou generally first launch the search engine gui captured in figure - you can start this either by selecting the module docs i...
1,030
moduleand press "go to selected,the module' documentation is rendered in html and displayed in web browser window like this one work on pythons and had to add to my pythonpath to get pydoc' gui client mode to look in the directory it was started from by command linec:\codeset pythonpath;%pytyonpathc:\codepy - - pydoc -...
1,031
the module search path here is the page for user-defined moduleshowing all its documentation strings (docstringsextracted from the source file pydoc can also be run to save the html documentation for module in file for later viewing or printingsee the preceding section for pointers alsonote that pydoc might not work we...
1,032
in figure - ' windowpydoc will produce an index page containing hyperlink to every module you can possibly import on your computer this includes python standard library modulesmodules of installed third-party extensionsuser-defined modules on your import search pathand even statically or dynamically linked-in -coded mo...
1,033
help menuand in the windows and earlier start button menu it' searchable help file on windowsand there is search engine for the online version of thesethe library reference is the one you'll want to use most of the time formal description of language-level detailsthe tutorial listed on this page also provides brief int...
1,034
are good you'll find ample material to browse published books as final resourceyou can choose from collection of professionally edited and published reference books for python bear in mind that books tend to lag behind the cutting edge of python changespartly because of the work involved in writingand partly because of...
1,035
unless you know what your text editor does with tabs otherwisewhat you see in your editor may not be what python sees when it counts tabs as number of spaces this is true in any block-structured languagenot just python--if the next programmer has tabs set differentlyit will be difficult or impossible to understand the ...
1,036
dictionary iterators--iterators do not sort always use parentheses to call function you must add parentheses after function name to call itwhether it takes arguments or not ( use function()not functionin the next part of this bookwe'll learn that functions are simply objects that have special operation-- call that you ...
1,037
when should you use documentation strings instead of hash-mark comments name three ways you can view documentation strings how can you obtain list of the available attributes in an object how can you get list of all available modules on your computer which python book should you purchase after this onetest your knowled...
1,038
now that you know how to code basic program logicthe following exercises will ask you to implement some simple tasks with statements most of the work is in exercise which lets you explore coding alternatives there are always many ways to arrange statementsand part of learning python is learning which arrangements work ...
1,039
found true elsei + if foundprint('at index'ielseprint( 'not found' :\book\testspython power py at index as isthe example doesn' follow normal python coding techniques follow the steps outlined here to improve it (for all the transformationsyou may either type your code interactively or store it in script file run from ...
1,040
hope the procedure will be well documented in python' manuals test your knowledgepart iii exercises
1,041
functions and generators
1,042
function basics in part iiiwe studied basic procedural statements in python herewe'll move on to explore set of additional statements and expressions that we can use to create functions of our own in simple termsa function is device that groups set of statements so they can be run more than once in program-- packaged p...
1,043
statement or expression examples global 'olddef changer()global xx 'newnonlocal ( xdef outer() 'olddef changer()nonlocal xx 'newyield def squares( )for in range( )yield * lambda funcs [lambda xx** lambda xx** why use functionsbefore we get into the detailslet' establish clear picture of what functions are all about fun...
1,044
but they do lead us to some bigger programming ideas coding functions although it wasn' made very formalwe've already used some functions in earlier for instanceto make file objectwe called the built-in open functionsimilarlywe used the len built-in function to ask for the number of items in collection object in this w...
1,045
series of results over time this is another advanced topic covered later in this part of the book global declares module-level variables that are to be assigned by defaultall names assigned in function are local to that function and exist only while the function runs to assign name in the enclosing modulefunctions need...
1,046
statements as with all compound python statementsdef consists of header line followed by block of statementsusually indented (or simple statement after the colonthe statement block becomes the function' body--that isthe code python executes each time the function is later called the def header line specifies function n...
1,047
it simply assigns name at runtime unlike in compiled languages such as cpython functions do not need to be fully defined before the program runs more generallydefs are not evaluated until they are reached and runand the code inside defs is not evaluated until the functions are later called because function definition h...
1,048
(assignedto the names in the function' headertimes( arguments in parentheses this expression passes two arguments to times as mentioned previouslyarguments are passed by assignmentso in this case the name in the function header is assigned the value is assigned the value and the function' body is run for this functiont...
1,049
protocol)the function can process them that isif the objects passed into function have the expected methods and expression operatorsthey are plug-and-play compatible with the function' logic even in our simple times functionthis means that any two objects that support will workno matter what they may beand no matter wh...
1,050
good nor general--we' still have to edit each copy to support different sequence namesand changing the algorithm would then require changing multiple copies definition by nowyou can probably guess that the solution to this dilemma is to package the for loop inside function doing so offers number of advantagesputting th...
1,051
mathematical intersection (there may be duplicates in the result)and isn' required at all (as we've seenpython' set data type provides built-in intersection operationindeedthe function could be replaced with single list comprehension expressionas it exhibits the classic loop collector code pattern[ for in if in [' '' '...
1,052
both reduce the amount of code we need to write and increase our code' flexibility local variables probably the most interesting part of this examplethoughis its names it turns out that the variable res inside intersect is what in python is called local variable-- name that is visible only to code inside the function d...
1,053
test your knowledgeanswers functions are the most basic way of avoiding code redundancy in python--factoring code into functions means that we have only one copy of an operation' code to update in the future functions are also the basic unit of code reuse in python --wrapping code in functions makes it reusable toolcal...
1,054
scopes introduced basic function definitions and calls as we sawpython' core function model is simple to usebut even simple function examples quickly led us to questions about the meaning of variables in our code this moves on to present the details behind python' scopes--the places where variables are defined and look...
1,055
and no other this rule means thatnames assigned inside def can only be seen by the code within that def you cannot even refer to such names from outside the function names assigned inside def do not clash with variables outside the defeven if the same names are used elsewhere name assigned outside given def ( in differ...
1,056
isa namespace in which variables created (assignedat the top level of the module file live global variables become attributes of module object to the outside world after imports but can also be used as simple variables within the module file itself the global scope spans single file only don' be fooled by the word "glo...
1,057
assignments do for instanceif the name is assigned to list at the top level of modulea statement within function will classify as localbut append(xwill not in the latter casewe are changing the list object that referencesnot itself -- is found in the global scope as usualand python happily modifies it without requiring...
1,058
this orderin the local scopein any enclosing functionslocal scopesin the global scopeand finally in the built-in scope the first occurrence wins the place in your code where variable is assigned usually determines its scope in python xnonlocal declarations can also force names to be mapped to enclosing function scopesw...
1,059
in comprehension expression such as [ for in ibecause they might clash with other names and reflect internal state in generatorsin xsuch variables are local to the expression itself in all comprehension formsgeneratorlistsetand dictionary in xthey are local to generator expressions and set and dictionary compressionsbu...
1,060
func( func in moduleresult= this module and the function it contains use number of names to do their business using python' scope ruleswe can classify the names as followsglobal namesxfunc is global because it' assigned at the top level of the module fileit can be referenced inside the function as simple unqualified va...
1,061
'ord''pow''print''property''quit''range''repr''reversed''round''set''setattr''slice''sorted''staticmethod''str''sum''super''tuple''type''vars''zip'the names in this list constitute the built-in scope in pythonroughly the first half are built-in exceptionsand the second half are built-in functions also in this list are ...
1,062
names as reserved with over names in this module in that would be far too restrictive and dauntinglen(dir(builtins))len([ for in dir(builtinsif not startswith('__')]( in factthere are times in advanced programming where you may really want to replace built-in name by redefining it in your code--to define custom open th...
1,063
in xand __builtin__ for the same in who said documenting this stuff was easybreaking the universe in python here' another thing you can do in python that you probably shouldn' --because the names true and false in are just variables in the built-in scope and are not reservedit' possible to reassign them with statement ...
1,064
global names may be referenced within function without being declared in other wordsglobal allows us to change names that live outside def at the top level of module file as we'll see laterthe nonlocal statement is almost identical but applies to names in the enclosing def' local scoperather than names in the enclosing...
1,065
thing although there are times when globals are usefulvariables assigned in def are local by default because that is normally the best policy changing globals can lead to well-known software engineering problemsbecause the variablesvalues are dependent on the order of calls to arbitrarily distant functionsprograms can ...
1,066
enough try to communicate with passed-in arguments and return values instead six months from nowboth you and your coworkers may be happy you did program designminimize cross-file changes here' another scope-related design issuealthough we can change variables in another file directlywe usually shouldn' module files wer...
1,067
all although such cross-file variable changes are always possible in pythonthey are usually much more subtle than you will want againthis sets up too strong coupling between the two files--because they are both dependent on the value of the variable xit' difficult to understand or reuse one file without the other such ...
1,068
var change local var def glob ()global var var + declare global (normalchange global var def glob ()var import thismod thismod var + change local var import myself change global var def glob ()var import sys glob sys modules['thismod'glob var + change local var import system table get module object (or use __name__chan...
1,069
with the addition of nested function scopesvariable lookup rules become slightly more complex within functiona reference (xlooks for the name first in the current local scope (function)then in the local scopes of any lexically enclosing functions in your source codefrom inner to outerthen in the current global scope (t...
1,070
for examplethe following code defines function that makes and returns another functionand represents more common usage patterndef () def ()print(xreturn remembers in enclosing def scope return but don' call it action (action(makereturn function call it nowprints in this codethe call to action is really running the func...
1,071
maker( pass to argument action at what we get back is reference to the generated nested function--the one created when the nested def runs if we now call what we got back from the outer functionf( ( pass to xn remembers * * we invoke the nested function--the one called action within maker in other wordswe're calling th...
1,072
appear in your interface (they do at the shellbut not in idlethis convention will be followed from this point on to make larger code examples bit easier to cut and paste from an ebook or other ' assuming that by now you understand indentation rules and have had your fair share of typing python codeand some functions an...
1,073
of the enclosing function' local names are retained by references within the classor one of its method functions see for more on nested classes as we'll see in later examples ( ' decorators)the outer def in such code serves similar roleit becomes class factoryand provides state retention for the nested class retaining ...
1,074
(xpass along instead of nesting forward reference ok def ( )print(xflat is still often better than nestedf ( if you avoid nesting this wayyou can almost forget about the nested scopes concept in python on the other handthe nested functions of closure (factoryfunctions are fairly common in modern python codeas are lambd...
1,075
to pass values into lambdas with defaults loop variables may require defaultsnot scopes there is one notable exception to the rule just gave (and reason why 've shown you the otherwise dated default argument technique we just saw)if lambda or def defined within function is nested inside loopand the nested function refe...
1,076
it' later called)each remembers its own value for idef makeactions()acts [for in range( )acts append(lambda xi=ii *xreturn acts acts makeactions(acts[ ]( acts[ ]( acts[ ]( acts[ ]( use defaults instead remember current * * * * this seems an implementation artifact that is prone to changeand may become more important as...
1,077
coworkerswill generally be better if you minimize nested function definitions the nonlocal statement in in the prior section we explored the way that nested functions can reference variables in an enclosing function' scopeeven if that function has already returned it turns out thatin python (though not in )we can also ...
1,078
for state retentionthoughnonlocal makes it more generally applicable besides allowing names in enclosing defs to be changedthe nonlocal statement also forces the issue for references--much like the global statementnonlocal causes searches for the names listed in the statement to begin in the enclosing defsscopesnot in ...
1,079
def nested(label)print(labelstatereturn nested referencing nonlocals works normally remembers state in enclosing scope tester( ('spam'spam ('ham'ham changing name in an enclosing def' scope is not allowed by defaultthoughthis is the normal case in as welldef tester(start)state start def nested(label)print(labelstatesta...
1,080
('spam'spam make new tester that starts at ('eggs'eggs my state information updated to ('bacon'bacon but ' is where it left offat each call has different state information in this sensepython' nonlocals are more functional than function locals typical in some other languagesin closure functionnonlocals are per-callmult...
1,081
syntaxerrorno binding for nonlocal 'spamfound these restrictions make sense once you realize that python would not otherwise generally know which enclosing scope to create brand-new name in in the prior listingshould spam be assigned in testeror the module outsidebecause this is ambiguouspython must resolve nonlocals a...
1,082
options are availabledepending on your goals the next three sections present some alternatives some of the code in these sections uses tools we haven' covered yet and is intended partially as previewbut we'll keep the examples simple here so that you can compare and contrast along the way state with globalsa single cop...
1,083
also support inheritancemultiple behaviorsand other tools we haven' explored classes in detail yetbut as brief preview for comparisonthe following is reformulation of the earlier tester/nested functions as classwhich records state in objects explicitly as they are created to make sense of this codeyou need to know that...
1,084
pancakes don' sweat the details in this code too much at this point in the bookit' mostly previewintended for general comparison to closures only we'll explore classes in depth in part viand will look at specific operator overloading tools like __call__ in the point to notice here is that classes can make state informa...
1,085
state to be accessed externallyand saves line by not requiring nonlocal declarationdef tester(start)def nested(label)print(labelnested statenested state + nested state start return nested tester( ('spam'spam ('ham'ham state nested is in enclosing scope change attrnot nested itself initial state after func defined is 'n...
1,086
on related noteit' also possible to change mutable object in the enclosing scope in and without declaring its name nonlocal the followingfor exampleworks the same as the previous versionis just as portableand provides changeable per-call statedef tester(start)def nested(label)print(labelstate[ ]state[ + state [startret...
1,087
original builtins open def custom(*kargs**pargs)print('custom open call % :id kargspargsreturn original(*kargs**pargsbuiltins open custom to change open for every module in processthis code reassigns it in the built-in scope to custom version coded with nested defafter it saving the original in the enclosing scope so t...
1,088
code when state retention is the only goal we'll see additional closure use cases laterespecially when exploring decorators in where we'll find the closures are actually preferred to classes in certain roles summary in this we studied one of two key concepts related to functionsscopeswhich determine how variables are l...
1,089
'spamdef func()global 'nifunc(print( what about this code--what' the outputand whyx 'spamdef func() 'nidef nested()print(xnested(func( how about this examplewhat is its output in python xand whydef func() 'nidef nested()nonlocal 'spamnested(print(xfunc( name three or more ways to retain state information in python func...
1,090
but not xmeans that the assignment to inside the nested function changes in the enclosing function' local scope without this statementthis assignment would classify as local to the nested functionmaking it different variablethe code would then print 'niinstead although the values of local variables go away when functio...
1,091
arguments explored the details behind python' scopes--the places where variables are defined and looked up as we learnedthe place where name is defined in our code determines much of its meaning this continues the function story by studying the concepts in python argument passing--the way that objects are sent to funct...
1,092
to function argumentsthough the assignment to argument names is automatic and implicit python' pass-by-assignment scheme isn' quite the same as ++' reference parameters optionbut it turns out to be very similar to the argument-passing model of the language (and othersin practiceimmutable arguments are effectively passe...
1,093
[ 'spamarguments assigned references to objects changes local name' value only changes shared object in place [ changer(xlxl ( ['spam' ]callerpass immutable and mutable objects is unchangedl is differentin this codethe changer function assigns values to argument itselfand to component of the object referenced by argume...
1,094
in the function may share objects with variables in the scope of the call hencein-place changes to mutable arguments in function can impact the caller herea and in the function initially reference the objects referenced by variables and when the function is first called changing the list through variable makes appear d...
1,095
[: [ 'spamcopy input list so we don' impact caller changes our list copy only both of these copying schemes don' stop the function from changing the object--they just prevent those changes from impacting the caller to really prevent changeswe can always convert to immutable objects to force the issue tuplesfor exampler...
1,096
xl ( [ ]it looks like the code is returning two values herebut it' really just one-- two-item tuple with the optional surrounding parentheses omitted after the call returnswe can use tuple assignment to unpack the parts of the returned tuple (if you've forgotten why this worksflip back to "tuplesin and and "assignment ...
1,097
by defaultarguments are matched by positionfrom left to rightand you must pass exactly as many arguments as there are argument names in the function header howeveryou can also specify matching by nameprovide default valuesand use collectors for extra arguments argument matching basics before we go into the syntactic de...
1,098
table - summarizes the syntax that invokes the special argument-matching modes table - function argument-matching forms syntax location interpretation func(valuecaller normal argumentmatched by position func(name=valuecaller keyword argumentmatched by name func(*iterablecaller pass all objects in iterable as individual...
1,099
further allows us to pick and choose which defaults to override in shortspecial argument-matching modes let you be fairly liberal about how many arguments must be passed to function if function specifies defaultsthey are used if you pass too few arguments if function uses the variable argument list formsyou can seeming...