id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
4,500 | (continued from previous page @property method-name should be same as attribute 'radiushere def radius(self)return self _radius _radius can be changed with other name return self diameter/ _radius can be changed with other name @radius setter def radius(selfval)'valshould be float or int if not isinstance(val(floatint)... |
4,501 | from pythonic import ring( __dict__ dictionary contains 'diameternot 'radius{'date''''metal''copper''diameter' 'price' 'quantity' radius radius is still accessbile area(area is working fine diameter diameter is accessbile next verify the output for the 'box pyfile again from box import box diameter_init( area(area is w... |
4,502 | decorator and descriptors decorators decorator is function that creates wrapper around another function this wrapper adds some additional functionality to existing code in this tutorialvarious types of decorators are discussed function inside the function and decorator following is the example of function inside the fu... |
4,503 | another nice way of writing above code is shown below here (*args and **kwargsare usedwhich takes all the arguments and keyword arguments of the function funcex py def addone(myfunc)def addoneinside(*args**kwargs)print("adding one"return myfunc(*args**kwargs return addoneinside def subthree( )return result addone(subth... |
4,504 | in this sectionwe saw the basics of the decoratorwhich we will be used in this tutorial decorator without arguments in following codedecorator takes function as the input and print the name of the function and return the function debugex py def printname(func)func is the function to be wrapped def pn(*args**kwargs)prin... |
4,505 | (continued from previous pagewrap is used to exchange metadata between functions @wraps(funcdef pn(*args**kwargs)print(func __name__return func(*args**kwargsreturn pn if we execute the mathex py againit will show the help features again note@wraps exchanges the metadata between the functions as shown in above example d... |
4,506 | error butabove code will generate error if we do not pass the argument to the decorator as shown belowmathex py from debugex import printname @printname def add num(xy)'''add two numbers''return( +yprint(add num( )help(add numfollowing error will be generate after running the codepython mathex py traceback (most recent... |
4,507 | (continued from previous page'''add two numbers''return( + @printname def diff num(xy)'''subtract two integers only''return( -yprint(add num( )print(diff num( )help(add numnext execute the codepython mathex py **add num diff num - dry decorator with arguments in previous codewe repeated the same code two time for creat... |
4,508 | python mathex py **add num diff num - partial function is required becausewhen we pass argument to the decorator @printname(prifix='**')then decorator will not find any function argument at first placehence return func(*arg**kwargswill generate error as there is no 'functo solve this problempartial is used which return... |
4,509 | (continued from previous page class method decorator at time : : note thatwe need to instantiate the instance mehtod decorator before using it as shown at line whereas class decorator can be used as classname decoratorname conclusion in this sectionwe saw the relation between 'function inside the functionand decorator ... |
4,510 | (continued from previous pageself side side @property def area(self)"""calculate the area of the square""return self side * name for setter and deleter ( @areamust be same as the method for which @property is used area here @area setter def area(selfvalue)""do not allow set area directly""print("can not set area"@area ... |
4,511 | square py def nested_property(func)""nest gettersetter and deleter""names func(names['doc'func __doc__ return property(**namesclass square(object)"" square using property with decorator""def __init__(selfside)self side side @nested_property def area()"""calculate the area of the square""def fget(self)""calculate area "... |
4,512 | (continued from previous pageprint("data descriptor __set__"tryself value value upper(except attributeerrorself value value def __delete__(selfinstance)print("can not delete"class (object)attr datadescriptor( datadescriptor(print( value (print( attrdata descriptor __get__ attr is equivalent to below code print(type(a__... |
4,513 | non-data descriptor non-data descriptor stores the assigned values in the dictionary as shown belownon_data_descriptor py class nondatadescriptor(object)""descriptor example ""def __init__(self)self value def __get__(selfinstancecls)print("non-data descriptor __get__"return self value class (object)attr nondatadescript... |
4,514 | notedescriptors can not be invoked if __getattribute__ method is used in the class as shown in above example we need to find some other ways in such cases use more than one instance for testing following is the good examplewhich shows that test must be performed on more than one object of classes as following codewill ... |
4,515 | (continued from previous pageself value value class number(object)""sample class that uses positivevalueonly descriptor""value positivevalueonly(test number(print(test value test value print(test value test value - valueerroronly positive values can be used passing arguments to decorator in previous codesno arguments w... |
4,516 | notein above examplelook for the pricenz classwhere init function takes two arguments and one of which is used by descriptor using 'instance netcommand furtherinit function in class total need one argument taxratewhich is passed by individual class which creating the object of the descriptor conclusion in this sectionw... |
4,517 | more examples this contains several examples of different topics which we learned in previous generalized attribute validation in this 'functions''@property''decoratorsand 'descriptorsare described alsothese techniques are used together in final example for attribute validation attribute validation is defined in sectio... |
4,518 | (continued from previous page intadd addintex( , print("intadd ="intadd adding stringsundesired result attribute validation is used for avoiding such errors stradd addintex("meher ""krishna"print("stradd ="straddmeher krishna keyword argument in listing 'addkeywordarg( * )is python featurein which all the arguments aft... |
4,519 | in listing lines - are used to verify the type of input variable 'xline checks whether the input is integer or notif it is not integer that error will be raised by line as shown in lines - similarlylines - are used to verify the type of variable 'ylisting input validation addintvalidation py def addintvalidation( :int*... |
4,520 | warningin the listingwe can see that help function is not working properly now as shown in listing alsodecorator removes the metaclass features 'annotationwill not workas shown in line listing decorator applied to function #addintdecorator py from funcnamedecorator import funcnamedecorator @funcnamedecorator def addint... |
4,521 | listing help features are visible again addintdecoratorfunctool py from funcnamedecoratorfunctool import funcnamedecoratorfunctool @funcnamedecoratorfunctool def addintdecorator( :int* :int-int'''add two variables (xy)xintegerpostional argument yintegerkeyword argument returntypeinteger ''return ( + intadd=addintdecora... |
4,522 | (continued from previous page self length is used in below linesbut length is not initialized by __init__initialization is done by setter at lines due to @property at line also value is displayed by getter (@propetyat line - whereas `widthis get and set as simple python code and without validation def __init__(selfleng... |
4,523 | explanation listing hereclass integer is used to verify the type of the attributes using '__get__and '__set__at lines and respectively the class 'rectis calling the class 'integerat lines and the name of the attribute is passed in these lineswhose values are set by the integer class in the form of dictionaries at line ... |
4,524 | the name of the attribute along with it' valid type then the decorator (lines - )extracts the 'key-valuepairs 'parameter-expected]_type(see line and pass these to descriptor 'typecheckthrough line if type is not validdescriptor will raise errorotherwise it will set the values to the variables finallythese set values wi... |
4,525 | inheritance with super in this sectioninheritance is discussed using super command in most languagesthe super method calls the parent classwhereas in python it is slightly different it consider the child before parentas shown in this section super child before parent lets understand super with the help of an example fi... |
4,526 | wheatdough py from pizza import pizzadoughfactory class wheatdoughfactory(doughfactory)def get_dough(self)return("wheat floor dough"class wheatpizza(pizzawheatdoughfactory)pass if __name__ ='__main__'wheatpizza(order_pizza('sausage''mushroom'notein pythoninheritance chain is not determine by the parent classbut by the ... |
4,527 | in the same waythe other functions of parent class can be called in following codeprintclass method of parent class is used by child class printclass py class (object)def printclassname(self)print(self __class__ __name__class ( )def printname(self)super(printclassname( ( printclassname( ( printclassname( notein above c... |
4,528 | #multipleinheritance py class (object)def __init__(self)print(" "class (object)def __init__(self)print(" "class (ab)def __init__(self) __init__(selfb __init__(selfself is required ( correct solution following is the another solution of the problemwhere super(function is added in both the classes note thatthe super(is a... |
4,529 | solution this is the first solution__init__ function of two classes are invoked explicitly the only problem here is that the solution does not depend on the order of inheritancebut on the order of invocationi if we exchange the lines and the solution will change mathproblem py class plus (object)def __init__(selfvalue)... |
4,530 | (continued from previous pages solution( print( valuemultiply reached plus reached typeerrorobject __init__(takes no parameters solution to solve the abovewe need to create another classand inherit it in classes plus and multiply as belowin below codemathclass is createdwhose init function takes one argument sincemathc... |
4,531 | (continued from previous pageclass solution(multiply plus method resolution ordersolution multiply plus mathclass builtins object conclusion in this sectionwe saw the functionality of the super(function it is shown that super(consider the child class first and then parent classes in the order of inheritance alsohelp co... |
4,532 | generatorex py def rxmsg()while trueitem yield print("message "itemmsg rxmsg(print(msgnext(msgsend resumes the execution and "sendsa value into the generator function msg send("hello"msg send("world"send and receive values both send and receive message can be combined together in generator alsogenerator can be closedan... |
4,533 | (continued from previous pagemsg rxmsg(next(msgm msg send("hello"print( message ackhello next(msgtraceback (most recent call last)file "rectangle py"line in next(msgstopiterationthanks msg send("world"print( 'yield fromcommand when yield from is usedit treats the supplied expression as subiterator all values produced b... |
4,534 | unix commands introduction in this we will implement some of the unix commands using 'python 'argparsethe 'argparsemodule is command line interface we will use 'argparsemodule to read the values from the terminal for more detailsplease see the online documentation of the module listing 'argpasemodule argparse_ex py imp... |
4,535 | (continued from previous page action='store_const'const=suminbuilt method 'sumto add the values of list help='sum of integers args parser parse_args(save arguments in args if --sum is in command if args accumulatesum args accumulate(args integersprint("sum ="sum if '- or --productis in command if args multiply !noneif ... |
4,536 | find command details create some files and folders inside directory next go to the directory and run following commands we have following files and folder in the current directorytree box py contributor py csv_format csv datamine py data txt expansion py expansion txt mathematician py methodex py price csv price csv pr... |
4,537 | (continued from previous page(show all directories which contains 'xin itfind -name "* *-type /unix_commands (show all files which contains 'xin itfind -name "* *-type /box py /data txt /expansion py /expansion txt /methodex py /text_format txt /unix_commands/argparse_ex py /unix_commands/file txt /unix_commands/file t... |
4,538 | (continued from previous page files [ for in iterdir(if is_file()for in filesprint( directories in current folder print("\ "directory [ for in iterdir(if is_dir()print("directories in current folder:"for in directoryprint(dbelow is the output for above codepython find_ex py all files and folders in current directoryarg... |
4,539 | (continued from previous page args parser parse_args(save arguments in args loc path(args location[ ] items=[for in loc rglob(args name)if args type ="dand is_dir()items append(lelif args type ="fand is_file()items append(lelif args type ="all"items append( print output for in itemsprint( (show files which starts with ... |
4,540 | (continued from previous pagepython find_ex py --type "df folder (read tfrom different locationpython find_ex py /folder --name " *python find_ex py / --name " * /tiger txt python find_ex py --name " */text_format txt /unix_commands/ /tiger txt grep "grepcommand is used to find the pattern in the filee in below code 'd... |
4,541 | cat in this sectionwe will implement the command 'catof unix we will write code to read the name of the files from the command line first create few files 'file txtand 'file txtetc and add some contents to it now read these files as shown belowwhich emulates the functionality of 'unix' cat command'listing read files fr... |
4,542 | (continued from previous page dog nudged cat duck is sleeping notetry both commands without '-nas well run below command to see more functionalities of 'catcommandand try to add some of those to 'cat pyman cat cat |
4,543 | caffe installation in ubuntu prerequisite for gpu supportwe need to install cuda as well ubuntu library installation sudo apt-get install - --force-yes build-essential autoconf libtool libopenblas-dev libgflags-dev '-libgoogle-glog-dev libopencv-dev protobuf-compiler libleveldb-dev liblmdb-dev libhdf -dev libsnappy'-de... |
4,544 | by mark lutz copyright ( mark lutz all rights reserved printed in the united states of america published by 'reilly mediainc gravenstein highway northsebastopolca 'reilly books may be purchased for educationalbusinessor sales promotional use online editions are also available for most titles (corporate/institutional sa... |
4,545 | preface xxiii part the beginning sneak preview "programming pythonthe short storythe task step representing records using lists using dictionaries step storing records persistently using formatted files using pickle files using per-record pickle files using shelves step stepping up to oop using classes adding behavior ... |
4,546 | using query strings and urllib formatting reply text web-based shelve interface the end of the demo part ii system programming system tools "the os path to knowledgewhy python herethe next five system scripting overview python system modules module documentation sources paging documentation strings custom paging script... |
4,547 | parsing command-line arguments shell environment variables fetching shell variables changing shell variables shell variable fine pointsparentsputenvand getenv standard streams redirecting streams to files and programs redirected streams and user interaction redirecting streams to python objects the io stringio and io b... |
4,548 | interprocess communication anonymous pipes named pipes (fifossocketsa first look signals the multiprocessing module why multiprocessingthe basicsprocesses and locks ipc toolspipesshared memoryand queues starting independent programs and much more why multiprocessingthe conclusion other ways to start programs the os spa... |
4,549 | greps and globs and finds rolling your own find module cleaning up bytecode files python tree searcher visitorwalking directories "++editing files in directory trees (visitorglobal replacements in directory trees (visitorcounting source code lines (visitorrecoding copies with classes (visitorother visitor examples (ext... |
4,550 | lambda callback handlers deferring calls with lambdas and object references callback scope issues bound method callback handlers callable class object callback handlers other tkinter callback protocols binding events adding multiple widgets widget resizing revisitedclipping attaching widgets to frames layoutpacking ord... |
4,551 | scales (slidersrunning gui code three ways attaching frames independent windows running programs images fun with buttons and pictures viewing and processing images with pil pil basics displaying other image types with pil creating image thumbnails with pil tkinter tourpart "on today' menuspamspamand spammenus top-level... |
4,552 | simple animation techniques other animation topics the end of the tour other widgets and options gui coding techniques "building better mousetrapguimixincommon tool mixin classes widget builder functions mixin utility classes guimakerautomating menus and toolbars subclass protocols guimaker classes guimaker self-test b... |
4,553 | pyphotoan image viewer and resizer running pyphoto pyphoto source code pyviewan image and notes slideshow running pyview pyview source code pydrawpainting and moving graphics running pydraw pydraw source code pyclockan analog/digital clock widget quick geometry lesson running pyclock pyclock source code pytoea tic-tac-... |
4,554 | stream redirection utility simple python file server running the file server and clients adding user-interface frontend client-side scripting "socket to me!ftptransferring files over the net transferring files with ftplib using urllib to download files ftp get and put utilities adding user interface transferring direct... |
4,555 | self-test script updating the pymail console client nntpaccessing newsgroups httpaccessing websites the urllib package revisited other urllib interfaces other client-side scripting options the pymailgui client "use the sourcelukesource code modules and size why pymailguirunning pymailgui presentation strategy major pym... |
4,556 | pymailguihelpuser help text and display altconfigsconfiguring for multiple accounts ideas for improvement server-side scripting "ohwhat tangled web we weavewhat' server-side cgi scriptthe script behind the curtain writing cgi scripts in python running server-side examples web server options running local web server the... |
4,557 | transferring files to clients and servers displaying arbitrary server files on the client uploading client files to the server more than one way to push bits over the net the pymailcgi server "things to do when visiting chicagothe pymailcgi website implementation overview new in this fourth edition (version new in the ... |
4,558 | databases and persistence "give me an order of persistencebut hold the picklespersistence options in python dbm files using dbm files dbm detailsfilesportabilityand close pickled objects using object pickling pickling in action pickle detailsprotocolsbinary modesand _pickle shelve files using shelves storing built-in o... |
4,559 | timing the improvements implementing sets built-in options set functions set classes optimizationmoving sets to dictionaries adding relational algebra to sets (externalsubclassing built-in types binary search trees built-in options implementing binary trees trees with both keys and values graph searching implementing g... |
4,560 | the parser' code adding parse tree interpreter parse tree structure exploring parse trees with the pytree gui parsers versus python pycalca calculator program/object simple calculator gui pycalc-- "realcalculator gui python/ integration " am lost at cextending and embedding extending python in coverview simple extensio... |
4,561 | conclusionpython and the development cycle "that' the end of the booknow here' the meaning of life"something' wrong with the way we program computersthe "gilligan factordoing the right thing the static language build cycle artificial complexities one language does not fit all enter python but what about that bottleneck... |
4,562 | "and now for something completely different this book explores ways to apply the python programming language in common application domains and realistically scaled tasks it' about what you can do with the language once you've mastered its fundamentals this book assumes you are relatively new to each of the application ... |
4,563 | this book is tutorial introduction to using python in common application domains and tasks it teaches how to apply python for system administrationguisand the weband explores its roles in networkingdatabasesfrontend scripting layerstext processingand more although the python language is used along the waythis book' foc... |
4,564 | because of the scopes carved out by the related books just mentionedthis book' scope follows two explicit constraintsit does not cover python language fundamentals it is not intended as language reference the former of these constraints reflects the fact that core language topics are the exclusive domain of learning py... |
4,565 | because the prior versions of this book were widely readhere is quick rundown of some of the most prominent specific changes in this editionits existing material was shortened to allow for new topics the prior edition of this book was also -page volumewhich didn' allow much room for covering new python topics (python '... |
4,566 | 've removed all the instructions for using and running program examples insteadplease consult the readme file in the examples distribution for example usage details moreovermost of the original acknowledgments are gone here because they are redundant with those in learning pythonsince that book is now considered prereq... |
4,567 | todayand those who do already have the skills required to read the larger and more compete example of integration present in the source code of python itself there is still enough to hint at possibilities herebut vast amounts of code have been cutin deference to the better examples you'll find in python' own code the s... |
4,568 | frameworks on the client such as flexsilverlightand pyjamas (generally known today as rich internet applicationsriasculture shift asidethe examples formerly presented in this category were by themselves also insufficient to either teach or do justice to the subject tools rather than including incomplete (and nearly use... |
4,569 | on these subjects other random bits naturallythere were additional smaller changes made along the way for exampletkinter' grid method is used instead of pack for layout of most input formsbecause it yields more consistent layout on platforms where label font sizes don' match up with entry widget height (including on wi... |
4,570 | possible audience in factthat' why the original version of this book later became twowith language basics delegated to learning python moreoverone can make case for distinction between programmerswho must acquire deep software development skillsand scripterswho do not for somea rudimentary knowledge of programming may ... |
4,571 | luckilymany of the / differences that impact this book' presentation are trivial for instancethe tkinter gui toolkitused extensively in this bookis shown under its tkinter name and package structure onlyits tkinter module incarnation is not described this mostly boils down to different import statementsbut only their p... |
4,572 | as book focused on applications instead of core language fundamentalslanguage changes are not always obtrusive here indeedin retrospect the book learning python may have been affected by core language changes more than this book in most cases heremore example changes were probably made in the name of clarity or functio... |
4,573 | some cost in workaround complexity in python unfortunatelyas we'll learn in the email package in python has number of issues related to str/bytes combinations in python for examplethere' no simple way to guess the encoding needed to convert mail bytes returned by the poplib module to the str expected by the email parse... |
4,574 | fallback optionif neither of those links worktry general web search (whichof courseis what most readers will probably try first anyhowwherever it may livethis website (as well as 'reilly'sdescribed in the next sectionis where you can fetch the book examples distribution package--an archive file containing all of the bo... |
4,575 | the book examples package described earlier also includes portable example demo launcher scripts named pydemos and pygadgetswhich provide quick look at some of this book' major guiand web-based examples these scripts and their launcherslocated at the top of the examples treecan be run to self-configure program and modu... |
4,576 | 'reilly networksee the 'reilly website atconventions used in this book the following font conventions are used in this bookitalic used for file and directory namesto emphasize new terms when first introducedand for some comments within code sections constant width used for code listings and to designate modulesmethodso... |
4,577 | 've written since monty pythonpython' namesakefor so many great bits to draw from (more in the next although writing is ultimately solitary taskthe ideas that spring forth owe much to the input of many ' thankful for all the feedback 've been fortunate to receive over the last yearsboth from classes and from readers st... |
4,578 | as discussedthis book won' devote much space to python fundamentalsand we'll defer an abstract discussion of python roles until the conclusionafter you've had chance to see it in action firsthand if you are looking for concise definition of this book' topicthoughtry thispython is general-purposeopen source computer pro... |
4,579 | the beginning this part of the book gets things started by taking us on quick tour that reviews python fundamental prerequisites and introduces some of the most common ways it is applied this kicks things off by using simple example--recording information about people--to briefly introduce some of the major python appl... |
4,580 | sneak preview "programming pythonthe short storyif you are like most peoplewhen you pick up book as large as this oneyou' like to know little about what you're going to be learning before you roll up your sleeves that' what this is for--it provides demonstration of some of the kinds of things you can do with pythonbefo... |
4,581 | aspects of the running example used in this -the characters here are similar in spirit to those in the oop tutorial in that bookand the later class-based examples here are essentially variation on theme despite some redundancyi' revisiting the example here for three reasonsit serves its purpose as review of language fu... |
4,582 | (my apologies if you really are bob or suegenerically or otherwise*each record is list of four propertiesnameagepayand job fields to access these fieldswe simply index by positionthe result is in parentheses here because it is tuple of two resultsbob[ ]sue[ ('bob smith' fetch namepay processing records is easy with thi... |
4,583 | of coursewhat we've really coded so far is just two variablesnot databaseto collect bob and sue into unitwe might simply stuff them into another listpeople [bobsuefor person in peopleprint(personreference in list of lists ['bob smith' 'software'['sue jones' 'hardware'now the people list represents our database we can f... |
4,584 | every time we want to extract last name or give raisewe'll have to repeat the kinds of code we just typedthat could become problem if we ever change the way those operations work--we may have to update many places in our code we'll address these issues in few moments field labels perhaps more fundamentallyaccessing fie... |
4,585 | sue jones [person[ ][ for person in people['bob smith''sue jones'for person in peopleprint(person[ ][ split()[- ]person[ ][ * collect names get last names give raise smith jones for person in peopleprint(person[ ]['pay' ['pay' all we've really done here is add an extra level of positional indexing to do betterwe might ... |
4,586 | the list-based record representations in the prior section workthough not without some cost in terms of performance required to search for field names (assuming you need to care about milliseconds and suchbut if you already know some pythonyou also know that there are more efficient and convenient ways to associate pro... |
4,587 | names ['name''age''pay''job'values ['sue jones' 'hdw'list(zip(namesvalues)[('name''sue jones')('age' )('pay' )('job''hdw')sue dict(zip(namesvalues)sue {'job''hdw''pay' 'age' 'name''sue jones'we can even make dictionaries from sequence of key values and an optional starting value for all the keys (handy to initialize an... |
4,588 | can even approach the utility of sql queries herealbeit operating on in-memory objects[rec['name'for rec in people if rec['age'> ['sue jones'sql-ish query [(rec['age'* if rec['age'> else rec['age']for rec in people[ (rec['name'for rec in people if rec['age'> next( 'sue jonesg ((rec['age'* if rec['age'> else rec['age']f... |
4,589 | deepbob ['name'{'last''smith''first''bob'bob ['name']['last''smithbob ['pay'][ bob' full name bob' last name bob' upper pay the name field is another dictionary hereso instead of splitting up stringwe simply index to fetch the last name moreoverpeople can have many jobsas well as minimum and maximum pay limits in factp... |
4,590 | it in loop--we get to bob' name immediately by indexing on key bob this really is dictionary of dictionariesthough you won' see all the gory details unless you display the database all at once (the python pprint pretty-printer module can help with legibility here)db {'bob'{'pay' 'job''dev''age' 'name''bob smith'}'sue'{... |
4,591 | ['bob smith''sue jones'and to add new recordsimply assign it to new keythis is just dictionaryafter alldb['tom'dict(name='tom'age= job=nonepay= db['tom'{'pay' 'job'none'age' 'name''tom'db['tom']['name''tomlist(db keys()['bob''sue''tom'len(db [rec['age'for rec in db values()[ [rec['name'for rec in db values(if rec['age'... |
4,592 | initialize data to be stored in filespicklesshelves records bob {'name''bob smith''age' 'pay' 'job''dev'sue {'name''sue jones''age' 'pay' 'job''hdw'tom {'name''tom''age' 'pay' 'job'nonedatabase db {db['bob'bob db['sue'sue db['tom'tom if __name__ ='__main__'when run as script for key in dbprint(key'=>\ 'db[key]as usualt... |
4,593 | the source file resides in the examples package per the example - listing label shown earlierthis script' full filename is pp \preview\initdata py in the examples tree we'll use these conventions throughout the booksee the preface for more on getting the examples if you wish to work along occasionally give more of the ... |
4,594 | ""save in-memory database object to file with custom formattingassume 'endrec ''enddb 'and '=>are not used in the dataassume db is dict of dictwarningeval can be dangerous it runs strings as codecould also eval(record dict all at oncecould also dbfile write(key '\ 'vs print(keyfile=dbfile)""dbfilename 'people-fileenddb... |
4,595 | directory)\pp \previewpython make_db_file py \pp \previewpython for line in open('people-file')print(lineend=''bob job=>'devpay=> age=> name=>'bob smithendrec sue job=>'hdwpay=> age=> name=>'sue jonesendrec tom job=>none pay=> age=> name=>'tomendrec enddb this file is simply our database' content with added formatting ... |
4,596 | from make_db_file import loaddbasestoredbase db loaddbase(db['sue']['pay'* db['tom']['name''tom tomstoredbase(dbhere are the dump script and the update script in action at system command lineboth sue' pay and tom' name change between script runs the main point to notice is that the data stays around after each script e... |
4,597 | too perhaps worst of allthe formatted text file scheme is already complex without being generalit is tied to the dictionary-of-dictionaries structureand it can' handle anything else without being greatly expanded it would be nice if general tool existed that could translate any sort of python data to format that could ... |
4,598 | \pp \previewpython dump_db_pickle py bob ={'pay' 'job''dev''age' 'name''bob smith'sue ={'pay' 'job''hdw''age' 'name''sue jones'tom ={'pay' 'job'none'age' 'name''tom'sue jones updating with pickle file is similar to manually formatted fileexcept that python is doing all of the formatting work for us example - shows how ... |
4,599 | for instanceallows us to ship pickled python objects across network and provides an alternative to larger protocols such as soap and xml-rpc using per-record pickle files as mentioned earlierone potential disadvantage of this section' examples so far is that they may become slow for very large databasesbecause the enti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.