id
int64
0
25.6k
text
stringlengths
0
4.59k
17,900
sys exc_info(function the following read-only attributes are available in traceback objectsattribute description tb_next next level in the stack trace (toward the execution frame where the exception occurredexecution frame object of the current level line number where the exception occurred instruction being executed in the current level tb_frame tb_lineno tb_lasti generator objects generator objects are created when generator function is invoked (see "functions and functional programming" generator function is defined whenever function makes use of the special yield keyword the generator object serves as both an iterator and container for information about the generator function itself the following attributes and methods are availableattribute description code object for the generator function execution frame of the generator function integer indicating whether or not the generator function is currently running next(execute the function until the next yield statement and return the value (this method is called _next_ in python send(valuesends value to generator the passed value is returned by the yield expression in the generator that executes until the next yield expression is encountered send(returns the value passed to yield in this expression close(closes generator by raising generatorexit exception in the generator function this method executes automatically when generator object is garbage-collected throw(exc [,exc_value raises an exception in generator at the point of the [,exc_tb ]]current yield statement exc is the exception typeexc_value is the exception valueand exc_tb is an optional traceback if the resulting exception is caught and handledreturns the value passed to the next yield statement gi_code gi_frame gi_running slice objects slice objects are used to represent slices given in extended slice syntaxsuch as [ : :stride] [ :jn: ]or ai:jslice objects are also created using the built-in slice([ , [,stride]function the following read-only attributes are availablef lib fl ff
17,901
types and objects attribute description start stop step lower bound of the slicenone if omitted upper bound of the slicenone if omitted stride of the slicenone if omitted slice objects also provide single methods indices(lengththis function takes length and returns tuple (start,stop,stridethat indicates how the slice would be applied to sequence of that length here' an examples slice( , indices( indices( slice object represents [ : returns ( , , --[ : returns ( , , --[ : ellipsis object the ellipsis object is used to indicate the presence of an ellipsis in an index lookup [there is single object of this typeaccessed through the built-in name ellipsis it has no attributes and evaluates as true none of python' built-in types make use of ellipsisbut it may be useful if you are trying to build advanced functionality into the indexing operator [on your own objects the following code shows how an ellipsis gets created and passed into the indexing operatorclass example(object)def _getitem_ (self,index)print(indexe example( [ calls _getitem_ (( ellipsis )object behavior and special methods objects in python are generally classified according to their behaviors and the features that they implement for exampleall of the sequence types such as stringslistsand tuples are grouped together merely because they all happen to support common set of sequence operations such as [ ]len( )etc all basic interpreter operations are implemented through special object methods the names of special methods are always preceded and followed by double underscores ( _these methods are automatically triggered by the interpreter as program executes for examplethe operation is mapped to an internal methodx _add_ ( )and an indexing operationx[ ]is mapped to _getitem_ (kthe behavior of each data type depends entirely on the set of special methods that it implements user-defined classes can define new objects that behave like the built-in types simply by supplying an appropriate subset of the special methods described in this section in additionbuilt-in types such as lists and dictionaries can be specialized (via inheritanceby redefining some of the special methods the next few sections describe the special methods associated with different categories of interpreter features object creation and destruction the methods in table createinitializeand destroy instances _new_ (is class method that is called to create an instance the _init_ (method initializes the lib fl ff
17,902
attributes of an object and is called immediately after an object has been newly created the _del_ (method is invoked when an object is about to be destroyed this method is invoked only when an object is no longer in use it' important to note that the statement del only decrements an object' reference count and doesn' necessarily result in call to this function further details about these methods can be found in table special methods for object creation and destruction method description _new_ (cls [,*args [,**kwargs]] class method called to create new instance called to initialize new instance called when an instance is being destroyed _init_ (self [,*args [,**kwargs]] _del_ (selfthe _new_ (and _init_ (methods are used together to create and initialize new instances when an object is created by calling (args)it is translated into the following stepsx _new_ ( ,argsis isinstance( , ) _init_ (argsin user-defined objectsit is rare to define _new_ (or _del_ ( _new_ (is usually only defined in metaclasses or in user-defined objects that happen to inherit from one of the immutable types (integersstringstuplesand so on_ _del_ (is only defined in situations in which there is some kind of critical resource management issuesuch as releasing lock or shutting down connection object string representation the methods in table are used to create various string representations of an object table special methods for object representation method description _format_ (selfformat_speccreates formatted representation _repr_ (selfcreates string representation of an object _str_ (selfcreates simple string representation the _repr_ (and _str_ (methods create simple string representations of an object the _repr_ (method normally returns an expression string that can be evaluated to re-create the object this is also the method responsible for creating the output of values you see when inspecting variables in the interactive interpreter this method is invoked by the built-in repr(function here' an example of using repr(and eval(togethera [ , , , repr(ab eval(screate list '[ ]turns back into list lib fl ff
17,903
types and objects if string expression cannot be createdthe convention is for _repr_ (to return string of the form as shown heref open("foo" repr(fa "the _str_ (method is called by the built-in str(function and by functions related to printing it differs from _repr_ (in that the string it returns can be more concise and informative to the user if this method is undefinedthe _repr_ (method is invoked the _format_ (method is called by the format(function or the format(method of strings the format_spec argument is string containing the format specification this string is the same as the format_spec argument to format(for exampleformat( ,"spec"" is { :spec}format(xcalls _format_ ("spec"calls _format_ ("spec"the syntax of the format specification is arbitrary and can be customized on an objectby-object basis howevera standard syntax is described in object comparison and ordering table shows methods that can be used to perform simple tests on an object the _bool_ (method is used for truth-value testing and should return true or false if undefinedthe _len_ (method is fallback that is invoked to determine truth the _hash_ (method is defined on objects that want to work as keys in dictionary the value returned is an integer that should be identical for two objects that compare as equal furthermoremutable objects should not define this methodany changes to an object will alter the hash value and make it impossible to locate an object on subsequent dictionary lookups table special methods for object testing and hashing method description _bool_ (self_ _hash_ (selfreturns false or true for truth-value testing computes an integer hash index objects can implement one or more of the relational operators (===!=each of these methods takes two arguments and is allowed to return any kind of objectincluding boolean valuea listor any other python type for instancea numerical package might use this to perform an element-wise comparison of two matricesreturning matrix with the results if comparison can' be madethese functions may also raise an exception table shows the special methods for comparison operators table methods for comparisons method result _lt_ (self,other_ _le_ (self,other_ _gt_ (self,other_ _ge_ (self,otherself other self <other self other self >other lib fl ff
17,904
table continued method result _eq_ (self,other_ _ne_ (self,otherself =other self !other it is not necessary for an object to implement all of the operations in table howeverif you want to be able to compare objects using =or use an object as dictionary keythe _eq_ (method should be defined if you want to be able to sort objects or use functions such as min(or max()then _lt_ (must be minimally defined type checking the methods in table can be used to redefine the behavior of the type checking functions isinstance(and issubclass(the most common application of these methods is in defining abstract base classes and interfacesas described in table methods for type checking method result _instancecheck_ (cls,object_ _subclasscheck_ (clssubisinstance(objectclsissubclass(subclsattribute access the methods in table readwriteand delete the attributes of an object using the dot operator and the del operatorrespectively table special methods for attribute access method description returns the attribute self name returns the attribute self name if not found through normal attribute lookup or raise attributeerror _setattr_ (selfnamevaluesets the attribute self name value overrides the default mechanism _delattr_ (selfnamedeletes the attribute self name _getattribute_ (self,name_ _getattr_ (selfnamewhenever an attribute is accessedthe _getattribute_ (method is always invoked if the attribute is locatedit is returned otherwisethe _getattr_ (method is invoked the default behavior of _getattr_ (is to raise an attributeerror exception the _setattr_ (method is always invoked when setting an attributeand the _delattr_ (method is always invoked when deleting an attribute lib fl ff
17,905
types and objects attribute wrapping and descriptors subtle aspect of attribute manipulation is that sometimes the attributes of an object are wrapped with an extra layer of logic that interact with the getsetand delete operations described in the previous section this kind of wrapping is accomplished by creating descriptor object that implements one or more of the methods in table keep in mind that descriptions are optional and rarely need to be defined table special methods for descriptor object method description returns an attribute value or raises attributeerror _set_ (self,instance,valuesets the attribute to value _delete_ (self,instancedeletes the attribute _get_ (self,instance,clsthe _get_ () _set_ ()and _delete_ (methods of descriptor are meant to interact with the default implementation of _getattribute_ () _setattr_ ()and _delattr_ (methods on classes and types this interaction occurs if you place an instance of descriptor object in the body of user-defined class in this caseall access to the descriptor attribute will implicitly invoke the appropriate method on the descriptor object itself typicallydescriptors are used to implement the low-level functionality of the object system including bound and unbound methodsclass methodsstatic methodsand properties further examples appear in sequence and mapping methods the methods in table are used by objects that want to emulate sequence and mapping objects table methods for sequences and mappings method description _len_ (selfreturns the length of self _getitem_ (selfkeyreturns self[key_ _setitem_ (selfkeyvaluesets self[keyvalue _delitem_ (selfkey_ _contains_ (self,objdeletes self[keyreturns true if obj is in selfotherwisereturns false here' an examplea [ , , , , , len(ax [ [ del [ in _len_ ( _getitem_ ( _setitem_ ( , _delitem_ ( _contains_ ( the _len_ method is called by the built-in len(function to return nonnegative length this function also determines truth values unless the _bool_ (method has also been defined lib fl ff
17,906
for manipulating individual itemsthe _getitem_ (method can return an item by key value the key can be any python object but is typically an integer for sequences the _setitem_ (method assigns value to an element the _delitem_ (method is invoked whenever the del operation is applied to single element the _contains_ (method is used to implement the in operator the slicing operations such as [ :jare also implemented using _getitem_ () _setitem_ ()and _delitem_ (howeverfor slicesa special slice object is passed as the key this object has attributes that describe the range of the slice being requested for examplea [ , , , , , [ : [ : [ , , del [ : _getitem_ (slice( , ,none) _setitem_ (slice( , ,none)[ , , ] _delitem_ (slice( , ,none)the slicing features of python are actually more powerful than many programmers realize for examplethe following variations of extended slicing are all supported and might be useful for working with multidimensional data structures such as matrices and arraysa [ : : strided slice (stride= [ : : multidimensional slice [ : : : : multiple dimensions with strides [ : : extended slice assignment del [: :extended slice deletion the general format for each dimension of an extended slice is : [:stride]where stride is optional as with ordinary slicesyou can omit the starting or ending values for each part of slice in additionthe ellipsis (written as is available to denote any number of trailing or leading dimensions in an extended slicea : [ : extended slice access with ellipsis when using extended slicesthe _getitem_ () _setitem_ ()and _delitem_ (methods implement accessmodificationand deletionrespectively howeverinstead of an integerthe value passed to these methods is tuple containing combination of slice or ellipsis objects for examplea [ : : : invokes _getitem_ (as followsa _getitem_ ((slice( , ,none)slice( , , )ellipsis)python stringstuplesand lists currently provide some support for extended sliceswhich is described in special-purpose extensions to pythonespecially those with scientific flavormay provide new types and objects with advanced support for extended slicing operations iteration if an objectobjsupports iterationit must provide methodobj _iter_ ()that returns an iterator object the iterator object iterin turnmust implement single methoditer next((or iter _next_ (in python )that returns the next object or raises stopiteration to signal the end of iteration both of these methods are used by the implementation of the for statement as well as other operations that lib fl ff
17,907
types and objects implicitly perform iteration for examplethe statement for in is carried out by performing steps equivalent to the following_iter _iter_ (while tryx _iter next()(#_iter _next_ (in python except stopiterationbreak do statements in body of for loop mathematical operations table lists special methods that objects must implement to emulate numbers mathematical operations are always evaluated from left to right according the precedence rules described in when an expression such as appearsthe interpreter tries to invoke the method _add_ (ythe special methods beginning with support operations with reversed operands these are invoked only if the left operand doesn' implement the specified operation for exampleif in doesn' support the _add_ (methodthe interpreter tries to invoke the method _radd_ (xtable methods for mathematical operations method result _add_ (self,other_ _sub_ (self,other_ _mul_ (self,other_ _div_ (self,other_ _truediv_ (self,other_ _floordiv_ (self,other_ _mod_ (self,other_ _divmod_ (self,other_ _pow_ (self,other [,modulo]self other self other self other self other (python onlyself other (python self /other self other divmod(self,otherself *otherpow(selfothermoduloself <other self >other self other self other self other other self other self other self other self (python onlyother self (python other /self other self divmod(other,self_ _lshift_ (self,other_ _rshift_ (self,other_ _and_ (self,other_ _or_ (self,other_ _xor_ (self,other_ _radd_ (self,other_ _rsub_ (self,other_ _rmul_ (self,other_ _rdiv_ (self,other_ _rtruediv_ (self,other_ _rfloordiv_ (self,other_ _rmod_ (self,other_ _rdivmod_ (self,otherf lib fl ff
17,908
table continued method result _rpow_ (self,other_ _rlshift_ (self,other_ _rrshift_ (self,otherother *self other <self other >self other self other self other self self +other self -other self *other self /other (python onlyself /other (python self //other self %other self **other self &other self |other self ^other self <<other self >>other -self +self abs(self~self int(selflong(self(python onlyfloat(selfcomplex(self_ _rand_ (self,other_ _ror_ (self,other_ _rxor_ (self,other_ _iadd_ (self,other_ _isub_ (self,other_ _imul_ (self,other_ _idiv_ (self,other_ _itruediv_ (self,other_ _ifloordiv_ (self,other_ _imod_ (self,other_ _ipow_ (self,other_ _iand_ (self,other_ _ior_ (self,other_ _ixor_ (self,other_ _ilshift_ (self,other_ _irshift_ (self,other_ _neg_ (self_ _pos_ (self_ _abs_ (self_ _invert_ (self_ _int_ (self_ _long_ (self_ _float_ (self_ _complex_ (selfthe methods _iadd_ () _isub_ ()and so forth are used to support in-place arithmetic operators such as += and -= (also known as augmented assignmenta distinction is made between these operators and the standard arithmetic methods because the implementation of the in-place operators might be able to provide certain customizations such as performance optimizations for instanceif the self parameter is not sharedthe value of an object could be modified in place without having to allocate newly created object for the result the three flavors of division operators-- _div_ () _truediv_ ()and _floordiv_ ()--are used to implement true division (/and truncating division (//operations the reasons why there are three operations deal with change in the semantics of integer division that started in python but became the default behavior in python in python the default behavior of python is to map the operator to _div_ (for integersthis operation truncates the result to an integer in python division is mapped to _truediv_ (and for integersa float is returned this latter lib fl ff
17,909
types and objects behavior can be enabled in python as an optional feature by including the statement from _future_ import division in program the conversion methods _int_ () _long_ () _float_ ()and _complex_ (convert an object into one of the four built-in numerical types these methods are invoked by explicit type conversions such as int(and float(howeverthese methods are not used to implicitly coerce types in mathematical operations for examplethe expression produces typeerror even if is userdefined object that defines _int_ (for integer conversion callable interface an object can emulate function by providing the _call_ (self [,*args [**kwargs]]method if an objectxprovides this methodit can be invoked like function that isx(arg arg invokes _call_ (selfarg arg objects that emulate functions can be useful for creating functors or proxies here is simple exampleclass distancefrom(object)def _init_ (self,origin)self origin origin def _call_ (selfx)return abs( self originnums [ - nums sort(key=distancefrom( )sort by distance from in this examplethe distancefrom class creates instances that emulate singleargument function these can be used in place of normal function--for instancein the call to sort(in the example context management protocol the with statement allows sequence of statements to execute under the control of another object known as context manager the general syntax is as followswith context as var]statements the context object shown here is expected to implement the methods shown in table the _enter_ (method is invoked when the with statement executes the value returned by this method is placed into the variable specified with the optional as var specifier the _exit_ (method is called as soon as control-flow leaves from the block of statements associated with the with statement as arguments_ _exit_ (receives the current exception typevalueand traceback if an exception has been raised if no errors are being handledall three values are set to none table special methods for context managers method description _enter_ (selfcalled when entering new context the return value is placed in the variable listed with the as specifier to the with statement lib fl ff
17,910
table continued method description _exit_ (selftypevaluetbcalled when leaving context if an exception occurredtypevalueand tb have the exception typevalueand traceback information the primary use of the context management interface is to allow for simplified resource control on objects involving system state such as open filesnetwork connectionsand locks by implementing this interfacean object can safely clean up resources when execution leaves context in which an object is being used further details are found in "program structure and control flow object inspection and dir(the dir(function is commonly used to inspect objects an object can supply the list of names returned by dir(by implementing _dir_ (selfdefining this makes it easier to hide the internal details of objects that you don' want user to directly access howeverkeep in mind that user can still inspect the underlying _dict_ attribute of instances and classes to see everything that is defined lib fl ff
17,911
lib fl ff
17,912
operators and expressions his describes python' built-in operatorsexpressionsand evaluation rules although much of this describes python' built-in typesuser-defined objects can easily redefine any of the operators to provide their own behavior operations on numbers the following operations can be applied to all numeric typesoperation description / * - + addition subtraction multiplication division truncating division power (xymodulo ( mod yunary minus unary plus the truncating division operator (//also known as floor divisiontruncates the result to an integer and works with both integers and floating-point numbers in python the true division operator (/also truncates the result to an integer if the operands are integers therefore / is not howeverthis behavior changes in python where division produces floating-point result the modulo operator returns the remainder of the division / for example is for floating-point numbersthe modulo operator returns the floating-point remainder of /ywhich is ( /yy for complex numbersthe modulo (%and truncating division operators (//are invalid the following shifting and bitwise logical operators can be applied only to integersoperation description < > ~ left shift right shift bitwise and bitwise or bitwise xor (exclusive orbitwise negation lib fl ff
17,913
operators and expressions the bitwise operators assume that integers are represented in ' complement binary representation and that the sign bit is infinitely extended to the left some care is required if you are working with raw bit-patterns that are intended to map to native integers on the hardware this is because python does not truncate the bits or allow values to overflow--insteadthe result will grow arbitrarily large in magnitude in additionyou can apply the following built-in functions to all the numerical typesfunction description abs(xdivmod( ,ypow( , [,modulo]round( ,[ ]absolute value returns ( /yx yreturns ( *ymodulo rounds to the nearest multiple of - (floating-point numbers onlythe abs(function returns the absolute value of number the divmod(function returns the quotient and remainder of division operation and is only valid on noncomplex numbers the pow(function can be used in place of the *operator but also supports the ternary power-modulo function (often used in cryptographic algorithmsthe round(function rounds floating-point numberxto the nearest multiple of to the power minus if is omittedit' set to if is equally close to two multiplespython rounds to the nearest multiple away from zero (for example is rounded to and - is rounded to - one caution here is that python rounds equally close values to the nearest even multiple (for example is rounded to and is rounded to this is subtle portability issue for mathematical programs being ported to python the following comparison operators have the standard mathematical interpretation and return boolean value of true for truefalse for falseoperation description = ! > < less than greater than equal to not equal to greater than or equal to less than or equal to comparisons can be chained togethersuch as in such expressions are evaluated as are legal but are likely to confuse anyone reading the code (it' important to note that no comparison is made between and in such an expressioncomparisons involving complex numbers are undefined and result in typeerror operations involving numbers are valid only if the operands are of the same type for built-in numbersa coercion operation is performed to convert one of the types to the otheras follows if either operand is complex numberthe other operand is converted to complex number lib fl ff
17,914
if either operand is floating-point numberthe other is converted to float otherwiseboth numbers must be integers and no conversion is performed for user-defined objectsthe behavior of expressions involving mixed operands depends on the implementation of the object as general rulethe interpreter does not try to perform any kind of implicit type conversion operations on sequences the following operators can be applied to sequence typesincluding stringslistsand tuplesoperation description nn , vn [is[ :js[ : :stridex in sx not in for in sall(sany(slen(smin(smax(ssum( [initial]concatenation makes copies of swhere is an integer variable unpacking indexing slicing extended slicing membership iteration returns true if all items in are true returns true if any item in is true length minimum item in maximum item in sum of items with an optional initial value the operator concatenates two sequences of the same type the operator makes copies of sequence howeverthese are shallow copies that replicate elements by reference only for exampleconsider the following codea [ , , [ac * [[ ][ ][ ][ ] [ - [[- ][- ][- ][- ]notice how the change to modified every element of the list in this casea reference to the list was placed in the list when was replicatedfour additional references to were created finallywhen was modifiedthis change was propagated to all the other "copiesof this behavior of sequence multiplication is often unexpected and not the intent of the programmer one way to work around the problem is to manually construct the replicated sequence by duplicating the contents of here' an examplea [list(afor in range( )list(makes copy of list the copy module in the standard library can also be used to make copies of objects lib fl ff
17,915
operators and expressions all sequences can be unpacked into sequence of variable names for exampleitems , , items letters "abcx, , letters ' ' ' ' 'cdatetime (( )( "am")(month,day,year),(hour,minute,am_pmdatetime when unpacking values into variablesthe number of variables must exactly match the number of items in the sequence in additionthe structure of the variables must match that of the sequence for examplethe last line of the example unpacks values into six variablesorganized into two -tupleswhich is the structure of the sequence on the right unpacking sequences into variables works with any kind of sequenceincluding those created by iterators and generators the indexing operator [nreturns the nth object from sequence in which [ is the first object negative indices can be used to fetch characters from the end of sequence for examples[- returns the last item otherwiseattempts to access elements that are out of range result in an indexerror exception the slicing operator [ :jextracts subsequence from consisting of the elements with index kwhere < both and must be integers or long integers if the starting or ending index is omittedthe beginning or end of the sequence is assumedrespectively negative indices are allowed and assumed to be relative to the end of the sequence if or is out of rangethey're assumed to refer to the beginning or end of sequencedepending on whether their value refers to an element before the first item or after the last itemrespectively the slicing operator may be given an optional strides[ : :stride]that causes the slice to skip elements howeverthe behavior is somewhat more subtle if stride is suppliedi is the starting indexj is the ending indexand the produced subsequence is the elements [ ] [ +stride] [ + *stride]and so forth until index is reached (which is not includedthe stride may also be negative if the starting index is omittedit is set to the beginning of the sequence if stride is positive or the end of the sequence if stride is negative if the ending index is omittedit is set to the end of the sequence if stride is positive or the beginning of the sequence if stride is negative here are some examplesa [ [:: [::- [ : : [ : :- [: : [: :- [ :: [ ::- [ : :- [ [ [ , [ , , [ , , , , [ , , , [ , , , , [ , , , , , [ , , , , the in operator tests to see whether the object is in the sequence and returns true or false similarlythe not in operator tests whether is not in the sequence for stringsthe in and not in operators accept subtrings for examplef lib fl ff
17,916
'helloin 'hello worldproduces true it is important to note that the in operator does not support wildcards or any kind of pattern matching for thisyou need to use library module such as the re module for regular expression patterns the for in operator iterates over all the elements of sequence and is described further in "program structure and control flow len(sreturns the number of elements in sequence min(sand max(sreturn the minimum and maximum values of sequencerespectivelyalthough the result may only make sense if the elements can be ordered with respect to the operator (for exampleit would make little sense to find the maximum value of list of file objectssum(ssums all of the items in but usually works only if the items represent numbers an optional initial value can be given to sum(the type of this value usually determines the result for exampleif you used sum(itemsdecimal decimal( ))the result would be decimal object (see more about the decimal module in "mathematics"strings and tuples are immutable and cannot be modified after creation lists can be modified with the following operatorsoperation description [ix [ :jr [ : :strider del [idel [ :jdel [ : :strideindex assignment slice assignment extended slice assignment deletes an element deletes slice deletes an extended slice the [ix operator changes element of list to refer to object xincreasing the reference count of negative indices are relative to the end of the listand attempts to assign value to an out-of-range index result in an indexerror exception the slicing assignment operator [ :jr replaces element kwhere < jwith elements from sequence indices may have the same values as for slicing and are adjusted to the beginning or end of the list if they're out of range if necessarythe sequence is expanded or reduced to accommodate all the elements in here' an examplea [ , , , , [ [ , , , , [ : [ , [ , , , , [ : [- ,- ,- [ , , ,- ,- ,- , [ :[ [ , , slicing assignment may be supplied with an optional stride argument howeverthe behavior is somewhat more restricted in that the argument on the right side must have exactly the same number of elements as the slice that' being replaced here' an examplea [ , , , , [ :: [ , [ :: [ , , [ , , , , valueerror only two elements in slice on left the del [ioperator removes element from list and decrements its reference count del [ :jremoves all the elements in slice stride may also be suppliedas in del [ : :stridef lib fl ff
17,917
sequences are compared using the operators ===and !when comparing two sequencesthe first elements of each sequence are compared if they differthis determines the result if they're the samethe comparison moves to the second element of each sequence this process continues until two different elements are found or no more elements exist in either of the sequences if the end of both sequences is reachedthe sequences are considered equal if is subsequence of bthen strings are compared using lexicographical ordering each character is assigned unique numerical index determined by the character set (such as ascii or unicodea character is less than another character if its index is less one caution concerning character ordering is that the preceding simple comparison operators are not related to the character ordering rules associated with locale or language settings thusyou would not use these operations to order strings according to the standard conventions of foreign language (see the unicodedata and locale modules for more informationanother cautionthis time involving strings python has two types of string databyte strings and unicode strings byte strings differ from their unicode counterpart in that they are usually assumed to be encodedwhereas unicode strings represent raw unencoded character values because of thisyou should never mix byte strings and unicode together in expressions or comparisons (such as using to concatenate byte string and unicode string or using =to compare mixed stringsin python mixing string types results in typeerror exceptionbut python attempts to perform an implicit promotion of byte strings to unicode this aspect of python is widely considered to be design mistake and is often source of unanticipated exceptions and inexplicable program behavior soto keep your head from explodingdon' mix string types in sequence operations string formatting the modulo operator ( dproduces formatted stringgiven format stringsand collection of objects in tuple or mapping object (dictionaryd the behavior of this operator is similar to the sprintf(function the format string contains two types of objectsordinary characters (which are left unmodifiedand conversion specifierseach of which is replaced with formatted string representing an element of the associated tuple or mapping if is tuplethe number of conversion specifiers must exactly match the number of objects in if is mappingeach conversion specifier must be associated with valid key name in the mapping (using parenthesesas described shortlyeach conversion specifier starts with the character and ends with one of the conversion characters shown in table table string formatting conversions character output format , decimal integer or long integer unsigned integer or long integer octal integer or long integer hexadecimal integer or long integer hexadecimal integer (uppercase lettersfloating point as [-] dddddd floating point as [-] dddddde+-xx lib fl ff
17,918
table continued character output format , floating point as [-] dddddde+-xx use % or % for exponents less than - or greater than the precisionotherwiseuse % string or any object the formatting code uses str(to generate strings produces the same string as produced by repr(single character literal between the character and the conversion characterthe following modifiers may appearin this order key name in parentheseswhich selects specific item out of the mapping object if no such element existsa keyerror exception is raised one or more of the followingn signindicating left alignment by defaultvalues are right-aligned signindicating that the numeric sign should be included (even if positiven indicating zero fill number specifying the minimum field width the converted value will be printed in field at least this wide and padded on the left (or right if the flag is givento make up the field width period separating the field width from precision number specifying the maximum number of characters to be printed from stringthe number of digits following the decimal point in floating-point numberor the minimum number of digits for an integer in additionthe asterisk (*character may be used in place of number in any width field if presentthe width will be read from the next item in the tuple the following code illustrates few examplesa "hellod {' ': ' ': ' ':'world' " is %da "% % ( ,br "%+ % ( ,br "%( )- %( ) gd "% % (cd[' '] "%* ( , ,br " %de " is "+ + " "hell worldr " " when used with dictionarythe string formatting operator is often used to mimic the string interpolation feature often found in scripting languages ( expansion of lib fl ff
17,919
operators and expressions $var symbols in stringsfor exampleif you have dictionary of valuesyou can expand those values into fields within formatted string as followsstock 'name'goog''shares 'price "%(shares) of %(name) at %(price) fstock " shares of goog at the following code shows how to expand the values of currently defined variables within string the vars(function returns dictionary containing all of the variables defined at the point at which vars(is called name "elwoodage "%(name) is %(age) years oldvars(advanced string formatting more advanced form of string formatting is available using the format(*args*kwargsmethod on strings this method collects an arbitrary collection of positional and keyword arguments and substitutes their values into placeholders embedded in placeholder of the form '{ }'where is numbergets replaced by positional argument supplied to format( placeholder of the form '{name}gets replaced by keyword argument name supplied to format use '{{to output single '{and '}}to output single '}for exampler "{ { { }format('goog', , "{name{shares{price}format(name='goog',shares= ,price= "hello { }your age is {age}format("elwood",age= "use {and }to output single curly bracesformat(with each placeholderyou can additionally perform both indexing and attribute lookups for examplein '{name[ ]}where is an integera sequence lookup is performed and in '{name[key]}where key is non-numeric stringa dictionary lookup of the form name['key'is performed in '{name attr}'an attribute lookup is performed here are some examplesstock 'name'goog''shares 'price "{ [name]{ [shares]{ [price]}format(stockx "{ real{ imag}format(xin these expansionsyou are only allowed to use names arbitrary expressionsmethod callsand other operations are not supported you can optionally specify format specifier that gives more precise control over the output this is supplied by adding an optional format specifier to each placeholder using colon (:)as in '{place:format_spec}by using this specifieryou can specify column widthsdecimal placesand alignment here is an exampler "{name: {shares: {price: }format (name="goog",shares= ,price= lib fl ff
17,920
the general format of specifier is [[fill[align]][sign][ ][widthprecision][typewhere each part enclosed in [is optional the width specifier specifies the minimum field width to useand the align specifier is one of ''or '^for leftrightand centered alignment within the field an optional fill character fill is used to pad the space for examplename "elwoodr "{ :< }format(namer "{ :> }format(namer "{ :^ }format(namer "{ :=^ }format(namer 'elwood elwoodr elwood '==elwood==the type specifier indicates the type of data table lists the supported format codes if not suppliedthe default format code is 'sfor strings'dfor integersand 'ffor floats table advanced string formatting type specifier codes character output format , , decimal integer or long integer binary integer or long integer octal integer or long integer hexadecimal integer or long integer hexadecimal integer (uppercase lettersfloating point as [-] dddddd floating point as [-] dddddde+-xx floating point as [-] dddddde+-xx use or for exponents less than - or greater than the precisionotherwiseuse same as except that the current locale setting determines the decimal point character multiplies number by and displays it using format followed by sign string or any object the formatting code uses str(to generate strings single character the sign part of format specifier is one of '+''-'or '+indicates that leading sign should be used on all numbers '-is the default and only adds sign character for negative numbers adds leading space to positive numbers the precision part of the specifier supplies the number of digits of accuracy to use for decimals if leading ' is added to the field width for numbersnumeric values are padded with leading to fill the space here are some examples of formatting different kinds of numbersx '{ : }format(xr '{ : }format(xr '{ : }format(xr '{ : }format(xr ar ' '{ : }format(yr lib fl ff
17,921
operators and expressions '{ : }format(yr '{ :+ }format(yr '{ :+ }format(yr '{ :+ %}format(yr + + '+ + %parts of format specifier can optionally be supplied by other fields supplied to the format function they are accessed using the same syntax as normal fields in format string for exampley '{ :{width{precision} }format( ,width= ,precision= '{ :{ { } }format( , , this nesting of fields can only be one level deep and can only occur in the format specifier portion in additionthe nested values cannot have any additional format specifiers of their own one caution on format specifiers is that objects can define their own custom set of specifiers underneath the coversadvanced string formatting invokes the special method _format_ (selfformat_specon each field value thusthe capabilities of the format(operation are open-ended and depend on the objects to which it is applied for exampledatestimesand other kinds of objects may define their own format codes in certain casesyou may want to simply format the str(or repr(representation of an objectbypassing the functionality implemented by its _format_ (method to do thisyou can add the '!sor '!rmodifier before the format specifier for examplename "guidor '{ ! :^ }format(namer 'guidooperations on dictionaries dictionaries provide mapping between names and objects you can apply the following operations to dictionariesoperation description [kd[kx del [kk in len(dindexing by key assignment by key deletes an item by key tests for the existence of key number of items in the dictionary key values can be any immutable objectsuch as stringsnumbersand tuples in additiondictionary keys can be specified as comma-separated list of valueslike thisd [ , , "food[ , , "barin this casethe key values represent tuplemaking the preceding assignments identical to the followingd[( , , )"food[( , , )"barf lib fl ff
17,922
operations on sets the set and frozenset type support number of common set operationsoperation description len(smax(smin(sunion of and intersection of and set difference symmetric difference number of items in the set maximum value minimum value the result of unionintersectionand difference operations will have the same type as the left-most operand for exampleif is frozensetthe result will be frozenset even if is set augmented assignment python provides the following set of augmented assignment operatorsoperation description + - * / // ** % & | ^ >> << / * > < these operators can be used anywhere that ordinary assignment is used here' an examplea [ , "hello % %sa + [ + %("monty""python" [ "hello monty pythonaugmented assignment doesn' violate mutability or perform in-place modification of objects thereforewriting + creates an entirely new object with the value user-defined classes can redefine the augmented assignment operators using the special methods described in "types and objects lib fl ff
17,923
operators and expressions the attribute operator the dot operator is used to access the attributes of an object here' an examplefoo print foo foo bar( , , more than one dot operator can appear in single expressionsuch as in foo the dot operator can also be applied to the intermediate results of functionsas in foo bar( , , spam user-defined classes can redefine or customize the behavior of more details are found in and "classes and object-oriented programming the function call (operator the (argsoperator is used to make function call on each argument to function is an expression prior to calling the functionall of the argument expressions are fully evaluated from left to right this is sometimes known as applicative order evaluation it is possible to partially evaluate function arguments using the partial(function in the functools module for exampledef foo( , , )return from functools import partial partial(foo, , supply values to and arguments of foo ( calls foo( , , )result is the partial(function evaluates some of the arguments to function and returns an object that you can call to supply the remaining arguments at later point in the previous examplethe variable represents partially evaluated function where the first two arguments have already been calculated you merely need to supply the last remaining argument value for the function to execute partial evaluation of function arguments is closely related to process known as curryinga mechanism by which function taking multiple arguments such as ( ,yis decomposed into series of functions each taking only one argument (for exampleyou partially evaluate by fixing to get new function to which you give values of to produce resultconversion functions sometimes it' necessary to perform conversions between the built-in types to convert between typesyou simply use the type name as function in additionseveral built-in functions are supplied to perform special kinds of conversions all of these functions return new object representing the converted value function description int( [,base]converts to an integer base specifies the base if is string converts to floating-point number creates complex number converts object to string representation float(xcomplex(real [,imag]str(xf lib fl ff
17,924
function description repr(xformat( [,format_spec]eval(strtuple(sconverts object to an expression string converts object to formatted string evaluates string and returns an object converts to tuple converts to list converts to set creates dictionary must be sequence of (key,valuetuples converts to frozen set converts an integer to character converts an integer to unicode character (python onlyconverts single character to its integer value converts an integer to hexadecimal string converts an integer to binary string converts an integer to an octal string list(sset(sdict(dfrozenset(schr(xunichr(xord(xhex(xbin(xoct(xnote that the str(and repr(functions may return different results repr(typically creates an expression string that can be evaluated with eval(to re-create the object on the other handstr(produces concise or nicely formatted representation of the object (and is used by the print statementthe format( [format_spec]function produces the same output as that produced by the advanced string formatting operations but applied to single object as inputit accepts an optional format_specwhich is string containing the formatting code the ord(function returns the integer ordinal value of character for unicodethis value will be the integer code point the chr(and unichr(functions convert integers back into characters to convert strings back into numbersuse the int()float()and complex(functions the eval(function can also convert string containing valid expression to an object here' an examplea int(" " long(" xfe " ( xfe lb float(" " eval(" " ( , , in functions that create containers (list()tuple()set()and so on)the argument may be any object that supports iteration used to generate all the items used to populate the object that' being created boolean expressions and truth values the andorand not keywords can form boolean expressions the behavior of these operators is as followsoperator description or and not if is falsereturn yotherwisereturn if is falsereturn xotherwisereturn if is falsereturn otherwisereturn lib fl ff
17,925
when you use an expression to determine true or false valuetrueany nonzero numbernonempty stringlisttupleor dictionary is taken to be true falsezerononeand empty liststuplesand dictionaries evaluate as false boolean expressions are evaluated from left to right and consume the right operand only if it' needed to determine the final value for examplea and evaluates only if is true this is sometimes known as "short-circuitevaluation object equality and identity the equality operator ( =ytests the values of and for equality in the case of lists and tuplesall the elements are compared and evaluated as true if they're of equal value for dictionariesa true value is returned only if and have the same set of keys and all the objects with the same key have equal values two sets are equal if they have the same elementswhich are compared using equality (==the identity operators ( is and is not ytest two objects to see whether they refer to the same object in memory in generalit may be the case that =ybut is not comparison between objects of noncompatible typessuch as file and floatingpoint numbermay be allowedbut the outcome is arbitrary and may not make any sense it may also result in an exception depending on the type order of evaluation table lists the order of operation (precedence rulesfor python operators all operators except the power (**operator are evaluated from left to right and are listed in the table from highest to lowest precedence that isoperators listed first in the table are evaluated before operators listed later (note that operators included together within subsectionssuch as yx yx yand yhave equal precedence table order of evaluation (highest to lowestoperator name )] [ ] [ :js attr + - ~ * yx yx /yx yx tuplelistand dictionary creation indexing and slicing attributes function calls unary operators power (right associativemultiplicationdivisionfloor divisionmodulo additionsubtraction bit-shifting bitwise and bitwise exclusive or bitwise or comparisonidentityand sequence membership tests yx <yx yx >yx =yx ! lib fl ff
17,926
table continued operator name is yx is not in sx not in not and or lambda argsexpr logical negation logical and logical or anonymous function the order of evaluation is not determined by the types of and in table soeven though user-defined objects can redefine individual operatorsit is not possible to customize the underlying evaluation orderprecedenceand associativity rules conditional expressions common programming pattern is that of conditionally assigning value based on the result of an expression for exampleif <bminvalue elseminvalue this code can be shortened using conditional expression for exampleminvalue if <= else in such expressionsthe condition in the middle is evaluated first the expression to the left of the if is then evaluated if the result is true otherwisethe expression after the else is evaluated conditional expressions should probably be used sparingly because they can lead to confusion (especially if they are nested or mixed with other complicated expressionshoweverone particularly useful application is in list comprehensions and generator expressions for examplevalues [ clamped [ if else for in valuesprint(clamped[ lib fl ff
17,927
lib fl ff
17,928
program structure and control flow his covers the details of program structure and control flow topics include conditionalsiterationexceptionsand context managers program structure and execution python programs are structured as sequence of statements all language featuresincluding variable assignmentfunction definitionsclassesand module importsare statements that have equal status with all other statements in factthere are no "specialstatementsand every statement can be placed anywhere in program for examplethis code defines two different versions of functionif debugdef square( )if not isinstance( ,float)raise typeerror("expected float"return elsedef square( )return when loading source filesthe interpreter always executes every statement in order until there are no more statements to execute this execution model applies both to files you simply run as the main program and to library files that are loaded via import conditional execution the ifelseand elif statements control conditional code execution the general format of conditional statement is as followsif expressionstatements elif expressionstatements elif expressionstatements elsestatements lib fl ff
17,929
program structure and control flow if no action is to be takenyou can omit both the else and elif clauses of conditional use the pass statement if no statements exist for particular clauseif expressionpass elsestatements do nothing loops and iteration you implement loops using the for and while statements here' an examplewhile expressionstatements for in sstatements the while statement executes statements until the associated expression evaluates to false the for statement iterates over all the elements of until no more elements are available the for statement works with any object that supports iteration this obviously includes the built-in sequence types such as liststuplesand stringsbut also any object that implements the iterator protocol an objectssupports iteration if it can be used with the following codewhich mirrors the implementation of the for statementit _iter_ (get an iterator for while tryi it next(get next item (use _next_ in python except stopiterationno more items break perform operations on in the statement for in sthe variable is known as the iteration variable on each iteration of the loopit receives new value from the scope of the iteration variable is not private to the for statement if previously defined variable has the same namethat value will be overwritten moreoverthe iteration variable retains the last value after the loop has completed if the elements used in iteration are sequences of identical sizeyou can unpack their values into individual iteration variables using statement such as the followingfor , , in sstatements in this examples must contain or produce sequenceseach with three elements on each iterationthe contents of the variables xyand are assigned the items of the corresponding sequence although it is most common to see this used when is sequence of tuplesunpacking works if the items in are any kind of sequence including listsgeneratorsand strings when loopingit is sometimes useful to keep track of numerical index in addition to the data values here' an examplei for in sf lib fl ff
17,930
statements + python provides built-in functionenumerate()that can be used to simplify this codefor , in enumerate( )statements enumerate(screates an iterator that simply returns sequence of tuples ( [ ])( [ ])( [ ])and so on another common looping problem concerns iterating in parallel over two or more sequences--for examplewriting loop where you want to take items from different sequences on each iteration as followss and are two sequences while len(sand len( ) [itake an item from [itake an item from statements + this code can be simplified using the zip(function for examples and are two sequences for , in zip( , )statements zip( ,tcombines sequences and into sequence of tuples ( [ ], [ ])( [ ], [ ])( [ ] [ ])and so forthstopping with the shortest of the sequences and should they be of unequal length one caution with zip(is that in python it fully consumes both and tcreating list of tuples for generators and sequences containing large amount of datathis may not be what you want the function itertools izip(achieves the same effect as zip(but generates the zipped values one at time rather than creating large list of tuples in python the zip(function also generates values in this manner to break out of loopuse the break statement for examplethis code reads lines of text from file until an empty line of text is encounteredfor line in open("foo txt")stripped line strip(if not strippedbreak blank linestop reading process the stripped line to jump to the next iteration of loop (skipping the remainder of the loop body)use the continue statement this statement tends to be used less often but is sometimes useful when the process of reversing test and indenting another level would make the program too deeply nested or unnecessarily complicated as an examplethe following loop skips all of the blank lines in filefor line in open("foo txt")stripped line strip(if not strippedcontinue skip the blank line process the stripped line lib fl ff
17,931
program structure and control flow the break and continue statements apply only to the innermost loop being executed if it' necessary to break out of deeply nested loop structureyou can use an exception python doesn' provide "gotostatement you can also attach the else statement to loop constructsas in the following examplefor-else for line in open("foo txt")stripped line strip(if not strippedbreak process the stripped line elseraise runtimeerror("missing section separator"the else clause of loop executes only if the loop runs to completion this either occurs immediately (if the loop wouldn' execute at allor after the last iteration on the other handif the loop is terminated early using the break statementthe else clause is skipped the primary use case for the looping else clause is in code that iterates over data but which needs to set or check some kind of flag or condition if the loop breaks prematurely for exampleif you didn' use elsethe previous code might have to be rewritten with flag variable as followsfound_separator false for line in open("foo txt")stripped line strip(if not strippedfound_separator true break process the stripped line if not found_separatorraise runtimeerror("missing section separator"exceptions exceptions indicate errors and break out of the normal control flow of program an exception is raised using the raise statement the general format of the raise statement is raise exception([value])where exception is the exception type and value is an optional value giving specific details about the exception here' an exampleraise runtimeerror("unrecoverable error"if the raise statement is used by itselfthe last exception generated is raised again (although this works only while handling previously raised exceptionto catch an exceptionuse the try and except statementsas shown heretryf open('foo'except ioerror as estatements lib fl ff
17,932
when an exception occursthe interpreter stops executing statements in the try block and looks for an except clause that matches the exception that has occurred if one is foundcontrol is passed to the first statement in the except clause after the except clause is executedcontrol continues with the first statement that appears after the try-except block otherwisethe exception is propagated up to the block of code in which the try statement appeared this code may itself be enclosed in try-except that can handle the exception if an exception works its way up to the top level of program without being caughtthe interpreter aborts with an error message if desireduncaught exceptions can also be passed to user-defined functionsys excepthook()as described in "python runtime services the optional as var modifier to the except statement supplies the name of variable in which an instance of the exception type supplied to the raise statement is placed if an exception occurs exception handlers can examine this value to find out more about the cause of the exception for exampleyou can use isinstance(to check the exception type one caution on the syntaxin previous versions of pythonthe except statement was written as except exctypevar where the exception type and variable were separated by comma (,in python this syntax still worksbut it is deprecated in new codeuse the as var syntax because it is required in python multiple exception-handling blocks are specified using multiple except clausesas in the following exampletrydo something except ioerror as ehandle / error except typeerror as ehandle type error except nameerror as ehandle name error single handler can catch multiple exception types like thistrydo something except (ioerrortypeerrornameerroras ehandle /otypeor name errors to ignore an exceptionuse the pass statement as followstrydo something except ioerrorpass do nothing (oh wellto catch all exceptions except those related to program exituse exception like thistrydo something except exception as eerror_log write('an error occurred % \nef lib fl ff
17,933
program structure and control flow when catching all exceptionsyou should take care to report accurate error information to the user for examplein the previous codean error message and the associated exception value is being logged if you don' include any information about the exception valueit can make it very difficult to debug code that is failing for reasons that you don' expect all exceptions can be caught using except with no exception type as followstrydo something excepterror_log write('an error occurred\ 'correct use of this form of except is lot trickier than it looks and should probably be avoided for instancethis code would also catch keyboard interrupts and requests for program exit--things that you may not want to catch the try statement also supports an else clausewhich must follow the last except clause this code is executed if the code in the try block doesn' raise an exception here' an exampletryf open('foo'' 'except ioerror as eerror_log write('unable to open foo % \neelsedata read( close(the finally statement defines cleanup action for code contained in try block here' an examplef open('foo',' 'trydo some stuff finallyf close(file closed regardless of what happened the finally clause isn' used to catch errors ratherit' used to provide code that must always be executedregardless of whether an error occurs if no exception is raisedthe code in the finally clause is executed immediately after the code in the try block if an exception occurscontrol is first passed to the first statement of the finally clause after this code has executedthe exception is re-raised to be caught by another exception handler built-in exceptions python defines the built-in exceptions listed in table lib fl ff
17,934
table built-in exceptions exception description baseexception generatorexit keyboardinterrupt systemexit exception stopiteration standarderror arithmeticerror floatingpointerror zerodivisionerror assertionerror attributeerror environmenterror ioerror oserror eoferror importerror lookuperror indexerror keyerror memoryerror nameerror unboundlocalerror referenceerror runtimeerror notimplementederror syntaxerror indentationerror taberror systemerror typeerror valueerror unicodeerror unicodedecodeerror unicodeencodeerror unicodetranslateerror the root of all exceptions raised by close(method on generator generated by the interrupt key (usually ctrl+cprogram exit/termination base class for all non-exiting exceptions raised to stop iteration base for all built-in exceptions (python onlyin python all exceptions below are grouped under exception base for arithmetic exceptions failure of floating-point operation division or modulus operation with raised by the assert statement raised when an attribute name is invalid errors that occur externally to python / or file-related error operating system error raised when the end of the file is reached failure of the import statement indexing and key errors out-of-range sequence index nonexistent dictionary key out of memory failure to find local or global name unbound local variable weak reference used after referent destroyed generic catchall error unimplemented feature parsing error indentation error inconsistent tab usage (generated with -tt optionnonfatal system error in the interpreter passing an inappropriate type to an operation invalid type unicode error unicode decoding error unicode encoding error unicode translation error lib fl ff
17,935
program structure and control flow exceptions are organized into hierarchy as shown in the table all the exceptions in particular group can be caught by specifying the group name in an except clause here' an exampletrystatements except lookuperrorstatements catch indexerror or keyerror or trystatements except exceptionstatements catch any program-related exception at the top of the exception hierarchythe exceptions are grouped according to whether or not the exceptions are related to program exit for examplethe systemexit and keyboardinterrupt exceptions are not grouped under exception because programs that want to catch all program-related errors usually don' want to also capture program termination by accident defining new exceptions all the built-in exceptions are defined in terms of classes to create new exceptioncreate new class definition that inherits from exceptionsuch as the followingclass networkerror(exception)pass to use your new exceptionuse it with the raise statement as followsraise networkerror("cannot find host "when raising an exceptionthe optional values supplied with the raise statement are used as the arguments to the exception' class constructor most of the timethis is simply string indicating some kind of error message howeveruser-defined exceptions can be written to take one or more exception values as shown in this exampleclass deviceerror(exception)def _init_ (self,errno,msg)self args (errnomsgself errno errno self errmsg msg raises an exception (multiple argumentsraise deviceerror( 'not responding'when you create custom exception class that redefines _init_ ()it is important to assign tuple containing the arguments to _init_ (to the attribute self args as shown this attribute is used when printing exception traceback messages if you leave it undefinedusers won' be able to see any useful information about the exception when an error occurs exceptions can be organized into hierarchy using inheritance for instancethe networkerror exception defined earlier could serve as base class for variety of more specific errors here' an exampleclass hostnameerror(networkerror)pass class timeouterror(networkerror)pass lib fl ff
17,936
def error ()raise hostnameerror("unknown host"def error ()raise timeouterror("timed out"tryerror (except networkerror as eif type(eis hostnameerrorperform special actions for this kind of error in this casethe except networkerror statement catches any exception derived from networkerror to find the specific type of error that was raisedexamine the type of the execution value with type(alternativelythe sys exc_info(function can be used to retrieve information about the last raised exception context managers and the with statement proper management of system resources such as fileslocksand connections is often tricky problem when combined with exceptions for examplea raised exception can cause control flow to bypass statements responsible for releasing critical resources such as lock the with statement allows series of statements to execute inside runtime context that is controlled by an object that serves as context manager here is an examplewith open("debuglog"," "as ff write("debugging\ "statements write("done\ "import threading lock threading lock(with lockcritical section statements end critical section in the first examplethe with statement automatically causes the opened file to be closed when control-flow leaves the block of statements that follows in the second examplethe with statement automatically acquires and releases lock when control enters and leaves the block of statements that follows the with obj statement allows the object obj to manage what happens when control-flow enters and exits the associated block of statements that follows when the with obj statement executesit executes the method obj _enter_ (to signal that new context is being entered when control flow leaves the contextthe method obj _exit_ (type,value,tracebackexecutes if no exception has been raisedthe three arguments to _exit_ (are all set to none otherwisethey contain the typevalueand traceback associated with the exception that has caused control-flow to leave the context the _exit_ (method returns true or false to indicate whether the raised exception was handled or not (if false is returnedany exceptions raised are propagated out of the contextf lib fl ff
17,937
program structure and control flow the with obj statement accepts an optional as var specifier if giventhe value returned by obj _enter_ (is placed into var it is important to emphasize that obj is not necessarily the value assigned to var the with statement only works with objects that support the context management protocol (the _enter_ (and _exit_ (methodsuser-defined classes can implement these methods to define their own customized context-management here is simple exampleclass listtransaction(object)def _init_ (self,thelist)self thelist thelist def _enter_ (self)self workingcopy list(self thelistreturn self workingcopy def _exit_ (self,type,value,tb)if type is noneself thelist[:self workingcopy return false this class allows one to make sequence of modifications to an existing list howeverthe modifications only take effect if no exceptions occur otherwisethe original list is left unmodified for exampleitems [ , , with listtransaction(itemsas workingworking append( working append( print(itemsproduces [ , , , , trywith listtransaction(itemsas workingworking append( working append( raise runtimeerror("we're hosed!"except runtimeerrorpass print(itemsproduces [ , , , , the contextlib module allows custom context managers to be more easily implemented by placing wrapper around generator function here is an examplefrom contextlib import contextmanager @contextmanager def listtransaction(thelist)workingcopy list(thelistyield workingcopy modify the original list only if no errors thelist[:workingcopy in this examplethe value passed to yield is used as the return value from _enter_ (when the _exit_ (method gets invokedexecution resumes after the yield if an exception gets raised in the contextit shows up as an exception in the generator function if desiredan exception could be caughtbut in this caseexceptions will simply propagate out of the generator to be handled elsewhere lib fl ff
17,938
assertions and _debug_ the assert statement can introduce debugging code into program the general form of assert is assert test [msgwhere test is an expression that should evaluate to true or false if test evaluates to falseassert raises an assertionerror exception with the optional message msg supplied to the assert statement here' an exampledef write_data(file,data)assert file"write_datafile not defined!the assert statement should not be used for code that must be executed to make the program correct because it won' be executed if python is run in optimized mode (specified with the - option to the interpreterin particularit' an error to use assert to check user input insteadassert statements are used to check things that should always be trueif one is violatedit represents bug in the programnot an error by the user for exampleif the function write_data()shown previouslywere intended for use by an end userthe assert statement should be replaced by conventional if statement and the desired error-handling in addition to assertpython provides the built-in read-only variable _debug_ _which is set to true unless the interpreter is running in optimized mode (specified with the - optionprograms can examine this variable as needed--possibly running extra error-checking procedures if set the underlying implementation of the _debug_ variable is optimized in the interpreter so that the extra control-flow logic of the if statement itself is not actually included if python is running in its normal modethe statements under the if _debug_ statement are just inlined into the program without the if statement itself in optimized modethe if _debug_ statement and all associated statements are completely removed from the program the use of assert and _debug_ allow for efficient dual-mode development of program for examplein debug modeyou can liberally instrument your code with assertions and debug checks to verify correct operation in optimized modeall of these extra checks get strippedresulting in no extra performance penalty lib fl ff
17,939
lib fl ff
17,940
functions and functional programming ubstantial programs are broken up into functions for better modularity and ease of maintenance python makes it easy to define functions but also incorporates surprising number of features from functional programming languages this describes functionsscoping rulesclosuresdecoratorsgeneratorscoroutinesand other functional programming features in additionlist comprehensions and generator expressions are described--both of which are powerful tools for declarative-style programming and data processing functions functions are defined with the def statementdef add( , )return the body of function is simply sequence of statements that execute when the function is called you invoke function by writing the function name followed by tuple of function argumentssuch as add( , the order and number of arguments must match those given in the function definition if mismatch existsa typeerror exception is raised you can attach default arguments to function parameters by assigning values in the function definition for exampledef split(line,delimiter=',')statements when function defines parameter with default valuethat parameter and all the parameters that follow are optional if values are not assigned to all the optional parameters in the function definitiona syntaxerror exception is raised default parameter values are always set to the objects that were supplied as values when the function was defined here' an examplea def foo( = )return foo(reassign 'areturns (default value not changedf lib fl ff
17,941
functions and functional programming in additionthe use of mutable objects as default values may lead to unintended behaviordef foo(xitems=[])items append(xreturn items foo( returns [ foo( returns [ foo( returns [ notice how the default argument retains modifications made from previous invocations to prevent thisit is better to use none and add check as followsdef foo(xitems=none)if items is noneitems [items append(xreturn items function can accept variable number of parameters if an asterisk (*is added to the last parameter namedef fprintf(filefmt*args)file write(fmt argsuse fprintf args gets ( ,"hello world" fprintf(out,"% % % " "hello world" in this caseall the remaining arguments are placed into the args variable as tuple to pass tuple args to function as if they were parametersthe *args syntax can be used in function call as followsdef printf(fmt*args)call another function and pass along args fprintf(sys stdoutfmt*argsfunction arguments can also be supplied by explicitly naming each parameter and specifying value these are known as keyword arguments here is an exampledef foo( , , , )statements keyword argument invocation foo( = = ='hello' =[ , ]with keyword argumentsthe order of the parameters doesn' matter howeverunless there are default valuesyou must explicitly name all of the required function parameters if you omit any of the required parameters or if the name of keyword doesn' match any of the parameter names in the function definitiona typeerror exception is raised alsosince any python function can be called using the keyword calling styleit is generally good idea to define functions with descriptive argument names positional arguments and keyword arguments can appear in the same function callprovided that all the positional arguments appear firstvalues are provided for all nonoptional argumentsand no argument value is defined more than once here' an examplefoo('hello' =[ , ] = foo( ='hello' =[ , ]typeerror multiple values for lib fl ff
17,942
if the last argument of function definition begins with **all the additional keyword arguments (those that don' match any of the other parameter namesare placed in dictionary and passed to the function this can be useful way to write functions that accept large number of potentially open-ended configuration options that would be too unwieldy to list as parameters here' an exampledef make_table(data**parms)get configuration parameters from parms ( dictfgcolor parms pop("fgcolor","black"bgcolor parms pop("bgcolor","white"width parms pop("width",noneno more options if parmsraise typeerror("unsupported configuration options %slist(parms)make_table(itemsfgcolor="black"bgcolor="white"border= borderstyle="grooved"cellpadding= width= you can combine extra keyword arguments with variable-length argument listsas long as the *parameter appears lastaccept variable number of positional or keyword arguments def spam(*args**kwargs)args is tuple of positional args kwargs is dictionary of keyword args keyword arguments can also be passed to another function using the **kwargs syntaxdef callfunc(*args**kwargs)func(*args,**kwargsthis use of *args and **kwargs is commonly used to write wrappers and proxies for other functions for examplethe callfunc(accepts any combination of arguments and simply passes them through to func(parameter passing and return values when function is invokedthe function parameters are simply names that refer to the passed input objects the underlying semantics of parameter passing doesn' neatly fit into any single stylesuch as "pass by valueor "pass by reference,that you might know about from other programming languages for exampleif you pass an immutable valuethe argument effectively looks like it was passed by value howeverif mutable object (such as list or dictionaryis passed to function where it' then modifiedthose changes will be reflected in the original object here' an examplea [ def square(items)for , in enumerate(items)items[ix modify items in-place square(achanges to [ functions that mutate their input values or change the state of other parts of the program behind the scenes like this are said to have side effects as general rulethis is lib fl ff
17,943
functions and functional programming programming style that is best avoided because such functions can become source of subtle programming errors as programs grow in size and complexity (for exampleit' not obvious from reading function call if function has side effectssuch functions interact poorly with programs involving threads and concurrency because side effects typically need to be protected by locks the return statement returns value from function if no value is specified or you omit the return statementthe none object is returned to return multiple valuesplace them in tupledef factor( ) while ( <( ))if (( dd = )return (( )dd return ( multiple return values returned in tuple can be assigned to individual variablesxy factor( return values placed in and or (xyfactor( alternate version same behavior scoping rules each time function executesa new local namespace is created this namespace represents local environment that contains the names of the function parametersas well as the names of variables that are assigned inside the function body when resolving namesthe interpreter first searches the local namespace if no match existsit searches the global namespace the global namespace for function is always the module in which the function was defined if the interpreter finds no match in the global namespaceit makes final check in the built-in namespace if this failsa nameerror exception is raised one peculiarity of namespaces is the manipulation of global variables within function for exampleconsider the following codea def foo() foo( is still when this code executesa returns its value of despite the appearance that we might be modifying the variable inside the function foo when variables are assigned inside functionthey're always bound to the function' local namespaceas resultthe variable in the function body refers to an entirely new object containing the value not the outer variable to alter this behavioruse the global statement global simply declares names as belonging to the global namespaceand it' necessary only when global variables will be modified it can be placed anywhere in function body and used repeatedly here' an examplef lib fl ff
17,944
def foo()global 'ais in global namespace foo( is now is still python supports nested function definitions here' an exampledef countdown(start) start def display()nested function definition print(' -minus %dnwhile display( - variables in nested functions are bound using lexical scoping that isnames are resolved by first checking the local scope and then all enclosing scopes of outer function definitions from the innermost scope to the outermost scope if no match is foundthe global and built-in namespaces are checked as before although names in enclosing scopes are accessiblepython only allows variables to be reassigned in the innermost scope (local variablesand the global namespace (using globalthereforean inner function can' reassign the value of local variable defined in an outer function for examplethis code does not workdef countdown(start) start def display()print(' -minus %dndef decrement() - fails in python while display(decrement(in python you can work around this by placing values you want to change in list or dictionary in python you can declare as nonlocal as followsdef countdown(start) start def display()print(' -minus %dndef decrement()nonlocal bind to outer (python onlyn - while display(decrement(the nonlocal declaration does not bind name to local variables defined inside arbitrary functions further down on the current call-stack (that isdynamic scopesoif you're coming to python from perlnonlocal is not the same as declaring perl local variable lib fl ff
17,945
functions and functional programming if local variable is used before it' assigned valuean unboundlocalerror exception is raised here' an example that illustrates one scenario of how this might occuri def foo() print(iresults in unboundlocalerror exception in this functionthe variable is defined as local variable (because it is being assigned inside the function and there is no global statementhoweverthe assignment tries to read the value of before its local value has been first assigned even though there is global variable in this exampleit is not used to supply value here variables are determined to be either local or global at the time of function definition and cannot suddenly change scope in the middle of function for examplein the preceding codeit is not the case that the in the expression refers to the global variable iwhereas the in print(irefers to the local variable created in the previous statement functions as objects and closures functions are first-class objects in python this means that they can be passed as arguments to other functionsplaced in data structuresand returned by function as result here is an example of function that accepts another function as input and calls itfoo py def callf(func)return func(here is an example of using the above functionimport foo def helloworld()return 'hello worldfoo callf(helloworld'hello worldpass function as an argument when function is handled as datait implicitly carries information related to the surrounding environment where the function was defined this affects how free variables in the function are bound as an exampleconsider this modified version foo py that now contains variable definitionfoo py def callf(func)return func(nowobserve the behavior of this exampleimport foo def helloworld()return "hello world is %dx foo callf(helloworldpass function as an argument 'hello world is lib fl ff
17,946
in this examplenotice how the function helloworld(uses the value of that' defined in the same environment as where helloworld(was defined thuseven though there is also an defined in foo py and that' where helloworld(is actually being calledthat value of is not the one that' used when helloworld(executes when the statements that make up function are packaged together with the environment in which they executethe resulting object is known as closure the behavior of the previous example is explained by the fact that all functions have _globals_ attribute that points to the global namespace in which the function was defined this always corresponds to the enclosing module in which function was defined for the previous exampleyou get the followinghelloworld _globals_ {' _builtins_ ''helloworld'' ' ' _name_ '' _main_ '' _doc_ 'none 'foo'when nested functions are usedclosures capture the entire environment needed for the inner function to execute here is an exampleimport foo def bar() def helloworld()return "hello world is %dx foo callf(helloworldreturns 'hello worldx is closures and nested functions are especially useful if you want to write code based on the concept of lazy or delayed evaluation here is another examplefrom urllib import urlopen from urllib request import urlopen (python def page(url)def get()return urlopen(urlread(return get in this examplethe page(function doesn' actually carry out any interesting computation insteadit merely creates and returns function get(that will fetch the contents of web page when it is called thusthe computation carried out in get(is actually delayed until some later point in program when get(is evaluated for examplepython page(jython page(python jython pydata python(fetches jydata jython(fetches in this examplethe two variables python and jython are actually two different versions of the get(function even though the page(function that created these values is no longer executingboth get(functions implicitly carry the values of the outer variables that were defined when the get(function was created thuswhen get( lib fl ff
17,947
functions and functional programming executesit calls urlopen(urlwith the value of url that was originally supplied to page(with little inspectionyou can view the contents of variables that are carried along in closure for examplepython _closure_ (,python _closure_ [ cell_contents jython _closure_ [ cell_contents closure can be highly efficient way to preserve state across series of function calls for exampleconsider this code that runs simple counterdef countdown( )def next()nonlocal - return return next example use next countdown( while truev next(if not vbreak get the next value in this codea closure is being used to store the internal counter value the inner function next(updates and returns the previous value of this counter variable each time it is called programmers not familiar with closures might be inclined to implement similar functionality using class such as thisclass countdown(object)def _init_ (self, )self def next(self) self self - return example use countdown( while truev next(if not vbreak get the next value howeverif you increase the starting value of the countdown and perform simple timing benchmarkyou will find that that the version using closures runs much faster (almost speedup when tested on the author' machinethe fact that closures capture the environment of inner functions also make them useful for applications where you want to wrap existing functions in order to add extra capabilities this is described next lib fl ff
17,948
decorators decorator is function whose primary purpose is to wrap another function or class the primary purpose of this wrapping is to transparently alter or enhance the behavior of the object being wrapped syntacticallydecorators are denoted using the special symbol as follows@trace def square( )return * the preceding code is shorthand for the followingdef square( )return * square trace(squarein the examplea function square(is defined howeverimmediately after its definitionthe function object itself is passed to the function trace()which returns an object that replaces the original square nowlet' consider an implementation of trace that will clarify how this might be usefulenable_tracing true if enable_tracingdebug_log open("debug log"," "def trace(func)if enable_tracingdef callf(*args,**kwargs)debug_log write("calling % % % \ (func _name_ _argskwargs) func(*args,**kwargsdebug_log write("% returned % \ (func _namer)return return callf elsereturn func in this codetrace(creates wrapper function that writes some debugging output and then calls the original function object thusif you call square()you will see the output of the write(methods in the wrapper the function callf that is returned from trace(is closure that serves as replacement for the original function final interesting aspect of the implementation is that the tracing feature itself is only enabled through the use of global variable enable_tracing as shown if set to falsethe trace(decorator simply returns the original function unmodified thuswhen tracing is disabledthere is no added performance penalty associated with using the decorator when decorators are usedthey must appear on their own line immediately prior to function or class definition more than one decorator can also be applied here' an example@foo @bar @spam def grok( )pass lib fl ff
17,949
functions and functional programming in this casethe decorators are applied in the order listed the result is the same as thisdef grok( )pass grok foo(bar(spam(grok)) decorator can also accept arguments here' an example@eventhandler('button'def handle_button(msg)@eventhandler('reset'def handle_reset(msg)if arguments are suppliedthe semantics of the decorator are as followsdef handle_button(msg)temp eventhandler('button'handle_button temp(handle_buttoncall decorator with supplied arguments call the function returned by the decorator in this casethe decorator function only accepts the arguments supplied with the specifier it then returns function that is called with the function as an argument here' an exampleevent handler decorator event_handlers def eventhandler(event)def register_function( )event_handlers[eventf return return register_function decorators can also be applied to class definitions for example@foo class bar(object)def _init_ (self, )self def spam(self)statements for class decoratorsyou should always have the decorator function return class object as result code that expects to work with the original class definition may want to reference members of the class directly such as bar spam this won' work correctly if the decorator function foo(returns function decorators can interact strangely with other aspects of functions such as recursiondocumentation stringsand function attributes these issues are described later in this generators and yield if function uses the yield keywordit defines an object known as generator generator is function that produces sequence of values for use in iteration here' an examplef lib fl ff
17,950
def countdown( )print("counting down from %dnwhile yield - return if you call this functionyou will find that none of its code starts executing for examplec countdown( insteada generator object is returned the generator objectin turnexecutes the function whenever next(is called (or _next_ (in python here' an examplec next(counting down from next( use __next__(in python when next(is invokedthe generator function executes statements until it reaches yield statement the yield statement produces result at which point execution of the function stops until next(is invoked again execution then resumes with the statement following yield you normally don' call next(directly on generator but use it with the for statementsum()or some other operation that consumes sequence for examplefor in countdown( )statements sum(countdown( ) generator function signals completion by returning or raising stopiterationat which point iteration stops it is never legal for generator to return value other than none upon completion subtle problem with generators concerns the case where generator function is only partially consumed for exampleconsider this codefor in countdown( )if = break statements in this examplethe for loop aborts by calling breakand the associated generator never runs to full completion to handle this casegenerator objects have method close(that is used to signal shutdown when generator is no longer used or deletedclose(is called normally it is not necessary to call close()but you can also call it manually as shown herec countdown( next(counting down from next( close( next(traceback (most recent call last)file ""line in stopiteration lib fl ff
17,951
functions and functional programming inside the generator functionclose(is signaled by generatorexit exception occurring on the yield statement you can optionally catch this exception to perform cleanup actions def countdown( )print("counting down from %dntrywhile yield except generatorexitprint("only made it to %dnalthough it is possible to catch generatorexitit is illegal for generator function to handle the exception and produce another output value using yield moreoverif program is currently iterating on generatoryou should not call close(asynchronously on that generator from separate thread of execution or from signal handler coroutines and yield expressions inside functionthe yield statement can also be used as an expression that appears on the right side of an assignment operator for exampledef receiver()print("ready to receive"while truen (yieldprint("got %sna function that uses yield in this manner is known as coroutineand it executes in response to values being sent to it its behavior is also very similar to generator for exampler receiver( next(advance to first yield ( _next_ (in python ready to receive send( got send( got send("hello"got hello in this examplethe initial call to next(is necessary so that the coroutine executes statements leading to the first yield expression at this pointthe coroutine suspendswaiting for value to be sent to it using the send(method of the associated generator object the value passed to send(is returned by the (yieldexpression in the coroutine upon receiving valuea coroutine executes statements until the next yield statement is encountered the requirement of first calling next(on coroutine is easily overlooked and common source of errors thereforeit is recommended that coroutines be wrapped with decorator that automatically takes care of this step lib fl ff
17,952
def coroutine(func)def start(*args,**kwargs) func(*args,**kwargsg next(return return start using this decoratoryou would write and use coroutines using@coroutine def receiver()print("ready to receive"while truen (yieldprint("got %snexample use receiver( send("hello world"note no initial next(needed coroutine will typically run indefinitely unless it is explicitly shut down or it exits on its own to close the stream of input valuesuse the close(method like thisr close( send( traceback (most recent call last)file ""line in stopiteration once closeda stopiteration exception will be raised if further values are sent to coroutine the close(operation raises generatorexit inside the coroutine as described in the previous section on generators for exampledef receiver()print("ready to receive"trywhile truen (yieldprint("got %snexcept generatorexitprint("receiver done"exceptions can be raised inside coroutine using the throw(exctype [value [tb]]method where exctype is an exception typevalue is the exception valueand tb is traceback object for exampler throw(runtimeerror,"you're hosed!"traceback (most recent call last)file ""line in file ""line in receiver runtimeerroryou're hosedexceptions raised in this manner will originate at the currently executing yield statement in the coroutine coroutine can elect to catch exceptions and handle them as appropriate it is not safe to use throw(as an asynchronous signal to coroutine--it should never be invoked from separate execution thread or in signal handler coroutine may simultaneously receive and emit return values using yield if values are supplied in the yield expression here is an example that illustrates thisdef line_splitter(delimiter=none)print("ready to split"result none while trueline (yield resultresult line split(delimiterf lib fl ff
17,953
functions and functional programming in this casewe use the coroutine in the same way as before howevernow calls to send(also produce result for examples line_splitter("," next(ready to split send(" , , "[' '' ''cs send(" , , "[' '' '' 'understanding the sequencing of this example is critical the first next(call advances the coroutine to (yield result)which returns nonethe initial value of result on subsequent send(callsthe received value is placed in line and split into result the value returned by send(is the value passed to the next yield statement encountered in other wordsthe value returned by send(comes from the next yield expressionnot the one responsible for receiving the value passed by send(if coroutine returns valuessome care is required if exceptions raised with throw(are being handled if you raise an exception in coroutine using throw()the value passed to the next yield in the coroutine will be returned as the result of throw(if you need this value and forget to save itit will be lost using generators and coroutines at first glanceit might not be obvious how to use generators and coroutines for practical problems howevergenerators and coroutines can be particularly effective when applied to certain kinds of programming problems in systemsnetworkingand distributed computation for examplegenerator functions are useful if you want to set up processing pipelinesimilar in nature to using pipe in the unix shell one example of this appeared in the introduction here is another example involving set of generator functions related to findingopeningreadingand processing filesimport os import fnmatch def find_files(topdirpattern)for pathdirnamefilelist in os walk(topdir)for name in filelistif fnmatch fnmatch(namepattern)yield os path join(path,nameimport gzipbz def opener(filenames)for name in filenamesif name endswith(gz") gzip open(nameelif name endswith(bz ") bz bz file(nameelsef open(nameyield def cat(filelist)for in filelistfor line in fyield line def grep(patternlines)for line in linesif pattern in lineyield line lib fl ff
17,954
here is an example of using these functions to set up processing pipelinewwwlogs find("www","access-log*"files opener(wwwlogslines cat(filespylines grep("python"linesfor line in pylinessys stdout write(linein this examplethe program is processing all lines in all "access-log*files found within all subdirectories of top-level directory "wwweach "access-logis tested for file compression and opened using an appropriate file opener lines are concatenated together and processed through filter that is looking for substring "pythonthe entire program is being driven by the for statement at the end each iteration of this loop pulls new value through the pipeline and consumes it moreoverthe implementation is highly memory-efficient because no temporary lists or other large data structures are ever created coroutines can be used to write programs based on data-flow processing programs organized in this way look like inverted pipelines instead of pulling values through sequence of generator functions using for loopyou send values into collection of linked coroutines here is an example of coroutine functions written to mimic the generator functions shown previouslyimport os import fnmatch @coroutine def find_files(target)while truetopdirpattern (yieldfor pathdirnamefilelist in os walk(topdir)for name in filelistif fnmatch fnmatch(name,pattern)target send(os path join(path,name)import gzipbz @coroutine def opener(target)while truename (yieldif name endswith(gz") gzip open(nameelif name endswith(bz ") bz bz file(nameelsef open(nametarget send( @coroutine def cat(target)while truef (yieldfor line in ftarget send(linef lib fl ff
17,955
functions and functional programming @coroutine def grep(patterntarget)while trueline (yieldif pattern in linetarget send(line@coroutine def printer()while trueline (yieldsys stdout write(linehere is how you would link these coroutines to create dataflow processing pipelinefinder find_files(opener(cat(grep("python",printer())))nowsend value finder send(("www","access-log*")finder send(("otherwww","access-log*")in this exampleeach coroutine sends data to another coroutine specified in the target argument to each coroutine unlike the generator exampleexecution is entirely driven by pushing data into the first coroutine find_files(this coroutinein turnpushes data to the next stage critical aspect of this example is that the coroutine pipeline remains active indefinitely or until close(is explicitly called on it because of thisa program can continue to feed data into coroutine for as long as necessary--for examplethe two repeated calls to send(shown in the example coroutines can be used to implement form of concurrency for examplea centralized task manager or event loop can schedule and send data into large collection of hundreds or even thousands of coroutines that carry out various processing tasks the fact that input data is "sentto coroutine also means that coroutines can often be easily mixed with programs that use message queues and message passing to communicate between program components further information on this can be found in "threads list comprehensions common operation involving functions is that of applying function to all of the items of listcreating new list with the results for examplenums [ squares [for in numssquares append( nbecause this type of operation is so commonit is has been turned into an operator known as list comprehension here is simple examplenums [ squares [ for in numsthe general syntax for list comprehension is as follows[expression for item in iterable if condition for item in iterable if condition for itemn in iterablen if conditionn lib fl ff
17,956
this syntax is roughly equivalent to the following codes [for item in iterable if condition for item in iterable if condition for itemn in iterablenif conditionns append(expressionto illustratehere are some more examplesa [- , , ,- , , 'abcc [ * for in ad [ for in if > [( ,yfor in for in if [( , )( , )( , ) [math sqrt( * + *yfor , in fc [- , , ,- , , [ , , , [( ,' '),( ,' '),( ,' ')( ,' '),( ,' '),( ,' ')( ,' '),( ,' '),( ,' ')( ,' '),( ,' '),( ,' ') [ the sequences supplied to list comprehension don' have to be the same length because they're iterated over their contents using nested set of for loopsas previously shown the resulting list contains successive values of expressions the if clause is optionalhoweverif it' usedexpression is evaluated and added to the result only if condition is true if list comprehension is used to construct list of tuplesthe tuple values must be enclosed in parentheses for example[( ,yfor in for in bis legal syntaxwhereas [ , for in for in bis not finallyit is important to note that in python the iteration variables defined within list comprehension are evaluated within the current scope and remain defined after the list comprehension has executed for examplein [ for in ]the iteration variable overwrites any previously defined value of and is set to the value of the last item in after the resulting list is created fortunatelythis is not the case in python where the iteration variable remains private generator expressions generator expression is an object that carries out the same computation as list comprehensionbut which iteratively produces the result the syntax is the same as for list comprehensions except that you use parentheses instead of square brackets here' an example(expression for item in iterable if condition for item in iterable if condition for itemn in iterablen if conditionnf lib fl ff
17,957
functions and functional programming unlike list comprehensiona generator expression does not actually create list or immediately evaluate the expression inside the parentheses insteadit creates generator object that produces the values on demand via iteration here' an examplea [ ( * for in ab next( next( the difference between list and generator expressions is importantbut subtle with list comprehensionpython actually creates list that contains the resulting data with generator expressionpython creates generator that merely knows how to produce data on demand in certain applicationsthis can greatly improve performance and memory use here' an exampleread file open("data txt"lines ( strip(for in fopen file read linesstrip trailing/leading whitespace comments ( for in lines if [ ='#'all comments for in commentsprint(cin this examplethe generator expression that extracts lines and strips whitespace does not actually read the entire file into memory the same is true of the expression that extracts comments insteadthe lines of the file are actually read when the program starts iterating in the for loop that follows during this iterationthe lines of the file are produced upon demand and filtered accordingly in factat no time will the entire file be loaded into memory during this process thereforethis would be highly efficient way to extract comments from gigabyte-sized python source file unlike list comprehensiona generator expression does not create an object that works like sequence it can' be indexedand none of the usual list operations will work (for exampleappend()howevera generator expression can be converted into list using the built-in list(functionclist list(commentsdeclarative programming list comprehensions and generator expressions are strongly tied to operations found in declarative languages in factthe origin of these features is loosely derived from ideas in mathematical set theory for examplewhen you write statement such as [ * for in if ]it' somewhat similar to specifying set such as oeax instead of writing programs that manually iterate over datayou can use these declarative features to structure programs as series of computations that simply operate on all of the data all at once for examplesuppose you had file "portfolio txtcontaining stock portfolio data like thisf lib fl ff
17,958
aa ibm cat msft ge msft ibm here is declarative-style program that calculates the total cost by summing up the second column multiplied by the third columnlines open("portfolio txt"fields (line split(for line in linesprint(sum(float( [ ]float( [ ]for in fields)in this programwe really aren' concerned with the mechanics of looping line-by-line over the file insteadwe just declare sequence of calculations to perform on all of the data not only does this approach result in highly compact codebut it also tends to run faster than this more traditional versiontotal for line in open("portfolio txt")fields line split(total +float(fields[ ]float(fields[ ]print(totalthe declarative programming style is somewhat tied to the kinds of operations programmer might perform in unix shell for instancethe preceding example using generator expressions is similar to the following one-line awk commandawk 'total +$ $ end print total }portfolio txt the declarative style of list comprehensions and generator expressions can also be used to mimic the behavior of sql select statementscommonly used when processing databases for exampleconsider these examples that work on data that has been read in list of dictionariesfields (line split(for line in open("portfolio txt")portfolio {'namef[ ]'sharesint( [ ])'pricefloat( [ ]for in fieldssome queries msft [ for in portfolio if ['name'='msft'large_holdings [ for in portfolio if ['shares']* ['price'> in factif you are using module related to database access (see )you can often use list comprehensions and database queries together all at once for examplesum(shares*cost for shares,cost in cursor execute("select sharescost from portfolio"if shares*cost > lib fl ff
17,959
functions and functional programming the lambda operator anonymous functions in the form of an expression can be created using the lambda statementlambda args expression args is comma-separated list of argumentsand expression is an expression involving those arguments here' an examplea lambda , + ( , gets the code defined with lambda must be valid expression multiple statements and other non-expression statementssuch as for and whilecannot appear in lambda statement lambda expressions follow the same scoping rules as functions the primary use of lambda is in specifying short callback functions for exampleif you wanted to sort list of names with case-insensitivityyou might write thisnames sort(key=lambda nn lower()recursion recursive functions are easily defined for exampledef factorial( )if < return elsereturn factorial( howeverbe aware that there is limit on the depth of recursive function calls the function sys getrecursionlimit(returns the current maximum recursion depthand the function sys setrecursionlimit(can be used to change the value the default value is although it is possible to increase the valueprograms are still limited by the stack size limits enforced by the host operating system when the recursion depth is exceededa runtimeerror exception is raised python does not perform tailrecursion optimization that you often find in functional languages such as scheme recursion does not work as you might expect in generator functions and coroutines for examplethis code prints all items in nested collection of listsdef flatten(lists)for in listsif isinstance( ,list)flatten(selseprint(sitems [[ , , ],[ , ,[ , ]],[ , , ]flatten(itemsprints howeverif you change the print operation to yieldit no longer works this is because the recursive call to flatten(merely creates new generator object without actually iterating over it here' recursive generator version that worksf lib fl ff
17,960
def genflatten(lists)for in listsif isinstance( ,list)for item in genflatten( )yield item elseyield item care should also be taken when mixing recursive functions and decorators if decorator is applied to recursive functionall inner recursive calls now get routed through the decorated version for example@locked def factorial( )if < return elsereturn factorial( calls the wrapped version of factorial if the purpose of the decorator was related to some kind of system management such as synchronization or lockingrecursion is something probably best avoided documentation strings it is common practice for the first statement of function to be documentation string describing its usage for exampledef factorial( )"""computes factorial for examplefactorial( ""if < return elsereturn *factorial( - the documentation string is stored in the _doc_ attribute of the function that is commonly used by ides to provide interactive help if you are using decoratorsbe aware that wrapping function with decorator can break the help features associated with documentation strings for exampleconsider this codedef wrap(func)call(*args,**kwargs)return func(*args,**kwargsreturn call @wrap def factorial( )"""computes factorial ""if user requests help on this version of factorial()he will get rather cryptic explanationhelp(factorialhelp on function call in module _main_ _call(*args**kwargs(endf lib fl ff
17,961
functions and functional programming to fix thiswrite decorator functions so that they propagate the function name and documentation string for exampledef wrap(func)call(*args,**kwargs)return func(*args,**kwargscall _doc_ func _doc_ call _name_ func _name_ return call because this is common problemthe functools module provides function wraps that can automatically copy these attributes not surprisinglyit is also decoratorfrom functools import wraps def wrap(func)@wraps(funccall(*args,**kwargs)return func(*args,**kwargsreturn call the @wraps(funcdecoratordefined in functoolspropagates attributes from func to the wrapper function that is being defined function attributes functions can have arbitrary attributes attached to them here' an exampledef foo()statements foo secure foo private function attributes are stored in dictionary that is available as the __dict__ attribute of function the primary use of function attributes is in highly specialized applications such as parser generators and application frameworks that would like to attach additional information to function objects as with documentation stringscare should be given if mixing function attributes with decorators if function is wrapped by decoratoraccess to the attributes will actually take place on the decorator functionnot the original implementation this may or may not be what you want depending on the application to propagate already defined function attributes to decorator functionuse the following template or the functools wraps(decorator as shown in the previous sectiondef wrap(func)call(*args,**kwargs)return func(*args,**kwargscall _doc_ func _doc_ call _name_ func _name_ call _dict_ update(func _dict_ _return call lib fl ff
17,962
eval()exec()and compile(the eval(str [,globals [,locals]]function executes an expression string and returns the result here' an examplea eval(' *math sin( + 'similarlythe exec(str [globals [locals]]function executes string containing arbitrary python code the code supplied to exec(is executed as if the code actually appeared in place of the exec operation here' an examplea [ exec("for in aprint( )"one caution with exec is that in python exec is actually defined as statement thusin legacy codeyou might see statements invoking exec without the surrounding parenthesessuch as exec "for in aprint ialthough this still works in python it breaks in python modern programs should use exec(as function both of these functions execute within the namespace of the caller (which is used to resolve any symbols that appear within string or fileoptionallyeval(and exec(can accept one or two mapping objects that serve as the global and local namespaces for the code to be executedrespectively here' an exampleglobals {' ' ' ' 'birds'['parrot''swallow''albatross'locals execute using the above dictionaries as the global and local namespace eval(" "globalslocalsexec("for in birdsprint( )"globalslocalsif you omit one or both namespacesthe current values of the global and local namespaces are used alsodue to issues related to nested scopesthe use of exec(inside of function body may result in syntaxerror exception if that function also contains nested function definitions or uses the lambda operator when string is passed to exec(or eval(the parser first compiles it into bytecode because this process is expensiveit may be better to precompile the code and reuse the bytecode on subsequent calls if the code will be executed multiple times the compile(str,filename,kindfunction compiles string into bytecode in which str is string containing the code to be compiled and filename is the file in which the string is defined (for use in traceback generationthe kind argument specifies the type of code being compiled--'singlefor single statement'execfor set of statementsor 'evalfor an expression the code object returned by the compile(function can also be passed to the eval(function and exec(statement here' an examples "for in range( , )print( ) compile( ,'','exec'compile into code object exec(cexecute it " yc compile( '''eval'result eval( compile into an expression execute it lib fl ff
17,963
lib fl ff
17,964
classes and object-oriented programming lasses are the mechanism used to create new kinds of objects this covers the details of classesbut is not intended to be an in-depth reference on object-oriented programming and design it' assumed that the reader has some prior experience with data structures and object-oriented programming in other languages such as or java ("types and objects,contains additional information about the terminology and internal implementation of objects the class statement class defines set of attributes that are associated withand shared bya collection of objects known as instances class is most commonly collection of functions (known as methods)variables (which are known as class variables)and computed attributes (which are known as propertiesa class is defined using the class statement the body of class contains series of statements that execute during class definition here' an exampleclass account(object)num_accounts def _init_ (self,name,balance)self name name self balance balance account num_accounts + def _del_ (self)account num_accounts - def deposit(self,amt)self balance self balance amt def withdraw(self,amt)self balance self balance amt def inquiry(self)return self balance the values created during the execution of the class body are placed into class object that serves as namespace much like module for examplethe members of the account class are accessed as followsaccount num_accounts account _init_ account _del_ account deposit account withdraw account inquiry lib fl ff
17,965
classes and object-oriented programming it' important to note that class statement by itself doesn' create any instances of the class (for exampleno accounts are actually created in the preceding examplerathera class merely sets up the attributes that will be common to all the instances that will be created later in this senseyou might think of it as blueprint the functions defined inside class are known as instance methods an instance method is function that operates on an instance of the classwhich is passed as the first argument by conventionthis argument is called selfalthough any legal identifier name can be used in the preceding exampledeposit()withdraw()and inquiry(are examples of instance methods class variables such as num_accounts are values that are shared among all instances of class (that isthey're not individually assigned to each instancein this caseit' variable that' keeping track of how many account instances are in existence class instances instances of class are created by calling class object as function this creates new instance that is then passed to the _init_ (method of the class the arguments to _init_ (consist of the newly created instance self along with the arguments supplied when calling the class object for examplecreate few accounts account("guido" account("bill" invokes account _init_ ( ,"guido", inside _init_ ()attributes are saved in the instance by assigning to self for exampleself name name is saving name attribute in the instance once the newly created instance has been returned to the userthese attributes as well as attributes of the class are accessed using the dot operator as followsa deposit( withdraw( name name calls account deposit( , calls account withdraw( , get account name the dot operator is responsible for attribute binding when you access an attributethe resulting value may come from several different places for examplea name in the previous example returns the name attribute of the instance howevera deposit returns the deposit attribute ( methodof the account class when you access an attributethe instance is checked first and if nothing is knownthe search moves to the instance' class instead this is the underlying mechanism by which class shares its attributes with all of its instances scoping rules although classes define namespaceclasses do not create scope for names used inside the bodies of methods thereforewhen you're implementing classreferences to attributes and methods must be fully qualified for examplein methods you always reference attributes of the instance through self thusin the example you use self balancenot balance this also applies if you want to call method from another methodas shown in the following examplef lib fl ff
17,966
class foo(object)def bar(self)print("bar!"def spam(self)bar(selfincorrect'bargenerates nameerror self bar(this works foo bar(selfthis also works the lack of scoping in classes is one area where python differs from +or java if you have used those languagesthe self parameter in python is the same as the this pointer the explicit use of self is required because python does not provide means to explicitly declare variables (that isa declaration such as int or float in cwithout thisthere is no way to know whether an assignment to variable in method is supposed to be local variable or if it' supposed to be saved as an instance attribute the explicit use of self fixes this--all values stored on self are part of the instance and all other assignments are just local variables inheritance inheritance is mechanism for creating new class that specializes or modifies the behavior of an existing class the original class is called base class or superclass the new class is called derived class or subclass when class is created via inheritanceit "inheritsthe attributes defined by its base classes howevera derived class may redefine any of these attributes and add new attributes of its own inheritance is specified with comma-separated list of base-class names in the class statement if there is no logical base classa class inherits from objectas has been shown in prior examples object is class which is the root of all python objects and which provides the default implementation of some common methods such as _str_ ()which creates string for use in printing inheritance is often used to redefine the behavior of existing methods as an examplehere' specialized version of account that redefines the inquiry(method to periodically overstate the current balance with the hope that someone not paying close attention will overdraw his account and incur big penalty when making payment on their subprime mortgageimport random class evilaccount(account)def inquiry(self)if random randint( , = return self balance elsereturn self balance notepatent pending idea evilaccount("george" deposit( calls account deposit( , available inquiry(calls evilaccount inquiry(cin this exampleinstances of evilaccount are identical to instances of account except for the redefined inquiry(method inheritance is implemented with only slight enhancement of the dot operator specificallyif the search for an attribute doesn' find match in the instance or the instance' classthe search moves on to the base class this process continues until there are no more base classes to search in the previous examplethis explains why deposit(calls the implementation of deposit(defined in the account class lib fl ff
17,967
classes and object-oriented programming subclass can add new attributes to the instances by defining its own version of _init_ (for examplethis version of evilaccount adds new attribute evilfactorclass evilaccount(account)def _init_ (self,name,balance,evilfactor)account _init_ (self,name,balanceinitialize account self evilfactor evilfactor def inquiry(self)if random randint( , = return self balance self evilfactor elsereturn self balance when derived class defines _init_ ()the _init_ (methods of base classes are not automatically invoked thereforeit' up to derived class to perform the proper initialization of the base classes by calling their _init_ (methods in the previous examplethis is shown in the statement that calls account _init_ (if base class does not define _init_ ()this step can be omitted if you don' know whether the base class defines _init_ ()it is always safe to call it without any arguments because there is always default implementation that simply does nothing occasionallya derived class will reimplement method but also want to call the original implementation to do thisa method can explicitly call the original method in the base classpassing the instance self as the first parameter as shown hereclass moreevilaccount(evilaccount)def deposit(self,amount)self withdraw( subtract the "conveniencefee evilaccount deposit(self,amountnowmake deposit subtlety in this example is that the class evilaccount doesn' actually implement the deposit(method insteadit is implemented in the account class although this code worksit might be confusing to someone reading the code ( was evilaccount supposed to implement deposit()?thereforean alternative solution is to use the super(function as followsclass moreevilaccount(evilaccount)def deposit(self,amount)self withdraw( subtract convenience fee super(moreevilaccount,selfdeposit(amountnowmake deposit super(clsinstancereturns special object that lets you perform attribute lookups on the base classes if you use thispython will search for an attribute using the normal search rules that would have been used on the base classes this frees you from hard-coding the exact location of method and more clearly states your intentions (that isyou want to call the previous implementation without regard for which base class defines itunfortunatelythe syntax of super(leaves much to be desired if you are using python you can use the simplified statement super(deposit(amountto carry out the calculation shown in the example in python howeveryou have to use the more verbose version python supports multiple inheritance this is specified by having class list multiple base classes for examplehere are collection of classesf lib fl ff
17,968
class depositcharge(object)fee def deposit_fee(self)self withdraw(self feeclass withdrawcharge(object)fee def withdraw_fee(self)self withdraw(self feeclass using multiple inheritance class mostevilaccount(evilaccountdepositchargewithdrawcharge)def deposit(self,amt)self deposit_fee(super(mostevilaccount,selfdeposit(amtdef withdraw(self,amt)self withdraw_fee(super(mostevilacount,selfwithdraw(amtwhen multiple inheritance is usedattribute resolution becomes considerably more complicated because there are many possible search paths that could be used to bind attributes to illustrate the possible complexityconsider the following statementsd mostevilaccount("dave", , deposit_fee(calls depositcharge deposit_fee(fee is withdraw_fee(calls withdrawcharge withdraw_fee(fee is ?in this examplemethods such as deposit_fee(and withdraw_fee(are uniquely named and found in their respective base classes howeverthe withdraw_fee(function doesn' seem to work right because it doesn' actually use the value of fee that was initialized in its own class what has happened is that the attribute fee is class variable defined in two different base classes one of those values is usedbut which one(hintit' depositcharge fee to find attributes with multiple inheritanceall base classes are ordered in list from the "most specializedclass to the "least specializedclass thenwhen searching for an attributethis list is searched in order until the first definition of the attribute is found in the examplethe class evilaccount is more specialized than account because it inherits from account similarlywithin mostevilaccountdepositcharge is considered to be more specialized than withdrawcharge because it is listed first in the list of base classes for any given classthe ordering of base classes can be viewed by printing its _mro_ attribute here' an examplemostevilaccount _mro_ (in most casesthis list is based on rules that "make sense "that isa derived class is always checked before its base classes and if class has more than one parentthe parents are always checked in the same order as listed in the class definition howeverthe precise ordering of base classes is actually quite complex and not based on any sort of "simplealgorithm such as depth-first or breadth-first search insteadthe ordering is determined according to the linearization algorithmwhich is described in the paper " monotonic superclass linearization for dylan( barrettet alpresented at lib fl ff
17,969
classes and object-oriented programming oopsla' subtle aspect of this algorithm is that certain class hierarchies will be rejected by python with typeerror here' an exampleclass (object)pass class ( )pass class ( , )pass typeerror can' create consistent method resolution order_ in this casethe method resolution algorithm rejects class because it can' determine an ordering of the base classes that makes sense for examplethe class appears before class in the inheritance listso it must be checked first howeverclass is more specialized because it inherits from thereforeif is checked firstit would not be possible to resolve specialized methods in in practicethese issues should rarely arise--and if they doit usually indicates more serious design problem with program as general rulemultiple inheritance is something best avoided in most programs howeverit is sometimes used to define what are known as mixin classes mixin class typically defines set of methods that are meant to be "mixed into other classes in order to add extra functionality (almost like macrotypicallythe methods in mixin will assume that other methods are present and will build upon them the depositcharge and withdrawcharge classes in the earlier example illustrate this these classes add new methods such as deposit_fee(to classes that include them as one of the base classes howeveryou would never instantiate depositcharge by itself in factif you didit wouldn' create an instance that could be used for anything useful (that isthe one defined method wouldn' even execute correctlyjust as final noteif you wanted to fix the problematic references to fee in this examplethe implementation of deposit_fee(and withdraw_fee(should be changed to refer to the attribute directly using the class name instead of self (for exampledepositchange feepolymorphism dynamic binding and duck typing dynamic binding (also sometimes referred to as polymorphism when used in the context of inheritanceis the capability to use an instance without regard for its type it is handled entirely through the attribute lookup process described for inheritance in the preceding section whenever an attribute is accessed as obj attrattr is located by searching within the instance itselfthe instance' class definitionand then base classesin that order the first match found is returned critical aspect of this binding process is that it is independent of what kind of object obj is thusif you make lookup such as obj nameit will work on any obj that happens to have name attribute this behavior is sometimes referred to as duck typing in reference to the adage "if it looks likequacks likeand walks like duckthen it' duck python programmers often write programs that rely on this behavior for exampleif you want to make customized version of an existing objectyou can either inherit from it or you can simply create completely new object that looks and acts like it but is otherwise unrelated this latter approach is often used to maintain loose coupling of program components for examplecode may be written to work with any kind of object whatsoever as long as it has certain set of methods one of the most common examples is with various "file-likeobjects defined in the standard library although these objects work like filesthey don' inherit from the built-in file object lib fl ff
17,970
static methods and class methods in class definitionall functions are assumed to operate on an instancewhich is always passed as the first parameter self howeverthere are two other common kinds of methods that can be defined static method is an ordinary function that just happens to live in the namespace defined by class it does not operate on any kind of instance to define static methoduse the @staticmethod decorator as shown hereclass foo(object)@staticmethod def add( , )return to call static methodyou just prefix it by the class name you do not pass it any additional information for examplex foo add( , common use of static methods is in writing classes where you might have many different ways to create new instances because there can only be one _init_ (functionalternative creation functions are often defined as shown hereclass date(object)def _init_ (self,year,month,day)self year year self month month self day day @staticmethod def now() time localtime(return date( tm_yeart tm_mont tm_day@staticmethod def tomorrow() time localtime(time time()+ return date( tm_yeart tm_mont tm_dayexample of creating some dates date( date now(calls static method now( date tomorrow(calls static method tomorrow(class methods are methods that operate on the class itself as an object defined using the @classmethod decoratora class method is different than an instance method in that the class is passed as the first argument which is named cls by convention for exampleclass times(object)factor @classmethod def mul(cls, )return cls factor* class twotimes(times)factor twotimes mul( calls times mul(twotimes - lib fl ff
17,971
classes and object-oriented programming in this examplenotice how the class twotimes is passed to mul(as an object although this example is esotericthere are practicalbut subtleuses of class methods as an examplesuppose that you defined class that inherited from the date class shown previously and customized it slightlyclass eurodate(date)modify string conversion to use european dates def _str_ (self)return "% /% /% (self dayself monthself yearbecause the class inherits from dateit has all of the same features howeverthe now(and tomorrow(methods are slightly broken for exampleif someone calls eurodate now() date object is returned instead of eurodate object class method can fix thisclass date(object)@classmethod def now(cls) time localtime(create an object of the appropriate type return cls( tm_yeart tm_montht tm_dayclass eurodate(date) date now( eurodate now(calls date now(dateand returns date calls date now(eurodateand returns eurodate one caution about static and class methods is that python does not manage these methods in separate namespace than the instance methods as resultthey can be invoked on an instance for examplea date( , , now(calls date now(datethis is potentially quite confusing because call to now(doesn' really have anything to do with the instance this behavior is one area where the python object system differs from that found in other oo languages such as smalltalk and ruby in those languagesclass methods are strictly separate from instance methods properties normallywhen you access an attribute of an instance or classthe associated value that is stored is returned property is special kind of attribute that computes its value when accessed here is simple exampleclass circle(object)def _init_ (self,radius)self radius radius some additional properties of circles @property def area(self)return math pi*self radius** @property def perimeter(self)return *math pi*self radius lib fl ff
17,972
the resulting circle object behaves as followsc circle( radius area perimeter area traceback (most recent call last)file ""line in attributeerrorcan' set attribute in this examplecircle instances have an instance variable radius that is stored area and perimeter are simply computed from that value the @property decorator makes it possible for the method that follows to be accessed as simple attributewithout the extra (that you would normally have to add to call the method to the user of the objectthere is no obvious indication that an attribute is being computed other than the fact that an error message is generated if an attempt is made to redefine the attribute (as shown in the attributeerror exception aboveusing properties in this way is related to something known as the uniform access principle essentiallyif you're defining classit is always good idea to make the programming interface to it as uniform as possible without propertiescertain attributes of an object would be accessed as simple attribute such as radius whereas other attributes would be accessed as methods such as area(keeping track of when to add the extra (adds unnecessary confusion property can fix this python programmers don' often realize that methods themselves are implicitly handled as kind of property consider this classclass foo(object)def _init_ (self,name)self name name def spam(self, )print("% % (self namexwhen user creates an instance such as foo("guido"and then accesses spamthe original function object spam is not returned insteadyou get something known as bound methodwhich is an object that represents the method call that will execute when the (operator is invoked on it bound method is like partially evaluated function where the self parameter has already been filled inbut the additional arguments still need to be supplied by you when you call it using (the creation of this bound method object is silently handled through property function that executes behind the scenes when you define static and class methods using @staticmethod and @classmethodyou are actually specifying the use of different property function that will handle the access to those methods in different way for example@staticmethod simply returns the method function back "as iswithout any special wrapping or processing properties can also intercept operations to set and delete an attribute this is done by attaching additional setter and deleter methods to property here is an examplef lib fl ff
17,973
classes and object-oriented programming class foo(object)def _init_ (self,name)self _name name @property def name(self)return self _name @name setter def name(self,value)if not isinstance(value,str)raise typeerror("must be string!"self _name value @name deleter def name(self)raise typeerror("can' delete name" foo("guido" name name "montyf name del name calls name(get function calls setter name( ,"monty"calls setter name( , -typeerror calls deleter name( -typeerror in this examplethe attribute name is first defined as read-only property using the @property decorator and associated method the @name setter and @name deleter decorators that follow are associating additional methods with the set and deletion operations on the name attribute the names of these methods must exactly match the name of the original property in these methodsnotice that the actual value of the name is stored in an attribute _name the name of the stored attribute does not have to follow any conventionbut it has to be different than the property in order to distinguish it from the name of the property itself in older codeyou will often see properties defined using the property(getf=nonesetf=nonedelf=nonedoc=nonefunction with set of uniquely named methods for carrying out each operation for exampleclass foo(object)def getname(self)return self _name def setname(self,value)if not isinstance(value,str)raise typeerror("must be string!"self _name value def delname(self)raise typeerror("can' delete name"name property(getname,setname,delnamethis older approach is still supportedbut the decorator version tends to lead to classes that are little more polished for exampleif you use decoratorsthe getsetand delete functions aren' also visible as methods descriptors with propertiesaccess to an attribute is controlled by series of user-defined getsetand delete functions this sort of attribute control can be further generalized through the use of descriptor object descriptor is simply an object that represents the value of an attribute by implementing one or more of the special methods _get_ () _set_ ()and _delete_ ()it can hook into the attribute access mechanism and can customize those operations here is an examplef lib fl ff
17,974
class typedproperty(object)def _init_ (self,name,type,default=none)self name "_name self type type self default default if default else type(def _get_ (self,instance,cls)return getattr(instance,self name,self defaultdef _set_ (self,instance,value)if not isinstance(value,self type)raise typeerror("must be %sself typesetattr(instance,self name,valuedef _delete_ (self,instance)raise attributeerror("can' delete attribute"class foo(object)name typedproperty("name",strnum typedproperty("num",int, in this examplethe class typedproperty defines descriptor where type checking is performed when the attribute is assigned and an error is produced if an attempt is made to delete the attribute for examplef foo( name name "guidodel name implicitly calls foo name _get_ ( ,foocalls foo name _set_ ( ,"guido"calls foo name _delete_ (fdescriptors can only be instantiated at the class level it is not legal to create descriptors on per-instance basis by creating descriptor objects inside _init_ (and other methods alsothe attribute name used by the class to hold descriptor takes precedence over attributes stored on instances in the previous examplethis is why the descriptor object takes name parameter and why the name is changed slightly by inserting leading underscore in order for the descriptor to store value on the instanceit has to pick name that is different than that being used by the descriptor itself data encapsulation and private attributes by defaultall attributes and methods of class are "public "this means that they are all accessible without any restrictions it also implies that everything defined in base class is inherited and accessible within derived class this behavior is often undesirable in object-oriented applications because it exposes the internal implementation of an object and can lead to namespace conflicts between objects defined in derived class and those defined in base class to fix this problemall names in class that start with double underscoresuch as _fooare automatically mangled to form new name of the form _classname_ _foo this effectively provides way for class to have private attributes and methods because private names used in derived class won' collide with the same private names used in base class here' an exampleclass (object)def _init_ (self)self _x def _spam(self)pass def bar(self)self _spam(mangled to self _a_ _x mangled to _a_ _spam(only calls _spam( lib fl ff
17,975
classes and object-oriented programming class ( )def _init_ (self) _init_ (selfself _x def _spam(self)pass mangled to self _b_ _x mangled to _b_ _spam(although this scheme provides the illusion of data hidingthere' no strict mechanism in place to actually prevent access to the "privateattributes of class in particularif the name of the class and corresponding private attribute are knownthey can be accessed using the mangled name class can make these attributes less visible by redefining the _dir_ (methodwhich supplies the list of names returned by the dir(function that' used to inspect objects although this name mangling might look like an extra processing stepthe mangling process actually only occurs once at the time class is defined it does not occur during execution of the methodsnor does it add extra overhead to program execution alsobe aware that name mangling does not occur in functions such as getattr()hasattr()setattr()or delattr(where the attribute name is specified as string for these functionsyou need to explicitly use the mangled name such as _classname_ _name to access the attribute it is recommended that private attributes be used when defining mutable attributes via properties by doing soyou will encourage users to use the property name rather than accessing the underlying instance data directly (which is probably not what you intended if you wrapped it with property to begin withan example of this appeared in the previous section giving method private name is technique that superclass can use to prevent derived class from redefining and changing the implementation of method for examplethe bar(method in the example only calls _spam()regardless of the type of self or the presence of different _spam(method in derived class finallydon' confuse the naming of private class attributes with the naming of "privatedefinitions in module common mistake is to define class where single leading underscore is used on attribute names in an effort to hide their values ( _namein modulesthis naming convention prevents names from being exported by the from module import statement howeverin classesthis naming convention does not hide the attribute nor does it prevent name clashes that arise if someone inherits from the class and defines new attribute or method with the same name object memory management when class is definedthe resulting class is factory for creating new instances for exampleclass circle(object)def _init_ (self,radius)self radius radius create some circle instances circle( circle( lib fl ff
17,976
the creation of an instance is carried out in two steps using the special method _new_ ()which creates new instanceand _init_ ()which initializes it for examplethe operation circle( performs these stepsc circle _new_ (circle if isinstance( ,circle)circle _init_ ( , the _new_ (method of class is something that is rarely defined by user code if it is definedit is typically written with the prototype _new_ (cls*args**kwargswhere args and kwargs are the same arguments that will be passed to _init_ ( _new_ (is always class method that receives the class object as the first parameter although _new_ (creates an instanceit does not automatically call _init_ (if you see _new_ (defined in classit usually means the class is doing one of two things firstthe class might be inheriting from base class whose instances are immutable this is common if defining objects that inherit from an immutable built-in type such as an integerstringor tuple because _new_ (is the only method that executes prior to the instance being created and is the only place where the value could be modified (in _init_ ()it would be too latefor exampleclass upperstr(str)def _new_ (cls,value="")return str _new_ (clsvalue upper() upperstr("hello"value is "hellothe other major use of _new_ (is when defining metaclasses this is described at the end of this once createdinstances are managed by reference counting if the reference count reaches zerothe instance is immediately destroyed when the instance is about to be destroyedthe interpreter first looks for _del_ (method associated with the object and calls it in practiceit' rarely necessary for class to define _del_ (method the only exception is when the destruction of an object requires cleanup action such as closing fileshutting down network connectionor releasing other system resources even in these casesit' dangerous to rely on _del_ (for clean shutdown because there' no guarantee that this method will be called when the interpreter exits better approach may be to define method such as close(that program can use to explicitly perform shutdown occasionallya program will use the del statement to delete reference to an object if this causes the reference count of the object to reach zerothe _del_ (method is called howeverin generalthe del statement doesn' directly call _del_ ( subtle danger involving object destruction is that instances for which _del_ (is defined cannot be collected by python' cyclic garbage collector (which is strong reason not to define _del_ unless you need toprogrammers coming from languages without automatic garbage collection ( ++should take care not to adopt programming style where _del_ (is unnecessarily defined although it is rare to break the garbage collector by defining _del_ ()there are certain types of programming patternsespecially those involving parent-child relationships or graphswhere this lib fl ff
17,977
classes and object-oriented programming can be problem for examplesuppose you had an object that was implementing variant of the "observer pattern class account(object)def _init_ (self,name,balance)self name name self balance balance self observers set(def _del_ (self)for ob in self observersob close(del self observers def register(self,observer)self observers add(observerdef unregister(self,observer)self observers remove(observerdef notify(self)for ob in self observersob update(def withdraw(self,amt)self balance -amt self notify(class accountobserver(object)def _init_ (selftheaccount)self theaccount theaccount theaccount register(selfdef _del_ (self)self theaccount unregister(selfdel self theaccount def update(self)print("balance is % fself theaccount balancedef close(self)print("account no longer in use"example setup account('dave', a_ob accountobserver(ain this codethe account class allows set of accountobserver objects to monitor an account instance by receiving an update whenever the balance changes to do thiseach account keeps set of the observers and each accountobserver keeps reference back to the account each class has defined _del_ (in an attempt to provide some sort of cleanup (such as unregistering and so onhoweverit just doesn' work insteadthe classes have created reference cycle in which the reference count never drops to and there is no cleanup not only thatthe garbage collector (the gc modulewon' even clean it upresulting in permanent memory leak one way to fix the problem shown in this example is for one of the classes to create weak reference to the other using the weakref module weak reference is way of creating reference to an object without increasing its reference count to work with weak referenceyou have to add an extra bit of functionality to check whether the object being referred to still exists here is an example of modified observer classimport weakref class accountobserver(object)def _init_ (selftheaccount)self accountref weakref ref(theaccounttheaccount register(selfcreate weakref lib fl ff
17,978
def _del_ (self)acc self accountref(get account if accunregister if still exists acc unregister(selfdef update(self)print("balance is % fself accountref(balancedef close(self)print("account no longer in use"example setup account('dave', a_ob accountobserver(ain this examplea weak reference accountref is created to access the underlying accountyou call it like function this either returns the account or none if it' no longer around with this modificationthere is no longer reference cycle if the account object is destroyedits _del_ method runs and observers receive notification the gc module also works properly more information about the weakref module can be found in "python runtime services object representation and attribute binding internallyinstances are implemented using dictionary that' accessible as the instance' __dict__ attribute this dictionary contains the data that' unique to each instance here' an examplea account('guido' _dict_ {'balance' 'name''guido'new attributes can be added to an instance at any timelike thisa number add attribute 'numberto _dict_ modifications to an instance are always reflected in the local _dict_ attribute likewiseif you make modifications to _dict_ directlythose modifications are reflected in the attributes instances are linked back to their class by special attribute _class_ the class itself is also just thin layer over dictionary which can be found in its own _dict_ attribute the class dictionary is where you find the methods for examplea _class_ account _dict_ keys([' _dict_ '' _module_ ''inquiry''deposit''withdraw'' _del_ ''num_accounts'' _weakref_ '' _doc_ '' _init_ 'finallyclasses are linked to their base classes in special attribute _bases_ _which is tuple of the base classes this underlying structure is the basis for all of the operations that getsetand delete the attributes of objects whenever an attribute is set using obj name valuethe special method obj _setattr_ ("name"valueis invoked if an attribute is deleted using del obj namethe special method obj _delattr_ ("name"is invoked the default behavior of these methods is to modify or remove values from the local _dict_ of obj unless the requested attribute happens to correspond to property or descriptor in lib fl ff
17,979
classes and object-oriented programming that casethe set and delete operation will be carried out by the set and delete functions associated with the property for attribute lookup such as obj namethe special method obj _getattrribute_ ("name"is invoked this method carries out the search process for finding the attributewhich normally includes checking for propertieslooking in the local _dict_ attributechecking the class dictionaryand searching the base classes if this search process failsa final attempt to find the attribute is made by trying to invoke the _getattr_ (method of the class (if definedif this failsan attributeerror exception is raised user-defined classes can implement their own versions of the attribute access functionsif desired for exampleclass circle(object)def _init_ (self,radius)self radius radius def _getattr_ (self,name)if name ='area'return math pi*self radius** elif name ='perimeter'return *math pi*self radius elsereturn object _getattr_ (self,namedef _setattr_ (self,name,value)if name in ['area','perimeter']raise typeerror("% is readonlynameobject _setattr_ (self,name,valuea class that reimplements these methods should probably rely upon the default implementation in object to carry out the actual work this is because the default implementation takes care of the more advanced features of classes such as descriptors and properties as general ruleit is relatively uncommon for classes to redefine the attribute access operators howeverone application where they are often used is in writing generalpurpose wrappers and proxies to existing objects by redefining _getattr_ () _setattr_ ()and _delattr_ () proxy can capture attribute access and transparently forward those operations on to another object _slots_ class can restrict the set of legal instance attribute names by defining special variable called _slots_ here' an exampleclass account(object) _slots_ ('name','balance'when _slots_ is definedthe attribute names that can be assigned on instances are restricted to the names specified otherwisean attributeerror exception is raised this restriction prevents someone from adding new attributes to existing instances and solves the problem that arises if someone assigns value to an attribute that they can' spell correctly in reality_ _slots_ was never implemented to be safety feature insteadit is actually performance optimization for both memory and execution speed instances of class that uses _slots_ no longer use dictionary for storing instance data insteada much more compact data structure based on an array is used in programs that lib fl ff
17,980
create large number of objectsusing _slots_ can result in substantial reduction in memory use and execution time be aware that the use of _slots_ has tricky interaction with inheritance if class inherits from base class that uses _slots_ _it also needs to define _slots_ for storing its own attributes (even if it doesn' add anyto take advantage of the benefits _slots_ provides if you forget thisthe derived class will run slower and use even more memory than what would have been used if _slots_ had not been used on any of the classesthe use of _slots_ can also break code that expects instances to have an underlying _dict_ attribute although this often does not apply to user codeutility libraries and other tools for supporting objects may be programmed to look at _dict_ for debuggingserializing objectsand other operations finallythe presence of _slots_ has no effect on the invocation of methods such as _getattribute_ () _getattr_ ()and _setattr_ (should they be redefined in class howeverthe default behavior of these methods will take _slots_ into account in additionit should be stressed that it is not necessary to add method or property names to _slots_ _as they are stored in the classnot on per-instance basis operator overloading user-defined objects can be made to work with all of python' built-in operators by adding implementations of the special methods described in to class for exampleif you wanted to add new kind of number to pythonyou could define class in which special methods such as _add_ (were defined to make instances work with the standard mathematical operators the following example shows how this works by defining class that implements the complex numbers with some of the standard mathematical operators note because python already provides complex number typethis class is only provided for the purpose of illustration class complex(object)def _init_ (self,real,imag= )self real float(realself imag float(imagdef _repr_ (self)return "complex(% ,% )(self realself imagdef _str_ (self)return "(% +%gj)(self realself imagself other def _add_ (self,other)return complex(self real other realself imag other imagself other def _sub_ (self,other)return complex(self real other realself imag other imagin the examplethe _repr_ (method creates string that can be evaluated to recreate the object (that is"complex(real,imag)"this convention should be followed for all user-defined objects as applicable on the other handthe _str_ (method lib fl ff
17,981
classes and object-oriented programming creates string that' intended for nice output formatting (this is the string that would be produced by the print statementthe other operatorssuch as _add_ (and _sub_ ()implement mathematical operations delicate matter with these operators concerns the order of operands and type coercion as implemented in the previous examplethe _add_ (and _sub_ (operators are applied only if complex number appears on the left side of the operator they do not work if they appear on the right side of the operator and the left-most operand is not complex for examplec complex( , complex( , traceback (most recent call last)file ""line in typeerrorunsupported operand type(sfor +'intand 'complexthe operation works partly by accident all of python' built-in numbers already have real and imag attributesso they were used in the calculation if the other object did not have these attributesthe implementation would break if you want your implementation of complex to work with objects missing these attributesyou have to add extra conversion code to extract the needed information (which might depend on the type of the other objectthe operation does not work at all because the built-in floating point type doesn' know anything about the complex class to fix thisyou can add reversedoperand methods to complexclass complex(object)def _radd_ (self,other)return complex(other real self realother imag self imagdef _rsub_ (self,other)return complex(other real self realother imag self imgthese methods serve as fallback if the operation failspython tries to execute _radd_ ( first before issuing typeerror older versions of python have tried various approaches to coerce types in mixedtype operations for exampleyou might encounter legacy python classes that implement _coerce_ (method this is no longer used by python or python alsodon' be fooled by special methods such as _int_ () _float_ ()or _complex_ (although these methods are called by explicit conversions such as int(xor float( )they are never called implicitly to perform type conversion in mixed-type arithmetic soif you are writing classes where operators must work with mixed typesyou have to explicitly handle the type conversion in the implementation of each operator types and class membership tests when you create an instance of classthe type of that instance is the class itself to test for membership in classuse the built-in function isinstance(obj,cnamethis lib fl ff
17,982
function returns true if an objectobjbelongs to the class cname or any class derived from cname here' an exampleclass (object)pass class ( )pass class (object)pass ( ( (instance of 'ainstance of 'binstance of 'ctype(aisinstance( ,aisinstance( ,aisinstance( ,creturns the class object returns true returns trueb derives from returns falsec not derived from similarlythe built-in function issubclass( ,breturns true if the class is subclass of class here' an exampleissubclass( ,aissubclass( ,areturns true returns false subtle problem with type-checking of objects is that programmers often bypass inheritance and simply create objects that mimic the behavior of another object as an exampleconsider these two classesclass foo(object)def spam(self, , )pass class fooproxy(object)def _init_ (self, )self def spam(self, , )return self spam( ,bin this examplefooproxy is functionally identical to foo it implements the same methodsand it even uses foo underneath the covers yetin the type systemfooproxy is different than foo for examplef foo( fooproxy(fisinstance(gfoocreate foo create fooproxy returns false if program has been written to explicitly check for foo using isinstance()then it certainly won' work with fooproxy object howeverthis degree of strictness is often not exactly what you want insteadit might make more sense to assert that an object can simply be used as foo because it has the same interface to do thisit is possible to define an object that redefines the behavior of isinstance(and issubclass(for the purpose of grouping objects together and type-checking here is an exampleclass iclass(object)def _init_ (self)self implementors set(def register(self, )self implementors add(cdef _instancecheck_ (self, )return self _subclasscheck_ (type( ) lib fl ff
17,983
classes and object-oriented programming def _subclasscheck_ (self,sub)return any( in self implementors for in sub mro()nowuse the above object ifoo iclass(ifoo register(fooifoo register(fooproxyin this examplethe class iclass creates an object that merely groups collection of other classes together in set the register(method adds new class to the set the special method _instancecheck_ (is called if anyone performs the operation isinstance(xiclassthe special method _subclasscheck_ (is called if the operation issubclass( ,iclassis called by using the ifoo object and registered implementersone can now perform type checks such as the followingf foo(create foo fooproxy(fcreate fooproxy isinstance(fifooreturns true isinstance(gifooreturns true issubclass(fooproxyifooreturns true in this exampleit' important to emphasize that no strong type-checking is occurring the ifoo object has overloaded the instance checking operations in way that allows you to assert that class belongs to group it doesn' assert any information on the actual programming interfaceand no other verification actually occurs in factyou can simply register any collection of objects you want to group together without regard to how those classes are related to each other typicallythe grouping of classes is based on some criteria such as all classes implementing the same programming interface howeverno such meaning should be inferred when overloading _instancecheck_ (or _subclasscheck_ (the actual interpretation is left up to the application python provides more formal mechanism for grouping objectsdefining interfacesand type-checking this is done by defining an abstract base classwhich is defined in the next section abstract base classes in the last sectionit was shown that the isinstance(and issubclass(operations can be overloaded this can be used to create objects that group similar classes together and to perform various forms of type-checking abstract base classes build upon this concept and provide means for organizing objects into hierarchymaking assertions about required methodsand so forth to define an abstract base classyou use the abc module this module defines metaclass (abcmetaand set of decorators (@abstractmethod and @abstractpropertythat are used as followsfrom abc import abcmetaabstractmethodabstractproperty class fooin python you use the syntax _metaclass_ abcmeta class foo(metaclass=abcmeta@abstractmethod def spam(self, , )pass @abstractproperty lib fl ff
17,984
def name(self)pass the definition of an abstract class needs to set its metaclass to abcmeta as shown (alsobe aware that the syntax differs between python and this is required because the implementation of abstract classes relies on metaclass (described in the next sectionwithin the abstract classthe @abstractmethod and @abstractproperty decorators specify that method or property must be implemented by subclasses of foo an abstract class is not meant to be instantiated directly if you try to create foo for the previous classyou will get the following errorf foo(traceback (most recent call last)file ""line in typeerrorcan' instantiate abstract class foo with abstract methods spam this restriction carries over to derived classes as well for instanceif you have class bar that inherits from foo but it doesn' implement one or more of the abstract methodsattempts to create bar will fail with similar error because of this added checkingabstract classes are useful to programmers who want to make assertions on the methods and properties that must be implemented on subclasses although an abstract class enforces rules about methods and properties that must be implementedit does not perform conformance checking on arguments or return values thusan abstract class will not check subclass to see whether method has used the same arguments as an abstract method likewisean abstract class that requires the definition of property does not check to see whether the property in subclass supports the same set of operations (getsetand deleteof the property specified in base although an abstract class can not be instantiatedit can define methods and properties for use in subclasses moreoveran abstract method in the base can still be called from subclass for examplecalling foo spam( ,bfrom the subclass is allowed abstract base classes allow preexisting classes to be registered as belonging to that base this is done using the register(method as followsclass grok(object)def spam(self, , )print("grok spam"foo register(grokregister with foo abstract base class when class is registered with an abstract basetype-checking operations involving the abstract base (such as isinstance(and issubclass()will return true for instances of the registered class when class is registered with an abstract classno checks are made to see whether the class actually implements any of the abstract methods or properties this registration process only affects type-checking it does not add extra error checking to the class that is registered unlike many other object-oriented languagespython' built-in types are organized into relatively flat hierarchy for exampleif you look at the built-in types such as int or floatthey directly inherit from objectthe root of all objectsinstead of an intermediate base class representing numbers this makes it clumsy to write programs that want to inspect and manipulate objects based on generic category such as simply being an instance of number lib fl ff
17,985
classes and object-oriented programming the abstract class mechanism addresses this issue by allowing preexisting objects to be organized into user-definable type hierarchies moreoversome library modules aim to organize the built-in types according to different capabilities that they possess the collections module contains abstract base classes for various kinds of operations involving sequencessetsand dictionaries the numbers module contains abstract base classes related to organizing hierarchy of numbers further details can be found in "mathematics,and "data structuresalgorithmsand utilities metaclasses when you define class in pythonthe class definition itself becomes an object here' an exampleclass foo(object)pass isinstance(foo,objectreturns true if you think about this long enoughyou will realize that something had to create the foo object this creation of the class object is controlled by special kind of object called metaclass simply stateda metaclass is an object that knows how to create and manage classes in the preceding examplethe metaclass that is controlling the creation of foo is class called type in factif you display the type of fooyou will find out that it is typetype(foowhen new class is defined with the class statementa number of things happen firstthe body of the class is executed as series of statements within its own private dictionary the execution of statements is exactly the same as in normal code with the addition of the name mangling that occurs on private members (names that start with _finallythe name of the classthe list of base classesand the dictionary are passed to the constructor of metaclass to create the corresponding class object here is an example of how it worksclass_name "fooname of class class_parents (object,base classes class_body ""class body def _init_ (self, )self def blah(self)print("hello world"""class_dict execute the body in the local dictionary class_dict exec(class_body,globals(),class_dictcreate the class object foo foo type(class_name,class_parents,class_dictthe final step of class creation where the metaclass type(is invoked can be customized the choice of what happens in the final step of class definition is controlled in lib fl ff
17,986
number of ways firstthe class can explicitly specify its metaclass by either setting _metaclass_ class variable (python )or supplying the metaclass keyword argument in the tuple of base classes (python class foo__metaclass__ type in python use the syntax class foo(metaclass=typeif no metaclass is explicitly specifiedthe class statement examines the first entry in the tuple of base classes (if anyin this casethe metaclass is the same as the type of the first base class thereforewhen you write class foo(object)pass foo will be the same type of class as object if no base classes are specifiedthe class statement checks for the existence of global variable called _metaclass_ if this variable is foundit will be used to create classes if you set this variableit will control how classes are created when simple class statement is used here' an example_ _metaclass_ type class foopass finallyif no _metaclass_ value can be found anywherepython uses the default metaclass in python this defaults to types classtypewhich is known as an oldstyle class this kind of classdeprecated since python corresponds to the original implementation of classes in python although these classes are still supportedthey should be avoided in new code and are not covered further here in python the default metaclass is simply type(the primary use of metaclasses is in frameworks that want to assert more control over the definition of user-defined objects when custom metaclass is definedit typically inherits from type(and reimplements methods such as _init_ (or _new_ (here is an example of metaclass that forces all methods to have documentation stringclass docmeta(type)def _init_ (self,name,bases,dict)for keyvalue in dict items()skip special and private methods if key startswith(" ")continue skip anything not callable if not hasattr(value," _call_ ")continue check for doc-string if not getattr(value," _doc_ ")raise typeerror("% must have docstringkeytype _init_ (self,name,bases,dictin this metaclassthe _init_ (method has been written to inspect the contents of the class dictionary it scans the dictionary looking for methods and checking to see whether they all have documentation strings if nota typeerror exception is generated otherwisethe default implementation of type _init_ (is called to initialize the class to use this metaclassa class needs to explicitly select it the most common technique for doing this is to first define base class such as the followingclass documented_ _metaclass_ docmeta in python use the syntax class documented(metaclass=docmetaf lib fl ff
17,987
classes and object-oriented programming this base class is then used as the parent for all objects that are to be documented for exampleclass foo(documented)spam(self, , )"spam does somethingpass this example illustrates one of the major uses of metaclasseswhich is that of inspecting and gathering information about class definitions the metaclass isn' changing anything about the class that actually gets created but is merely adding some additional checks in more advanced metaclass applicationsa metaclass can both inspect and alter the contents of class definition prior to the creation of the class if alterations are going to be madeyou should redefine the _new_ (method that runs prior to the creation of the class itself this technique is commonly combined with techniques that wrap attributes with descriptors or properties because it is one way to capture the names being used in the class as an examplehere is modified version of the typedproperty descriptor that was used in the "descriptorssectionclass typedproperty(object)def _init_ (self,type,default=none)self name none self type type if defaultself default default elseself default type(def _get_ (self,instance,cls)return getattr(instance,self name,self defaultdef _set_ (self,instance,value)if not isinstance(value,self type)raise typeerror("must be %sself typesetattr(instance,self name,valuedef _delete_ (self,instance)raise attributeerror("can' delete attribute"in this examplethe name attribute of the descriptor is simply set to none to fill this inwe'll rely on meta class for exampleclass typedmeta(type)def _new_ (cls,name,bases,dict)slots [for key,value in dict items()if isinstance(value,typedproperty)value name "_key slots append(value namedict[' _slots_ 'slots return type _new_ (cls,name,bases,dictbase class for user-defined objects to use class typedin python use the syntax _metaclass_ typedmeta class typed(metaclass=typedmetain this examplethe metaclass scans the class dictionary and looks for instances of typedproperty if foundit sets the name attribute and builds list of names in slots after this is donea _slots_ attribute is added to the class dictionaryand the class is constructed by calling the _new_ (method of the type(metaclass here is an example of using this new metaclassclass foo(typed)name typedproperty(strnum typedproperty(int, lib fl ff
17,988
although metaclasses make it possible to drastically alter the behavior and semantics of user-defined classesyou should probably resist the urge to use metaclasses in way that makes classes work wildly different from what is described in the standard python documentation users will be confused if the classes they must write don' adhere to any of the normal coding rules expected for classes class decorators in the previous sectionit was shown how the process of creating class can be customized by defining metaclass howeversometimes all you want to do is perform some kind of extra processing after class is definedsuch as adding class to registry or database an alternative approach for such problems is to use class decorator class decorator is function that takes class as input and returns class as output for exampleregistry def register(cls)registry[cls _clsid_ _cls return cls in this examplethe register function looks inside class for _clsid_ attribute if foundit' used to add the class to dictionary mapping class identifiers to class objects to use this functionyou can use it as decorator right before the class definition for example@register class foo(object) _clsid_ " - def bar(self)pass herethe use of the decorator syntax is mainly one of convenience an alternative way to accomplish the same thing would have been thisclass foo(object) _clsid_ " - def bar(self)pass register(fooregister the class although it' possible to think of endless diabolical things one might do to class in class decorator functionit' probably best to avoid excessive magic such as putting wrapper around the class or rewriting the class contents lib fl ff
17,989
lib fl ff
17,990
modulespackagesand distribution arge python programs are organized into modules and packages in additiona large number of modules are included in the python standard library this describes the module and package system in more detail in additionit provides information on how to install third-party modules and distribute source code modules and the import statement any python source file can be used as module for exampleconsider the following codespam py def foo()print(" ' foo and is %sadef bar()print(" ' bar and ' calling foo"foo(class spam(object)def grok(self)print(" ' spam grok"to load this code as moduleuse the statement import spam the first time import is used to load moduleit does three things it creates new namespace that serves as container for all the objects defined in the corresponding source file this is the namespace accessed when functions and methods defined within the module use the global statement it executes the code contained in the module within the newly created namespace it creates name within the caller that refers to the module namespace this name matches the name of the module and is used as followsimport spam spam spam foo( spam spam( grok(loads and executes the module 'spamaccesses member of module 'spamcall function in module 'spamcreate an instance of spam spam( lib fl ff
17,991
modulespackagesand distribution it is important to emphasize that import executes all of the statements in the loaded source file if module carries out computation or produces output in addition to defining variablesfunctionsand classesyou will see the result alsoa common confusion with modules concerns the access to classes keep in mind that if file spam py defines class spamyou must use the name spam spam to refer to the class to import multiple modulesyou can supply import with comma-separated list of module nameslike thisimport socketosre the name used to refer to module can be changed using the as qualifier here' an exampleimport spam as sp import socket as net sp foo(sp bar(net gethostname(when module is loaded using different name like thisthe new name only applies to the source file or context where the import statement appeared other program modules can still load the module using its original name changing the name of the imported module can be useful tool for writing extensible code for examplesuppose you have two modulesxmlreader py and csvreader pythat both define function read_data(filenamefor reading some data from filebut in different input formats you can write code that selectively picks the reader module like thisif format ='xml'import xmlreader as reader elif format ='csv'import csvreader as reader data reader read_data(filenamemodules are first class objects in python this means that they can be assigned to variablesplaced in data structures such as listand passed around in program as data for instancethe reader variable in the previous example simply refers to the corresponding module object underneath the coversa module object is layer over dictionary that is used to hold the contents of the module namespace this dictionary is available as the _dict_ of moduleand whenever you look up or change value in moduleyou're working with this dictionary the import statement can appear at any point in program howeverthe code in each module is loaded and executed only onceregardless of how often you use the import statement subsequent import statements simply bind the module name to the module object already created by the previous import you can find dictionary containing all currently loaded modules in the variable sys modules this dictionary maps module names to module objects the contents of this dictionary are used to determine whether import loads fresh copy of module lib fl ff
17,992
importing selected symbols from module the from statement is used to load specific definitions within module into the current namespace the from statement is identical to import except that instead of creating name referring to the newly created module namespaceit places references to one or more of the objects defined in the module into the current namespacefrom spam import foo foo(spam foo(imports spam and puts 'fooin current namespace calls spam foo(nameerrorspam the from statement also accepts comma-separated list of object names for examplefrom spam import foobar if you have very long list of names to importthe names can be enclosed in parentheses this makes it easier to break the import statement across multiple lines here' an examplefrom spam import (foobarspamin additionthe as qualifier can be used to rename specific objects imported with from here' an examplefrom spam import spam as sp sp(the asterisk (*wildcard character can also be used to load all the definitions in moduleexcept those that start with an underscore here' an examplefrom spam import load all definitions into current namespace the from module import statement may only be used at the top level of module in particularit is illegal to use this form of import inside function bodies due to the way in which it interacts with function scoping rules ( when functions are compiled into internal bytecodeall of the symbols used within the function need to be fully specifiedmodules can more precisely control the set of names imported by from module import by defining the list _all_ here' an examplemodulespam py _all_ 'bar''spamnames will export with from spam import importing definitions with the from form of import does not change their scoping rules for exampleconsider this codefrom spam import foo foo(prints " ' foo and is in this examplethe definition of foo(in spam py refers to global variable when reference to foo is placed into different namespaceit doesn' change the binding rules for variables within that function thusthe global namespace for function is always the module in which the function was definednot the namespace into which function is imported and called this also applies to function calls for examplein the lib fl ff
17,993
modulespackagesand distribution following codethe call to bar(results in call to spam foo()not the redefined foo(that appears in the previous code examplefrom spam import bar def foo()print(" ' different foo"bar(when bar calls foo()it calls spam foo()not the definition of foo(above another common confusion with the from form of import concerns the behavior of global variables for exampleconsider this codefrom spam import afoo foo(print(aimport global variable modify the variable prints " ' foo and is prints " hereit is important to understand that variable assignment in python is not storage operation that isthe assignment to in the earlier example is not storing new value in aoverwriting the previous value insteada new object containing the value is created and the name is made to refer to it at this pointa is no longer bound to the value in the imported module but to some other object because of this behaviorit is not possible to use the from statement in way that makes variables behave similarly as global variables or common blocks in languages such as or fortran if you want to have mutable global program parameters in your programput them in module and use the module name explicitly using the import statement (that isuse spam explicitlyexecution as the main program there are two ways in which python source file can execute the import statement executes code in its own namespace as library module howevercode might also execute as the main program or script this occurs when you supply the program as the script name to the interpreterpython spam py each module defines variable_ _name_ _that contains the module name programs can examine this variable to determine the module in which they're executing the top-level module of the interpreter is named _main_ programs specified on the command line or entered interactively run inside the _main_ module sometimes program may alter its behaviordepending on whether it has been imported as module or is running in _main_ for examplea module may include some testing code that is executed if the module is used as the main program but which is not executed if the module is simply imported by another module this can be done as followscheck if running as program if _name_ =' _main_ 'yes statements elsenoi must have been imported as module statements it is common practice for source files intended for use as libraries to use this technique for including optional testing or example code for exampleif you're developing lib fl ff
17,994
moduleyou can put code for testing the features of your library inside an if statement as shown and simply run python on your module as the main program to run it that code won' run for users who import your library the module search path when loading modulesthe interpreter searches the list of directories in sys path the first entry in sys path is typically an empty string ''which refers to the current working directory other entries in sys path may consist of directory nameszip archive filesand egg files the order in which entries are listed in sys path determines the search order used when modules are loaded to add new entries to the search pathsimply add them to this list although the path usually contains directory nameszip archive files containing python modules can also be added to the search path this can be convenient way to package collection of modules as single file for examplesuppose you created two modulesfoo py and bar pyand placed them in zip file called mymodules zip the file could be added to the python search path as followsimport sys sys path append("mymodules zip"import foobar specific locations within the directory structure of zip file can also be used in additionzip files can be mixed with regular pathname components here' an examplesys path append("/tmp/modules zip/lib/python"in addition to zip filesyou can also add egg files to the search path egg files are packages created by the setuptools library this is common format encountered when installing third-party python libraries and extensions an egg file is actually just zip file with some extra metadata ( version numberdependenciesetc added to it thusyou can examine and extract data from an egg file using standard tools for working with zip files despite support for zip file importsthere are some restrictions to be aware of firstit is only possible import pypywpycand pyo files from an archive shared libraries and extension modules written in cannot be loaded directly from archivesalthough packaging systems such as setuptools are sometimes able to provide workaround (typically by extracting extensions to temporary directory and loading modules from itmoreoverpython will not create pyc and pyo files when py files are loaded from an archive (described nextthusit is important to make sure these files are created in advance and placed in the archive in order to avoid poor performance when loading modules module loading and compilation so farthis has presented modules as files containing pure python code howevermodules loaded with import really fall into four general categoriesn code written in python py filesn or +extensions that have been compiled into shared libraries or dlls lib fl ff
17,995
packages containing collection of modules built-in modules written in and linked into the python interpreter when looking for module (for examplefoo)the interpreter searches each of the directories in sys path for the following files (listed in search order) directoryfoodefining package foo pydfoo sofoomodule soor foomodule dll (compiled extensions foo pyo (only if the - or -oo option has been used foo pyc foo py (on windowspython also checks for pyw files packages are described shortlycompiled extensions are described in "extending and embedding python for py fileswhen module is first importedit' compiled into bytecode and written back to disk as pyc file on subsequent importsthe interpreter loads this precompiled bytecode unless the modification date of the py file is more recent (in which casethe pyc file is regeneratedpyo files are used in conjunction with the interpreter' - option these files contain bytecode stripped of line numbersassertionsand other debugging information as resultthey're somewhat smaller and allow the interpreter to run slightly faster if the -oo option is specified instead of -odocumentation strings are also stripped from the file this removal of documentation strings occurs only when pyo files are created--not when they're loaded if none of these files exists in any of the directories in sys paththe interpreter checks whether the name corresponds to built-in module name if no match existsan importerror exception is raised the automatic compilation of files into pyc and pyo files occurs only in conjunction with the import statement programs specified on the command line or standard input don' produce such files in additionthese files aren' created if the directory containing module' py file doesn' allow writing ( either due to insufficient permission or if it' part of zip archivethe - option to the interpreter also disables the generation of these files if pyc and pyo files are availableit is not necessary for corresponding py file to exist thusif you are packaging code and don' wish to include sourceyou can merely bundle set of pyc files together howeverbe aware that python has extensive support for introspection and disassembly knowledgeable users will still be able to inspect and find out lot of details about your program even if the source hasn' been provided alsobe aware that pyc files tend to be version-specific thusa pyc file generated for one version of python might not work in future release when import searches for filesit matches filenames in case-sensitive manner-even on machines where the underlying file system is case-insensitivesuch as on windows and os (such systems are case-preservinghoweverthereforeimport foo will only import the file foo py and not the file foo py howeveras general ruleyou should avoid the use of module names that differ in case only lib fl ff
17,996
module reloading and unloading python provides no real support for reloading or unloading of previously imported modules although you can remove module from sys modulesthis does not generally unload module from memory this is because references to the module object may still exist in other program components that used import to load that module moreoverif there are instances of classes defined in the modulethose instances contain references back to their class objectwhich in turn holds references to the module in which it was defined the fact that module references exist in many places makes it generally impractical to reload module after making changes to its implementation for exampleif you remove module from sys modules and use import to reload itthis will not retroactively change all of the previous references to the module used in program insteadyou'll have one reference to the new module created by the most recent import statement and set of references to the old module created by imports in other parts of the code this is rarely what you want and never safe to use in any kind of sane production code unless you are able to carefully control the entire execution environment older versions of python provided reload(function for reloading module howeveruse of this function was never really safe (for all of the aforementioned reasons)and its use was actively discouraged except as possible debugging aid python removes this feature entirely soit' best not to rely upon it finallyit should be noted that / +extensions to python cannot be safely unloaded or reloaded in any way no support is provided for thisand the underlying operating system may prohibit it anyways thusyour only recourse is to restart the python interpreter process packages packages allow collection of modules to be grouped under common package name this technique helps resolve namespace conflicts between module names used in different applications package is defined by creating directory with the same name as the package and creating the file _init_ py in that directory you can then place additional source filescompiled extensionsand subpackages in this directoryas needed for examplea package might be organized as followsgraphics_ _init_ py primitive_ _init_ py lines py fill py text py graph d_ _init_ py plot py graph d_ _init_ py plot py formats_ _init_ py gif py lib fl ff
17,997
png py tiff py jpeg py the import statement is used to load modules from package in number of waysn import graphics primitive fill this loads the submodule graphics primitive fill the contents of this module have to be explicitly namedsuch as graphics primitive fill floodfill(img, , ,colorn from graphics primitive import fill this loads the submodule fill but makes it available without the package prefixfor examplefill floodfill(img, , ,colorn from graphics primitive fill import floodfill this loads the submodule fill but makes the floodfill function directly accessiblefor examplefloodfill(img, , ,colorwhenever any part of package is first importedthe code in the file _init_ py is executed minimallythis file may be emptybut it can also contain code to perform package-specific initializations all the _init_ py files encountered during an import are executed thereforethe statement import graphics primitive fillshown earlierwould first execute the _init_ py file in the graphics directory and then the _init_ py file in the primitive directory one peculiar problem with packages is the handling of this statementfrom graphics primitive import programmer who uses this statement usually wants to import all the submodules associated with package into the current namespace howeverbecause filename conventions vary from system to system (especially with regard to case sensitivity)python cannot accurately determine what modules those might be as resultthis statement just imports all the names that are defined in the _init_ py file in the primitive directory this behavior can be modified by defining list_ _all_ _that contains all the module names associated with the package this list should be defined in the package _init_ py filelike thisgraphics/primitive/ _init_ py _all_ ["lines","text","fill"now when the user issues from graphics primitive import statementall the listed submodules are loaded as expected another subtle problem with packages concerns submodules that want to import other submodules within the same package for examplesuppose the graphics primitive fill module wants to import the graphics primitive lines module to do thisyou can simply use the fully specified named ( from graphics primitives import linesor use package relative import like thisfill py from import lines in this examplethe used in the statement from import lines refers to the same directory of the calling module thusthis statement looks for module lines in the lib fl ff
17,998
same directory as the file fill py great care should be taken to avoid using statement such as import module to import package submodule in older versions of pythonit was unclear whether the import module statement was referring to standard library module or submodule of package older versions of python would first try to load the module from the same package directory as the submodule where the import statement appeared and then move on to standard library modules if no match was found howeverin python import assumes an absolute path and will simply try to load module from the standard library relative import more clearly states your intentions relative imports can also be used to load submodules contained in different directories of the same package for exampleif the module graphics graph plot wanted to import graphics primitives linesit could use statement like thisplot py from primitives import lines herethe moves out one directory level and primitives drops down into different package directory relative imports can only be specified using the from module import symbol form of the import statement thusstatements such as import primitives lines or import lines are syntax error alsosymbol has to be valid identifier soa statement such as from import primitives lines is also illegal finallyrelative imports can only be used within packageit is illegal to use relative import to refer to modules that are simply located in different directory on the filesystem importing package name alone doesn' import all the submodules contained in the package for examplethe following code doesn' workimport graphics graphics primitive fill floodfill(img, , ,colorfailshoweverbecause the import graphics statement executes the _init_ py file in the graphics directoryrelative imports can be used to load all the submodules automaticallyas followsgraphics/ _init_ py from import primitivegraph dgraph graphics/primitive/ _init_ py from import linesfilltextnow the import graphics statement imports all the submodules and makes them available using their fully qualified names againit is important to stress that package relative import should be used as shown if you use simple statement such as import modulestandard library modules may be loaded instead finallywhen python imports packageit defines special variable_ _path_ _which contains list of directories that are searched when looking for package submodules ( _path_ is package-specific version of the sys path variable_ _path_ is accessible to the code contained in _init_ py files and initially contains single item with the directory name of the package if necessarya package can supply additional directories to the _path_ list to alter the search path used for finding submodules this might be useful if the organization of package on the file system is complicated and doesn' neatly match up with the package hierarchy lib fl ff
17,999
modulespackagesand distribution distributing python programs and libraries to distribute python programs to othersyou should use the distutils module as preparationyou should first cleanly organize your work into directory that has readme filesupporting documentationand your source code typicallythis directory will contain mix of library modulespackagesand scripts modules and packages refer to source files that will be loaded with import statements scripts are programs that will run as the main program to the interpreter ( running as python scriptnamehere is an example of directory containing python codespamreadme txt documentation txt libspam py spampkg_ _init_ py foo py bar py runspam py single library module package of support modules script to run aspython runspam py you should organize your code so that it works normally when running the python interpreter in the top-level directory for exampleif you start python in the spam directoryyou should be able to import modulesimport package componentsand run scripts without having to alter any of python' settings such as the module search path after you have organized your codecreate file setup py in the top most directory (spam in the previous examplesin this fileput the following codesetup py from distutils core import setup setup(name "spam"version " "py_modules ['libspam']packages ['spampkg']scripts ['runspam py']in the setup(callthe py_modules argument is list of all of the single-file python modulespackages is list of all package directoriesand scripts is list of script files any of these arguments may be omitted if your software does not have any matching components ( there are no scriptsname is the name of your packageand version is the version number as string the call to setup(supports variety of other parameters that supply various metadata about your package table shows the most common parameters that can be specified all values are strings except for the classifiers parameterwhich is list of strings such as ['development status : beta''programming language :python'( full list can be found at table parameters to setup(parameter description name version author author_email name of the package (requiredversion number (requiredauthor' name author' email address lib fl ff