id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
1,700 | finally run traceback (most recent call last)file "except-finally py"line in func(file "except-finally py"line in raise def raise ()raise syntaxerror syntaxerrornone as we saw in as of python except and finally clauses can be mixed in the same try statement thisalong with multiple except clause supportmakes some of the... |
1,701 | loop loop loop loop continuing if you change the raise in this to breakyou'll get an infinite loopbecause you'll break only out of the most deeply nested for loopand wind up in the second-level loop nesting the code would then print "loop and start the for again also notice that variable is still what it was after the ... |
1,702 | warnings functions can signal conditions with raise user-defined exceptions can also signal nonerror conditions for instancea search routine can be coded to raise an exception when match is found instead of returning status flag for the caller to interpret in the followingthe try/except/else exception handler does the ... |
1,703 | we encountered examples in this category in as summarythoughexception processing tools are also commonly used to ensure that system resources are finalizedregardless of whether an error occurs during processing or not for examplesome servers require connections to be closed in order to terminate session similarlyoutput... |
1,704 | you can also make use of exception handlers to replace python' default top-level exception-handling behavior by wrapping an entire program (or call to itin an outer try in your top-level codeyou can catch any exception that may occur while your program runsthereby subverting the default program termination in the follo... |
1,705 | is left abstract in this examplebecause an uncaught exception in test case would normally kill this test driveryou need to wrap test case calls in try if you want to continue the testing process after test fails the empty except catches any uncaught exception generated by test case as usualand it uses sys exc_info to l... |
1,706 | instance __class__ is the exception class as we've seenusing exception for the general exception name here would catch all nonexit exceptionssimilar to an empty except but less extremeand still giving access to the exception instance and its class even sousing the instance object' interfaces and polymorphism is often b... |
1,707 | topicsconsult other reference resources and manuals version skew notein python xthe older tools sys exc_type and sys exc_value still work to fetch the most recent exception type and valuebut they can manage only singleglobal exception for the entire process these two names have been removed in python the newer and pref... |
1,708 | and you reduce the amount of code within the function the types of programs you write will probably influence the amount of exception handling you code as well serversfor instancemust generally keep running persistently and so will likely require try statements to catch and recover from exceptions inprocess testing pro... |
1,709 | def bye()sys exit( trybye(exceptprint('got it'print('continuing 'crucial errorabort nowoops--we ignored the exit python exiter py got it continuing you simply might not expect all the kinds of exceptions that could occur during an operation using the built-in exception classes of the prior can help in this particular c... |
1,710 | and exception catchers are handybut potentially error-prone in the last examplefor instanceyou would be better off saying except keyerrorto make your intentions explicit and avoid intercepting unrelated events in simpler scriptsthe potential for problems might not be significant enough to outweigh the convenience of ca... |
1,711 | describe in moment in terms of the essentialsthoughthe python story--and this book' main journey--is now complete along the wayyou've seen just about everything there is to see in the language itselfand in enough depth to apply to most of the code you are likely to encounter in the open source "wild you've studied buil... |
1,712 | most of the examples in this book have been fairly small and self-contained they were written that way on purposeto help you master the basics but now that you know all about the core languageit' time to start learning how to use python' built-in and third-party interfaces to do real work in practicepython programs can... |
1,713 | tools the firstpyunit (called unittest in the library manual)provides an objectoriented class framework for specifying and customizing test cases and expected results it mimics the junit framework for java this is sophisticated class-based unit testing systemsee the python library manual for details doctest the doctest... |
1,714 | to profiling long-running programs debuggers we also discussed debugging options in (see its sidebar "debugging python codeon page as reviewmost development ides for python support gui-based debuggingand the python standard library also includes source code debugger module called pdb this module provides command-line i... |
1,715 | and to be deployed in because this provides very modest performance boosthoweverit is not commonly used except to remove debugging code as last resortyou can also move parts of your program to compiled language such as to boost performance see the book programming python and the python standard manuals for more on exte... |
1,716 | than advanced--and to someesoteric--language features on the other handif you do need to care about things like unicode or binary datahave to deal with api-building tools such as descriptorsdecoratorsand metaclassesor just want to dig bit further in generalthe next part of the book will help you get started the larger ... |
1,717 | statement to catch the error what happens if you change oops to raise keyerror instead of an indexerrorwhere do the names keyerror and indexerror come from(hintrecall that all unqualified names generally come from one of four scopes exception objects and lists change the oops function you just wrote to raise an excepti... |
1,718 | advanced topics |
1,719 | unicode and byte strings so farour exploration of strings in this book has been deliberately incomplete ' types preview briefly introduced python' unicode strings and files without giving many detailsand the strings in the core types part of this book (deliberately limited its scope to the subset of string topics that ... |
1,720 | delve into the worlds of unicode encodings or binary data for some readers' preview may sufficeand others may wish to file this away for future reference if you ever need to care about processing either of thesethoughyou'll find that python' string models provide the support you need string changes in one of the most n... |
1,721 | filesdirectoriesnetwork interfacesdatabasespipesjsonxmland even guisunicode may no longer be an optional topic for you in python python ' support for unicode and binary data is also available in xalbeit in different forms although our main focus in this is on string types in xwe'll also explore how ' equivalent support... |
1,722 | through (outside ascii' rangeto special characters one such standardknown as the latin- character setis widely used in western europe in latin- character codes above are assigned to accented and otherwise special characters the character assigned to byte value for exampleis specially marked non-ascii character xc chr( ... |
1,723 | (zero valuebytes that can cause problems for libraries and networking because their encodingscharacter maps assign characters to the same codes for compatibilityascii is subset of both latin- and utf- that isa valid ascii character string is also valid latin- and utf- -encoded string for exampleevery ascii file is vali... |
1,724 | how python stores strings in memory the prior section' encodings really only apply when text is stored or transferred externallyin files and other mediums in memorypython always stores decoded text strings in an encoding-neutral formatwhich may or may not use multiple bytes for each character all text processing occurs... |
1,725 | memoryand its characters may not fit in bytes anyhow text size as we saw by example in under unicode single character does not necessarily map directly to single byteeither when encoded in file or when stored in memory even characters in simple -bit ascii text may not map to bytes --utf- uses multiple bytes per charact... |
1,726 | all three string types in support similar operation setsbut they have different roles the main goal behind this change in was to merge the normal and unicode string types of into single string type that supports both simple and unicode textdevelopers wanted to remove the string dichotomy and make unicode processing mor... |
1,727 | str or bytes although python and offer much the same functionalitythey package it differently in factthe mapping from to string types is not completely direct- ' str equates to both str and bytes in xand ' str equates to both str and unicode in moreoverthe mutability of ' bytearray is unique in practicethoughthis asymm... |
1,728 | outputhtmlemail contentor csv or xml filesyou'll probably want to use str and text-mode files notice that the mode string argument to built-in function open (its second argumentbecomes fairly crucial in python --its content not only specifies file processing modebut also implies python object type by adding to the mode... |
1,729 | python string objects originate when you call built-in function such as str or bytesread file created by calling open (described in the next section)or code literal syntax in your script for the lattera new literal formb'xxx(and equivalentlyb'xxx'is used to create bytes objects in xand you may create bytearray objects ... |
1,730 | python ' 'xxxand 'xxxunicode string literal forms were removed in python because they were deemed redundant--normal strings are unicode in to aid both forward and backward compatibilitythoughthey are available again as of where they are treated as normal str stringsc:\codec:\python \python 'spamtype(uu 'spamu[ 'slist( ... |
1,731 | 'spamu[ 'slist( [ ' ' ' ' ' ' ' 'as we sawfor compatibility this form works in and later toobut it simply makes normal str there (the is ignoredstring type conversions although python allowed str and unicode type objects to be mixed in expressions (when the str contained only -bit ascii text) draws much sharper distinc... |
1,732 | sys platform 'win sys getdefaultencoding('utf- underlying platform default encoding for str here bytes(stypeerrorstring argument without an encoding str( " 'spam'len(str( ) len(str(bencoding='ascii') str without encoding print stringnot conversionuse encoding to convert to str when in doubtpass in an encoding name argu... |
1,733 | chr( ' stands for character 'xs 'xyza unicode string of ascii text 'xyzlen(sthree characters long [ord(cfor in sthree characters with integer ordinal values [ normal -bit ascii text like this is represented with one character per byte under each of the unicode encoding schemes described earlier in this encode('ascii'va... |
1,734 | outside the -bit range of asciibut we can embed them in str objects because str supports unicodechr( xc 'achr( xe ' xc xe characters outside ascii' range '\xc \xe 'aesingle -bit value hex escapestwo digits '\ \ 'aelen( -bit unicode escapesfour digits each two characters long (not number of bytes!note that in unicode te... |
1,735 | are written to filethe raw bytes shown here for encoding results are what is actually stored on the file for the encoding types givens encode('latin- ' '\xc \xe byte per character when encoded encode('utf- ' '\xc \ \xc \xa bytes per character when encoded len( encode('latin- ') len( encode('utf- ') bytes in latin- in u... |
1,736 | encode('utf- ' ' \xc \ \xc \xa clen( encode('utf- ') bytes when encoded per latin- bytes when encoded per utf- technically speakingyou can also build unicode strings piecemeal using chr instead of unicode or hex escapesbut this might become tedious for large stringss 'achr( xc 'bchr( xe 'cs 'aabecsome other encodings m... |
1,737 | two cautions here too firstpython allows special characters to be coded with both hex and unicode escapes in str stringsbut only with hex escapes in bytes strings --unicode escape sequences are silently taken verbatim in bytes literalsnot as escapes in factbytes must be decoded to str strings to print their non-ascii c... |
1,738 | raw bytes do not correspond to utf- unicodedecodeerror'utf codec can' decode bytes in position - both these constraints make sense if you remember that byte strings hold bytes-based datanot decoded unicode code point ordinalswhile they may contain the encoded form of textdecoded code point values don' quite apply to by... |
1,739 | stress python unicode support in this because it' new but now that 've shown you the basics of unicode strings in xi need to explain more fully how you can do much the same in xthough the tools differ unicode is available in python xbut is distinct type from strsupports most of the same operationsand allows mixing of n... |
1,740 | ' \xc \ \xc \xa cencode per utf- multibyte non-ascii characters can be coded with hex or unicode escapes in string literals in xjust as in howeveras with bytes in xthe "\ and "\ escapes are recognized only for unicode strings in xnot -bit str strings--againthese are used to give the values of decoded unicode ordinal in... |
1,741 | can' mix in if str is non-asciiu ' \xc \xe cs unicodedecodeerror'asciicodec can' decode byte xc in position ordinal not in range( 'abcu 'abca\xc \xe cprint 'abcu abcaabec can mix only if str is all -bit ascii decode('latin- ' ' \xc \xe ca\xc \xe cprint decode('latin- ' aabecaabec manual conversion may be required in to... |
1,742 | the text of your script filespython uses the utf- encoding by defaultbut it allows you to change this to support arbitrary character sets by including comment that names your desired encoding the comment must be of this form and must appear as either the first or second line in your script in either python or -*codingl... |
1,743 | file declarationssee the currency symbols used in the money formatting example of as well as its associated file in this book' examples packageformats_currency py the latter requires source-file declaration to be usable by pythonbecause it embeds non-ascii currency symbol characters this example also illustrates the po... |
1,744 | shortened for brevity) 'spamb find( 'pa' bbytes literal replace( 'pa' 'xy' 'sxymbytes methods expect bytes arguments split( 'pa'[ ' ' ' 'bytes methods return bytes results 'spamb[ 'xtypeerror'bytesobject does not support item assignment one notable difference is that string formatting works only on str objects in xnot ... |
1,745 | [ show all the byte' int values [ :] [:- ( 'pam' 'spa'len( 'lmnb'spamlmnb 'spamspamspamspamother ways to make bytes objects so farwe've been mostly making bytes objects with the bliteral syntax we can also create them by calling the bytes constructor with str and an encoding namecalling the bytes constructor with an it... |
1,746 | in the replace call of the section "method callson page we had to pass in two bytes objects--str types won' work there although python automatically converts str to and from unicode when possible ( when the str is -bit ascii text)python requires specific string types in some contexts and expects manual conversions if n... |
1,747 | of text such as asciiwhich can be represented with byte per character (richer unicode text generally requires unicode stringswhich are still immutablethe bytear ray type is also available in python and as back-port from xbut it does not enforce the strict text/binary distinction there that it does in bytearrays in acti... |
1,748 | [ ' '[ bytearray( 'xyam'or index byte string processing bytearray objects borrows from both strings and listssince they are mutable byte strings while the byterrray' methods overlap with both str and bytesit also has many of the list' mutable methods besides named methodsthe __iadd__ and __setitem__ methods in bytearra... |
1,749 | bytearray( 'yamlmno'len( replace('xy''sp'this works in typeerrortype str doesn' support the buffer api replace( 'xy' 'sp'bytearray( 'spamlmno' bytearray( 'xyamlmno' bytearray( 'xyamlmnoxyamlmnoxyamlmnoxyamlmno'python string types summary finallyby way of summarythe following examples demonstrate how bytes and byte arra... |
1,750 | objectstext-mode files interpret file contents according to unicode encoding--either the default for your platformor one whose name you pass in by passing in an encoding name to openyou can force conversions for various types of unicode files textmode files also perform universal line-end translationsby defaultall line... |
1,751 | in python xthere is no major distinction between text and binary files--both accept and return content as str strings the only major difference is that text files automatically map \ end-of-line characters to and from \ \ on windowswhile binary files do not ( ' stringing operations together into one-liners here just fo... |
1,752 | --againa desired result for binary data type requirements and file behavior are the same even if the data we're writing to the binary file is truly binary in nature in the followingfor examplethe "\ is binary zero byte and not printable characterwrite and read truly binary data open('temp''wb'write( ' \ ' open('temp'' ... |
1,753 | in addition to type constraintsfile content can matter in text-mode output files require str instead of bytes for contentso there is no way in to write truly binary data to text-mode file depending on the encoding rulesbytes outside the default character set can sometimes be embedded in normal stringand they can always... |
1,754 | manual encoding as we've already learnedwe can always encode such string to raw bytes according to the target encoding nameencode manually with methods encode('latin- ' ' \xc \xe clen( encode('utf- ' ' \xc \ \xc \xa clen( bytes when encoded as latin- bytes when encoded as utf- file output encoding nowto write our strin... |
1,755 | open('utf data''rb'read( decode('aabecutf- is default decoding mismatches finallykeep in mind that this behavior of files in limits the kind of content you can load as text as suggested in the prior sectionpython really must be able to decode the data in text files into str stringaccording to either the default or pass... |
1,756 | let' make some files with boms to see how this works in practice when you save text file in windows notepadyou can specify its encoding type in drop-down list-simple ascii textutf- or littleor big-endian utf- if two-line text file named spam txt is saved in notepad as the encoding type ansifor instanceit' written as si... |
1,757 | the same patterns generally hold true for output when writing unicode file in python codewe need more explicit encoding name to force the bom in utf- --"utf- does not write (or skipthe bombut "utf- -sigdoesopen('temp txt'' 'encoding='utf- 'write('spam\nspam\ ' open('temp txt''rb'read(no bom 'spam\ \nspam\ \nopen('temp ... |
1,758 | may have to manually write and skip the bom yourself in some scenarios if it is required or present--study the following examples for more bom-making instructionsopen('temp txt'' 'encoding='utf- -be'write('\ufeffspam\nspam\ ' open('spam txt''rb'read( '\xfe\xff\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \nopen('temp txt'' 'encoding='... |
1,759 | ' \xc \xe ccodecs open('utfdata'' 'encoding='utf- 'read( ' \xc \xe cprint codecs open('utfdata'' 'encoding='utf- 'read(aabec reads decode print to view for more unicode detailssee earlier sections of this and python manuals unicode filenames and streams in closingthis section has focused on the encoding and decoding of... |
1,760 | utf- may sometimes be required to print non-ascii textand to display such text in shell windows (possibly in conjunction with code page changes on some windows machinesa script that prints non-ascii filenamesfor examplemay fail unless this setting is made for more background on this subjectsee also "currency symbolsuni... |
1,761 | ( 'bugger all' 'here' 'earth!'bytes substrings in python results are similarbut the unicode type is used for non-ascii textand str handles both -bit and binary textc:\codec:\python \python import re 'bugger all down here on earth! 'bugger all down here on earth!simple text and binary unicode text re match('*down *on *)... |
1,762 | :\codec:\python \python from struct import pack pack('> sh' 'spam' '\ \ \ \ spam\ \ str in ( -bit stringssince bytes has an almost identical interface to that of str in and xthoughmost programmers probably won' need to care--the change is irrelevant to most existing codeespecially since reading from binary file creates... |
1,763 | ( 'spam' accessing bits of parsed integers bin(values[ ]' values[ values[ bin(values[ ' bin(values[ ' bool(values[ true bool(values[ false result of struct unpack can get to bits in ints test first (lowestbit in int bitwise orturn bits on decimal is binary bitwise xoroff if both true test if bit is on test if bit is se... |
1,764 | '\ \ ] \ ( \ \ \ python default protocol= =binary pickle dumps([ ]protocol= '(lp \nl \nal \nal \na ascii protocol but still bytesthis implies that files used to store pickled objects must always be opened in binary mode in python xsince text files use str strings to represent datanot bytes--the dump call simply attempt... |
1,765 | their version-specific defaultsalways use binary-mode files for pickled data--the following works the same in python and ximport pickle pickle dump([ ]open('temp''wb')pickle load(open('temp''rb')[ version neutral and required in because almost all programs let python pickle and unpickle objects automatically and do not... |
1,766 | like xpathfirstwe could run basic pattern matching on the file' textthough this tends to be inaccurate if the text is unpredictable where applicablethe re module we met earlier does the job--its match method looks for match at the start of stringsearch scans ahead for matchand the findall method used here locates all p... |
1,767 | parser parse('mybooks xml'finallythe elementtree system available in the etree package of the standard library can often achieve the same effects as xml dom parsersbut with remarkably less code it' python-specific way to both parse and generate xml textafter parseits api gives access to components of the documentfile e... |
1,768 | regrettablygoing into further xml parsing details is beyond this book' scope if you are interested in text or xml parsingit is covered in more detail in the applicationsfocused follow-up book programming python for more details on restructpickleand xmlas well as the additional impacts of unicode on other library tools ... |
1,769 | convenient tactical tool in such casesand its file objects give you tangible window on your data when neededboth in scripts and interactive mode for more realistically scaled examples of unicode at worki suggest my other book programming python th edition (or laterthat book develops much larger programs than we can her... |
1,770 | why is ascii text considered to be kind of unicode text how large an impact does python ' string types change have on your codetest your knowledgeanswers python has three string typesstr (for unicode textincluding ascii)bytes (for binary data with absolute byte values)and bytearray ( mutable flavor of bytesthe str type... |
1,771 | simply pass the name of the file' encoding to the open built-in in (codecs open(in )data will be decoded per the specified encoding when it is read from the file you can also read in binary mode and manually decode the bytes to string by giving an encoding namebut this involves extra work and is somewhat error-prone fo... |
1,772 | managed attributes this expands on the attribute interception techniques introduced earlierintroduces anotherand employs them in handful of larger examples like everything in this part of the bookthis is classified as an advanced topic and optional readingbecause most applications programmers don' need to care about th... |
1,773 | raise typeerror('cannot fetch name'elsereturn self name transform(def setname(selfvalue)if not valid(value)raise typeerror('cannot change name'elseself name transform(valueperson person(person getname(person setname('value'howeverthis also requires changing all the places where names are used in the entire program-- po... |
1,774 | with arbitrary get and set handler methodsand the basis for other tools such as properties and slots the tools in the first of these bullets are available in all pythons the last three bulletstools are available in python and new-style classes in --they first appeared in python along with many of the other advanced too... |
1,775 | property is created by assigning the result of built-in function to class attributeattribute property(fgetfsetfdeldocnone of this built-in' arguments are requiredand all default to none if not passed for the first threethis none means that the corresponding operation is not supportedand attempting it will raise an attr... |
1,776 | print('-'* sue person('sue jones'print(sue nameprint(person name __doc__runs delname sue inherits property too or help(person nameproperties are available in both and xbut they require new-style object derivation in to work correctly for assignments--add object as superclass here to run this in you can list the supercl... |
1,777 | the example in the prior section simply traces attribute accesses usuallythoughproperties do much more--computing the value of an attribute dynamically when fetchedfor example the following example illustratesclass propsquaredef __init__(selfstart)self value start def getx(self)return self value * def setx(selfvalue)se... |
1,778 | to define function that will run automatically when an attribute is fetchedclass person@property def name(self)rebindsname property(namewhen runthe decorated method is automatically passed to the first argument of the property built-in this is really just alternative syntax for creating property and rebinding the attri... |
1,779 | an alternative way to code properties in this case when it' runthe results are the samec:\codepy - prop-person-deco py fetch bob smith change fetch robert smith remove fetch sue jones name property docs compared to manual assignment of property resultsin this case using decorators to code properties requires just three... |
1,780 | directly unlike propertiesdescriptors are broader in scopeand provide more general tool for instancebecause they are coded as normal classesdescriptors have their own statemay participate in descriptor inheritance hierarchiescan use composition to aggregate objectsand provide natural structure for coding internal metho... |
1,781 | these generally computes value for instance accessand the latter usually returns self if descriptor object access is supported for examplein the following sessionwhen attr is fetchedpython automatically runs the __get__ method of the descriptor class instance to which the subject attr class attribute is assigned in xus... |
1,782 | list( __dict__ keys()[' ' ( get get stored on xhiding ay still inherits descriptor this is the way all instance attribute assignments work in pythonand it allows classes to selectively override class-level defaults in their instances to make descriptor-based attribute read-onlycatch the assignment in the descriptor cla... |
1,783 | use (objectin "name descriptor docsdef __get__(selfinstanceowner)print('fetch 'return instance _name def __set__(selfinstancevalue)print('change 'instance _name value def __delete__(selfinstance)print('remove 'del instance _name class persondef __init__(selfname)self _name name name name(use (objectin bob person('bob s... |
1,784 | also like in the property exampleour descriptor class instance is class attribute and thus is inherited by all instances of the client class and any subclasses if we change the person class in our example to the followingfor instancethe output of our script is the sameclass superdef __init__(selfname)self _name name na... |
1,785 | fetchedclass descsquaredef __init__(selfstart)self value start def __get__(selfinstanceowner)return self value * def __set__(selfinstancevalue)self value value class client descsquare( class client descsquare( each desc has own state on attr fetch on attr assign no delete or docs assign descriptor instance to class att... |
1,786 | use instance state to record data pertaining to descriptor implementation internals--if stored in each instancethere would be multiple varying copies descriptor methods may use either state formbut descriptor state often makes it unnecessary to use special naming conventions to avoid name collisions in the instance for... |
1,787 | instanceinstead of itself cruciallyunlike data stored in the descriptor itselfthis allows for data that can vary per client class instance the descriptor in the following example assumes the instance has an attribute _x attached by the client classand uses it to compute the value of the attribute it representsclass ins... |
1,788 | def __init__(selfdata)self data data def __get__(selfinstanceowner)return '% % (self datainstance datadef __set__(selfinstancevalue)instance data value class clientdef __init__(selfdata)self data data managed descboth('spam' client('eggs' managed 'spameggsi managed 'spami managed 'spamspamshow both data sources change ... |
1,789 | as mentioned earlierproperties and descriptors are strongly related--the property built-in is just convenient way to create descriptor now that you know how both workyou should also be able to see that it' possible to simulate the property built-in with descriptor class like the followingclass propertydef __init__(self... |
1,790 | accessor function and return the property object (self should sufficesince the prop erty built-in already does thiswe'll omit formal coding of this extension here descriptors and slots and more you can also probably now at least in part imagine how descriptors are used to implement python' slots extensioninstance attri... |
1,791 | be cautious when using this method to avoid recursive loops by passing attribute accesses to superclass we met the former of these in it' available for all python versions the latter of these is available for new-style classes in xand for all (implicitly new-styleclasses in these two methods are representatives of set ... |
1,792 | on undefined attribute fetch [obj namedef __getattribute__(selfname)on all attribute fetch [obj namedef __setattr__(selfnamevalue)on all attribute assignment [obj name=valuedef __delattr__(selfname)on all attribute deletion [del obj namein all of theseself is the subject instance object as usualname is the string name ... |
1,793 | assignments in some contexts-- tradeoff described in and mentioned in the context of the case study example we'll explore at the end of this avoiding loops in attribute interception methods these methods are generally straightforward to usetheir only substantially complex aspect is the potential for looping ( recursing... |
1,794 | assignments to higher superclass to avoid loopingjust like __getattribute__ (and per the upcoming notethis scheme is sometimes preferred)def __setattr__(selfnamevalue)object __setattr__(self'other'valueforce higher to avoid me by contrastthoughwe cannot use the __dict__ trick to avoid loops in __getattri bute__def __ge... |
1,795 | def __setattr__(selfattrvalue)print('setattrif attr ='name'attr '_nameself __dict__[attrvalue on [obj any valuedef __delattr__(selfattr)print('delattrif attr ='name'attr '_namedel self __dict__[attron [del obj anybob person('bob smith'print(bob namebob name 'robert smithprint(bob namedel bob name print('-'* sue person(... |
1,796 | assume unknown names are errorsreplace __getattr__ with this def __getattribute__(selfattr)print('getattrif attr ='name'attr '_namereturn object __getattribute__(selfattron [obj anyintercept all names map to internal name avoid looping here when run with this changethe output is similarbut we get an extra __getattri bu... |
1,797 | def __setattr__(selfattrvalue)if attr =' 'attr 'valueself __dict__[attrvalue on all attr assignments attrsquare( attrsquare( instances of class with overloading each has different state information print( xa print( xprint( * * * ( running this code results in the same output that we got earlier when using properties an... |
1,798 | fetch value as welldef __getattribute__(selfattr)if attr =' 'return object __getattribute__(self'value'* of coursethis still incurs call to the superclass methodbut not an additional recursive call before we get there add print calls to these methods to trace how and when they run __getattr__ and __getattribute__ compa... |
1,799 | and must route those it does not manage to the superclass fetcher to avoid loopsc:\codepy - getattr- -getattr py getattr getattr getattr getattr although __getattribute__ can catch more attribute fetches than __getattr__in practice they are often just variations on theme--if attributes are not physically storedthe two ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.