id
int64
0
25.6k
text
stringlengths
0
4.59k
1,300
that' the story todaychange is always possibility in open source projects (indeedthe prior edition quoted plans on string formatting and relative imports in that were later abandoned)so as usualbe sure to watch for future developments on this front given the performance advantage and auto-initialization code of regular...
1,301
this is also true if we import through the namespace package name immediately-because the namespace package is made when first reachedthe timing of path extensions is irrelevantc:\codec:\python \python import sub mod dir \sub\mod import sub mod dir \sub\mod one package spanning two directories sub mod sub mod sub sub _...
1,302
:\codec:\python \python import sub lower mod dir \sub\lower\mod :\codec:\python \python import sub import sub mod dir \sub\mod import sub lower mod dir \sub\lower\mod namespace pkg nested in namespace pkg same effect if accessed incrementally sub lower single-directory namespace pkg sub lower __path__ _namespacepath(['...
1,303
as explained earlierpart of the purpose of __init___ py files in regular packages is to declare the directory as package--it tells python to use the directoryrather than skipping ahead to possible file of the same name later on the path this avoids inadvertently choosing noncode subdirectory that accidentally appears e...
1,304
sys path[: [''' :\\code\\ns \\dir'first 'means current working directorycwd in factsetting the path to include module works the same as it does in earlier pythonseven if same-named namespace directory appears earlier on the pathnamespace packages are used in only in cases that would be errors in earlier pythonsc:\codep...
1,305
this introduced python' package import model--an optional but useful way to explicitly list part of the directory path leading up to your modules package imports are still relative to directory on your module import search pathbut your script gives the rest of the path to the module explicitly as we've seenpackages not...
1,306
or use the as extension with the import statement to rename the path to shorter synonym in both casesthe path is listed in only one placein the from or import statement in python and earliereach directory listed in an executed import or from statement must contain an __init__ py file other directoriesincluding the dire...
1,307
advanced module topics this concludes this part of the book with collection of more advanced module-related topics--data hidingthe __future__ modulethe __name__ variablesys path changeslisting toolsimporting modules by name stringtransitive reloadsand so on--along with the standard set of gotchas and exercises related ...
1,308
with the outside world are the tools it usesand the tools it defines maximize module cohesionunified purpose you can minimize module' couplings by maximizing its cohesionif all the components of module share general purposeyou're less likely to depend on external names modules should rarely change other modulesvariable...
1,309
as we've seena python module exports all the names assigned at the top level of its file there is no notion of declaring which names should and shouldn' be visible outside the module in factthere' no way to prevent client from changing names inside module if it wants to in pythondata hiding in modules is conventionnot ...
1,310
from alls import a_c ( nameerrorname 'bis not defined load __all__ names only from alls import ab_c_d ab_c_d ( but other importers get every name import alls alls aalls balls _calls _d ( like the _x conventionthe __all__ list has meaning only to the from statement form and does not amount to privacy declarationother im...
1,311
__future__ import even in code run by version of python where the feature is present normally mixed usage modes__name__ and __main__ our next module-related trick lets you both import file as module and run it as standalone programand is widely used in python files it' actually so simple that some miss the point at fir...
1,312
common and simplest unit-testing protocol in python it' much more convenient than retyping all your tests at the interactive prompt will discuss other commonly used options for testing python code--as you'll seethe unittest and doctest standard library modules provide more advanced testing tools in additionthe __name__...
1,313
def lessthan(xy)return def grtrthan(xy)return if __name__ ='__main__'print(minmax(lessthan )print(minmax(grtrthan )self-test code we're also printing the value of __name__ at the top here to trace its value python creates and assigns this usage-mode variable as soon as it starts loading file when we run this file as to...
1,314
various specialized string display formatting utilities test me with canned self-test or command-line arguments to doadd parens for negative moneyadd more features ""def commas( )""format positive integer-like for display with commas between digit groupings"xxx,yyy,zzz""digits str(nassert(digits isdigit()result 'while ...
1,315
print(money(float(sys argv[ ])int(sys argv[ ]))this file works identically in python and when run directlyit tests itself as beforebut it uses options on the command line to control the test behavior run this file directly with no command-line arguments on your own to see what its self-test code prints--it' too extensi...
1,316
parse modulesdocumentation in python' standard library manual in some scenariosyou might also use the built-in input functionused in and to prompt the shell user for test inputs instead of pulling them from the command line also see ' discussion of the new {,dstring format method syntax added in python and this formatt...
1,317
uunicode literals as treated as normal strings in as of $ , , ps , = , ps , eur , eur , $? , if this works on your computeryou can probably skip the next few paragraphs depending on your interface and system settingsthoughgetting this to run and display properly may require additional steps on my machineit behaves corr...
1,318
= ps print('\xa ' ''% '\ ' = ps xstr is unicodeu'optional againthere' much more on unicode in -- topic many see as peripheralbut which can crop up even in relatively simple contexts like thisthe takeaway point here is thatoperational issues asidea carefully coded script can often manage to support unicode in both and d...
1,319
in and later and clicking on the file' index entry (see sys path list per sys path is initialized on startupbut thereafter you can deleteappendand reset its components however you likeimport sys sys path [''' :\\temp'' :\\windows\\system \\python zip'more deleted sys path append(' :\\sourcedir'import string extend modu...
1,320
from the pathalsoremember that such sys path settings endure for only as long as the python session or program (technicallyprocessthat made them runsthey are not retained after python exits by contrastpythonpath and pth file path configurations live in the operating system instead of running python programand so are mo...
1,321
renames module or tool your code uses extensivelyor provides new alternative you' rather use insteadyou can simply rename it to its prior name on import to avoid breaking your codeimport newname as oldname from library import newname as oldname and keep happily using oldname until you have time to update all your code ...
1,322
""mydir pya module that lists the namespaces of other modules ""from __future__ import print_function compatibility seplen sepchr '-def listing(moduleverbose=true)sepline sepchr seplen if verboseprint(seplineprint('name:'module __name__'file:'module __file__print(seplinecount for attr in sorted(module __dict__)scan nam...
1,323
print_function _feature(( 'alpha' )( 'alpha' ) sepchr seplen mydir has names to use this as tool for listing other modulessimply pass the modules in as objects to this file' function here it is listing attributes in the tkinter gui module in the standard library ( tkinter in python )it will technically work on any obje...
1,324
file ""line import "stringsyntaxerrorinvalid syntax it also won' work to simply assign the string to variable namex 'stringimport herepython will try to import file pynot the string module--the name in an import statement both becomes variable assigned to the loaded module and identifies the external file literally run...
1,325
workand is generally preferred in more recent pythons for direct calls to import by name string--at least per the current "officialpolicy stated in python' manualsimport importlib modname 'stringstring importlib import_module(modnamestring the import_module call takes module name stringand an optional second argument t...
1,326
better approach is to write general tool to do transitive reloads automatically by scanning modules__dict__ namespace attributes and checking each item' type to find nested modules to reload such utility function could call itself recursively to navigate arbitrarily shaped and deep import dependency chains module __dic...
1,327
import importlibsys if len(sys argv modname sys argv[ module importlib import_module(modnamereloader(moduleself-test code import on tests only command line (or passedimport by name string test passed-in reloader if __name__ ='__main__'tester(reload_all'reloadall'testreload myselfbesides namespace dictionariesthis scrip...
1,328
reloading ntpath reloading stat reloading genericpath reloading copyreg perhaps most commonlywe can also deploy this module at the interactive prompt-herein for some standard library modules notice how os is imported by tkinterbut tkinter reaches sys before os can (if you want to test this on python xsubstitute tkinter...
1,329
without stopping pythonchange all three filesassignment values and save from imp import reload reload(aa xa ya ( from reloadall import reload_all reload_all(areloading reloading reloading xa ya ( built-in reload is top level only normal usage mode reloads all nested modules too study the reloader' code and results for ...
1,330
recursive functionswhich may be preferable in some contexts the following is one such transitive reloaderit uses generator expression to filter out nonmodules and modules already visited in the current module' namespace because it both pops and adds items at the end of its listit is stack basedthough the order of both ...
1,331
reloading types though it' hard to see herewe really are testing the individual reloader alternatives --each of these tests shares common tester functionbut passes it the reload_all from its own file here are the variants reloading the tkinter gui module and all the modules its imports reachc:\codereloadall py tkinter ...
1,332
reloadall tester(reloadall reload_all'reloadall 'reloading reloadall reloading types mimic self-test code finallyif you look at the output of tkinter reloads earlieryou may notice that each of the three variants may produce results in different orderthey all depend on namespace dictionary orderingand the last also reli...
1,333
something important about the language module name clashespackage and package-relative imports if you have two modules of the same nameyou may only be able to import one of them --by defaultthe one whose directory is leftmost in the sys path module search path will always be chosen this isn' an issue if the module you ...
1,334
error"func not yet assigned def func ()print(func ()ok"func looked up later func (error"func not yet assigned def func ()return "hellofunc (ok"func and "func assigned when this file is imported (or run as standalone program)python executes its statements from top to bottom the first call to func fails because the func ...
1,335
we change the name in nested py attribute qualification directs python to name in the module objectrather than name in the importernested pynested py import nested nested nested printer(get module as whole okchange nested ' python nested py from can obscure the meaning of variables mentioned this earlier but saved the ...
1,336
names using from that isthe client' names will still reference the original objects fetched with fromeven if the names in the original module are later resetfrom module import from imp import reload reload(modulex may not reflect any module reloadschanges modulebut not my names still references old object to make reloa...
1,337
original version of the function to really get the new functionyou must refer to it as module function after the reloador rerun the fromfrom imp import reload import module reload(modulefrom module import function function( or give up and use module function(nowthe new version of the function will finally runbut it see...
1,338
recur py from recur import from recur import run recur now if it doesn' exist ok"xalready assigned error"ynot yet assigned :\codepy - import recur traceback (most recent call last)file ""line in file \recur py"line in import recur file \recur py"line in from recur import importerrorcannot import name python avoids reru...
1,339
bookhoweverbefore we dive into that topicbe sure to work through this part' set of lab exercises and before thathere is this quiz to review the topics covered here test your knowledgequiz what is significant about variables at the top level of module whose names begin with single underscore what does it mean when modul...
1,340
see part in appendix for the solutions import basics write program that counts the lines and characters in file (similar in spirit to part of what wc does on unixwith your text editorcode python module called mymod py that exports three top-level namesa countlines(namefunction that reads an input file and counts the nu...
1,341
attribute package imports import your file from package create subdirectory called mypkg nested in directory on your module import search pathcopy or move the mymod py module file you created in exercise or into the new directoryand try to import it with package import of the form import mypkg mymod and call its functi...
1,342
classes and oop
1,343
oopthe big picture so far in this bookwe've been using the term "objectgenerically reallythe code written up to this point has been object-based--we've passed objects around our scriptsused them in expressionscalled their methodsand so on for our code to qualify as being truly object-oriented (oo)thoughour objects will...
1,344
remember when told you that programs "do things with stuffin and in simple termsclasses are just way to define new sorts of stuffreflecting real objects in program' domain for instancesuppose we decide to implement that hypothetical pizza-making robot we used as an example in if we implement it using classeswe can mode...
1,345
classes also support the oop notion of inheritancewe can extend class by redefining its attributes outside the class itself in new software components coded as subclasses more generallyclasses can build up namespace hierarchieswhich define names to be used by objects created from classes in the hierarchy this supports ...
1,346
from bottom to top and left to right in other wordsattribute fetches are simply tree searches the term inheritance is applied because objects lower in tree inherit attributes attached to objects higher in that tree as the search proceeds from the bottom upin sensethe objects linked into tree are the union of all the at...
1,347
we usually call classes higher in the tree (like and superclassesclasses lower in the tree (like are known as subclasses these terms refer to both relative tree positions and roles superclasses provide behavior shared by all their subclassesbut because the search proceeds from the bottom upsubclasses may override behav...
1,348
although they are technically two separate object types in the python modelthe classes and instances we put in these trees are almost identical--each type' main purpose is to serve as another kind of namespace-- package of variablesand place where we can attach attributes if classes and instances therefore sound like m...
1,349
to run bob giveraise(method callpython looks up giveraise from bobby inheritance search passes bob to the located giveraise functionin the special self argument when you call employee giveraise(bob)you're just performing both steps yourself this description is technically the default case (python has additional method ...
1,350
choose name by asking for it from the class it lives in ( zbecause of the way inheritance searches proceedthe object to which you attach an attribute turns out to be crucial--it determines the name' scope attributes attached to instances pertain only to those single instancesbut attributes attached to classes are share...
1,351
to the instance being processed--the subject of the call in factbecause all the objects in class trees are just namespace objectswe can fetch or set any of their attributes by going through the appropriate names saying setname is as valid as saying setnameas long as the names and are in your code' scopes operator overl...
1,352
to built-ins giveraise may make sense for an employeebut might not oop is about code reuse and thatalong with few syntax detailsis most of the oop story in python of coursethere' bit more to it than just inheritance for exampleoperator overloading is much more general than 've described so far--classes may also provide...
1,353
exampleif engineers have unique salary computation rule (perhaps it' not hours times rate)you can replace just that one method in subclassclass engineer(employee)def computesalary(self)specialized subclass something custom here because the computesalary version here appears lower in the class treeit will replace (overr...
1,354
data converter(datawriter write(databy passing in instances of subclasses that specialize the required read and write method interfaces for various data sourceswe can reuse the processor function for any data source we need to useboth now and in the futureclass readerdef read(self)default behavior and tools def other(s...
1,355
summary we took an abstract look at classes and oop in this taking in the big picture before we dive into syntax details as we've seenoop is mostly about an argument named selfand search for attributes in trees of linked objects called inheritance objects at the bottom of the tree inherit attributes from objects higher...
1,356
as attributesthe main difference between them is that classes are kind of factory for creating multiple instances classes also support operator overloading methodswhich instances inheritand treat any functions nested in the class as methods for processing instances the first argument in class' method function is specia...
1,357
class coding basics now that we've talked about oop in the abstractit' time to see how this translates to actual code this begins to fill in the syntax details behind the class model in python if you've never been exposed to oop in the pastclasses can seem somewhat complicated if taken in single dose to make class codi...
1,358
functions of but this is natural part of the class modeland state in classes is explicit attributes instead of implicit scope references moreoverthis is just part of what classes do--they also support customization by inheritanceoperator overloadingand multiple behaviors via methods generally speakingclasses are more c...
1,359
instance objects created from classes are new namespacesthey start out empty but inherit attributes that live in the class objects from which they were generated assignments to attributes of self in methods make per-instance attributes inside class' method functionsthe first argument (called self by conventionreference...
1,360
inheritance herethe "dataattribute is found in instancesbut "setdataand "displayare in the class above them ingat this pointwe have three objectstwo instances and class reallywe have three linked namespacesas sketched in figure - in oop termswe say that "is afirstclassas is --they both inherit names attached to the cla...
1,361
undefined name error--the attribute named data doesn' even exist in memory until it is assigned within the setdata method as another way to appreciate how dynamic this model isconsider that we can change instance attributes in the class itselfby assigning to self in methodsor outside the classby assigning to an explici...
1,362
and the class that is inherited from is its superclass classes inherit attributes from their superclasses just as instances inherit the attribute names defined in their classesclasses inherit all of the attribute names defined in their superclassespython finds them automatically when they're accessedif they don' exist ...
1,363
class tree heresecondclass redefines and so customizes the "displaymethod for its instances secondclass defines the display method to print with different format by defining an attribute with the same name as an attribute in firstclasssecondclass effectively replaces the display attribute in its superclass recall that ...
1,364
before we move onremember that there' nothing magic about class name it' just variable assigned to an object when the class statement runsand the object can be referenced with any normal expression for instanceif our firstclass were coded in module file instead of being typed interactivelywe could import it and use its...
1,365
person person(lowercase for modules uppercase for classes alsokeep in mind that although classes and modules are both namespaces for attaching attributesthey correspond to very different source code structuresa module reflects an entire filebut class is statement within file we'll say more about such distinctions later...
1,366
manyand not for most commonly used operations operators allow classes to integrate with python' object model by overloading type operationsthe user-defined objects we implement with classes can act just like built-insand so provide consistency as well as compatibility with expected interfaces operator overloading is an...
1,367
self data *other in-place changenamed thirdclass('abc' display(current value "abcprint( [thirdclassabc__init__ called inherited method called 'xyzb display(current value "abcxyzprint( [thirdclassabcxyz__add__makes new instance has all thirdclass methods mul( print( [thirdclassabcabcabcmulchanges instance in place __str...
1,368
specially named methods such as __init____add__and __str__ are inherited by subclasses and instancesjust like any other names assigned in class if they're not coded in classpython looks for such names in all its superclassesas usual operator overloading method names are also not built-in or reserved wordsthey are just ...
1,369
in action in one overloading method we will use often here is the __init__ constructor methodused to initialize newly created instance objectsand present in almost every realistic class because it allows classes to fill out the attributes in their new instances immediatelythe constructor is useful for almost every kind...
1,370
remember the class from which they were madethoughthey will obtain the attributes we attached to the class by inheritancex namey name ('bob''bob'name is stored on the class only reallythese instances have no attributes of their ownthey simply fetch the name attribute from the class object where it is stored if we do as...
1,371
__dict__['age'keyerror'agebut attribute fetch checks classes too indexing dict does not do inheritance to facilitate inheritance search on attribute fetcheseach instance has link to its class that python creates for us--it' called __class__if you want to inspect itx __class__ instance to class link classes also have __...
1,372
'bobsamebut pass to self rec method( 'suecan call through instance or class normallyclasses are filled out by class statementsand instance attributes are created by assignments to self attributes in method functions the point againthoughis that they don' have to beoop in python really is mostly about looking up attribu...
1,373
print(rec namebob this code has substantially less syntax than the dictionary equivalent it uses an empty class statement to generate an empty namespace object once we make the empty classwe fill it out by assigning class attributes over timeas before this worksbut new class statement will be required for each distinct...
1,374
by always setting the namejoband age attributeseven though the latter can be omitted when an object is made togetherthe class' methods and instance attributes create packagewhich combines both data and logic we could further extend this code by adding logic to compute salariesparse namesand so on ultimatelywe might lin...
1,375
how are classes related to modules how are instances and classes created where and how are class attributes created where and how are instance attributes created what does self mean in python class how is operator overloading coded in python class when might you want to support operator overloading in your classes whic...
1,376
explicit operator overloading is coded in python class with specially named methodsthey all begin and end with double underscores to make them unique these are not built-in or reserved namespython just runs them automatically when an instance appears in the corresponding operation python itself defines the mappings fro...
1,377
more realistic example we'll dig into more class syntax details in the next before we dothoughi' like to show you more realistic example of classes in action that' more practical than what we've seen so far in this we're going to build set of classes that do something more concrete--recording and processing information...
1,378
okso much for the design phase--let' move on to implementation our first task is to start coding the main classperson in your favorite text editoropen new file for the code we'll be writing it' fairly strong convention in python to begin module names with lowercase letter and class names with an uppercase letterlike th...
1,379
have the same name by assigning the job local to the self job attribute with self job=jobwe save the passed-in job on the instance for later use as usual in pythonwhere name is assignedor what object it is assigned todetermines what it means speaking of argumentsthere' really nothing magical about __init__apart from th...
1,380
code at the bottom of the file that contains the objects to be testedlike thisadd incremental self-test code class persondef __init__(selfnamejob=nonepay= )self name name self job job self pay pay bob person('bob smith'sue person('sue jones'job='dev'pay= print(bob namebob payprint(sue namesue paytest the class runs __i...
1,381
somewhere else (and we will soon in this we'll see the output of its test code every time the file is imported that' not very good software citizenshipthoughclient programs probably don' care about our internal tests and won' want to see our output mixed in with their own although we could split the test code off into ...
1,382
multiple items into tuple in onlyc:\codec:\python \python person py ('bob smith' ('sue jones' if this difference is the sort of detail that might keep you awake at nightssimply remove the parentheses to use print statementsor add an import of python ' print function at the top of your scriptas shown in ( ' add this eve...
1,383
its state information in place with an assignment this task also involves basic operations that work on python' core objectsregardless of whether they are standalone or embedded in class structure ( ' formatting the result in the following to mask the fact that different pythons print different number of decimal digits...
1,384
across many filessplit into individual stepsand so on in prototype like thisfrequent change is almost guaranteed coding methods what we really want to do here is employ software design concept known as encapsulation--wrapping up operation logic behind interfacessuch that each operation is coded only once in our program...
1,385
returns the resultbecause this operation is called function nowit computes value for its caller to use arbitrarilyeven if it is just to be printed similarlythe new giveraise method just does to self what we did to sue before when run nowour file' output is similar to before--we've mostly just refactored the code to all...
1,386
code something called function decorators and explore python' assert statement-alternatives that can do the validity test for us automatically during development in for examplewe'll write tool that lets us validate with strange incantations like the following@rangetest(percent=( )use decorator to validate def giveraise...
1,387
single display in all cases--printsnested appearancesand interactive echoes this still allows clients to provide an alternative display with __str__but for limited contexts onlysince this is self-contained examplethis is moot point here the __init__ constructor method we've already coded isstrictly speakingoperator ove...
1,388
an as-code low-level display of an object when presentand __str__ is reserved for more user-friendly informational displays like ours here sometimes classes provide both __str__ for user-friendly displays and __repr__ with extra details for developers to view because printing runs __str__ and the interactive prompt ech...
1,389
passed-in percentage as usualbut also gets an extra bonus that defaults to for instanceif manager' raise is specified as %it will really get (any relation to persons living or dead isof coursestrictly coincidental our new method begins as followsbecause this redefinition of giveraise will be closer in the class tree to...
1,390
an instance (the usual waywhere python sends the instance to the self argument automaticallyor through the class (the less common schemewhere you must pass the instance manuallyin more symbolic termsrecall that normal method call of this forminstance method(args is automatically translated by python into this equivalen...
1,391
person giveraise(selfpercent bonusif __name__ ='__main__'bob person('bob smith'sue person('sue jones'job='dev'pay= print(bobprint(sueprint(bob lastname()sue lastname()sue giveraise print(suetom manager('tom jones''mgr' tom giveraise print(tom lastname()print(tomredefine at this level call person' version make manager__...
1,392
python code because of these downsidesthis book prefers to call superclasses by explicit name instead of superrecommends the same policy for newcomersand defers presenting super until it' usually best judged after you learn the simplerand generally more traditional and "pythonicways of achieving the same goalsespeciall...
1,393
is at the heart of python' flexibility passing any of our three objects to function that calls giveraise methodfor examplewould have the same effectthe appropriate version would be run automaticallydepending on which type of object was passed on the other handprinting runs the same __repr__ for all three objectsbecause...
1,394
eraise operation without subclassingbut none of the other options yield code as optimal as oursalthough we could have simply coded manager from scratch as newindependent codewe would have had to reimplement all the behaviors in person that are the same for managers although we could have simply changed the existing per...
1,395
self pay pay def lastname(self)return self name split()[- def giveraise(selfpercent)self pay int(self pay ( percent)def __repr__(self)return '[person% % ](self nameself payclass manager(person)def __init__(selfnamepay)person __init__(selfname'mgr'paydef giveraise(selfpercentbonus )person giveraise(selfpercent bonusrede...
1,396
in this complete formand despite their relatively small sizesour classes capture nearly all the important concepts in python' oop machineryinstance creation--filling out instance attributes behavior methods--encapsulating logic in class' methods operator overloading--providing behavior for built-in operations like prin...
1,397
covered in full in but its basic usage is simple enough to leverage here by combining these toolsthe giveraise method here still achieves customizationby changing the argument passed along to the embedded object in effectmanager becomes controller layer that passes calls down to the embedded objectrather than up to sup...
1,398
book' examples doesfile person-department py aggregate embedded objects into composite class personsame class manager(person)same class departmentdef __init__(self*args)self members list(argsdef addmember(selfperson)self members append(persondef giveraises(selfpercent)for person in self membersperson giveraise(percentd...
1,399
scripts is often natural next step--and the topic of the next section catching built-in attributes in an implementation notein python --and in when ' "new styleclasses are enabled--the alternative delegation-based manager class of the file person-composite py that we coded in this will not be able to intercept and dele...