id
int64
0
25.6k
text
stringlengths
0
4.59k
18,100
number class that serves as the top of the numeric hierarchy complex class that represents the complex numbers numbers of this type have real and imag attributes this class inherits from number real class that represents the real numbers inherits from complex rational class that represents fractions numbers of this type have numerator and denominator attributes inherits from real integral class that represents the integers inherits from rational the classes in this module are not meant to be instantiated insteadthey can be used to perform various kinds of type checks on values for exampleif isinstance(xnumbers numberstatements is any kind of number if isinstance(xnumbers integralstatements is an integral value if one of these type checks returns trueit means that is compatible with all of the usual mathematical operations associated with that type and that conversion to one of the built-in types such as complex()float()or int(will work the abstract base classes can also be used as base class for user-defined classes that are meant to emulate numbers doing this is not only just good idea for type checkingbut it adds extra safety checks that make sure you implement all of the required methods for exampleclass foo(numbers real)pass foo(traceback (most recent call last)file ""line in typeerrorcan' instantiate abstract class foo with abstract methods _abs_ __ _add_ __ _div_ __ _eq_ __ _float_ __ _floordiv_ __ _le_ __ _lt_ __ _mod_ __ _mul_ __ _neg_ __ _pos_ __ _pow_ __ _radd_ __ _rdiv_ __ _rfloordiv_ __ _rmod_ __ _rmul_ __ _rpow_ __ _rtruediv_ __ _truediv_ __ _trunc_ notes refer to ("classes and object-oriented programming"for more information on abstract base classes pep (about the type hierarchy and intended use of this module lib fl ff
18,101
mathematics random the random module provides variety of functions for generating pseudo-random numbers as well as functions for randomly generating values according to various distributions on the real numbers most of the functions in this module depend on the function random()which generates uniformly distributed numbers in the range [ using the mersenne twister generator seeding and initialization the following functions are used to control the state of the underlying random number generatorseed([ ]initializes the random number generator if is omitted or nonethe system time is used to seed the generator otherwiseif is an integer or long integerits value is used if is not an integerit must be hashable object and the value of hash(xis used as seed getstate(returns an object representing the current state of the generator this object can later be passed to setstate(to restore the state setstate(staterestores the state of the random number generator from an object returned by getstate(jumpahead(nquickly changes the state of the generator to what it would be if random(were called times in row must be nonnegative integer random integers the following functions are used to manipulate random integers getrandbits(kcreates long integer containing random bits randint( ,breturns random integerxin the range < < randrange(start,stop [,step]returns random integer in range(start,stop,stepdoes not include the endpoint random sequences the following functions are used to randomize sequence data choice(seqreturns random element from the nonempty sequence seq lib fl ff
18,102
sample(slenreturns sequence lengthlencontaining elements chosen randomly from the sequence the elements in the resulting sequence are placed in the order in which they were selected shuffle( [,random]randomly shuffles the items in the list in place random is an optional argument that specifies random generation function if suppliedit must be function that takes no arguments and returns floating-point number in the range [ real-valued random distributions the following functions generate random numbers on real numbers distribution and parameter names correspond to the standard names used in probability and statistics you will need to consult an appropriate text to find out more details random(returns random number in the range [ uniform( ,breturns uniformly distributed random number in the range [abbetavariate(alphabetareturns value between and from the beta distribution alpha - and beta - cunifvariate(meanarccircular uniform distribution mean is the mean angleand arc is the range of the distributioncentered around the mean angle both of these values must be specified in radians in the range between and pi returned values are in the range (mean arc/ mean arc/ expovariate(lambdexponential distribution lambd is divided by the desired mean returns values in the range [ +infinitygammavariate(alphabetagamma distribution alpha - beta gauss(musigmagaussian distribution with mean mu and standard deviation sigma slightly faster than normalvariate(lognormvariate(musigmalog normal distribution taking the natural logarithm of this distribution results in normal distribution with mean mu and standard deviation sigma normalvariate(musigmanormal distribution with mean mu and standard deviation sigma lib fl ff
18,103
paretovariate(alphapareto distribution with shape parameter alpha triangular([low [high [mode]]]triangular distribution random number in the range low < high with mode mode by defaultlow is high is and mode is set to the midpoint of low and high vonmisesvariate(mukappavon mises distributionwhere mu is the mean angle in radians between and pi and kappa is nonnegative concentration factor if kappa is zerothe distribution reduces to uniform random angle over the range to pi weibullvariate(alphabetaweibull distribution with scale parameter alpha and shape parameter beta notes the functions in this module are not thread-safe if you are generating random numbers in different threadsyou should use locking to prevent concurrent access the period of the random number generator (before numbers start repeatingis ** - the random numbers generated by this module are deterministic and should not be used for cryptography new types of random number generators can be created by subclassing random random and implementing the random()seed()getstate()getstate()and jumpahead(methods all the other functions in this module are actually internally implemented as methods of random thusthey could be accessed as methods of an instance of the new random number generator the module provides two alternative random number generators classes-wichmannhill and systemrandom--that are used by instantiating the appropriate class and calling the preceding functions as methods the wichmannhill class implements the wichmann-hill generator that was used in earlier python releases the systemrandom class generates random numbers using the system random number generator os urandom( lib fl ff
18,104
data structuresalgorithmsand code simplification he modules in this are used to address common programming problems related to data structuresalgorithmsand the simplification of code involving iterationfunction programmingcontext managersand classes these modules should be viewed as extension of python' built-in types and functions in many casesthe underlying implementation is highly efficient and may be better suited to certain kinds of problems than what is available with the built-ins abc the abc module defines metaclass and pair of decorators for defining new abstract base classes abcmeta metaclass that represents an abstract base class to define an abstract classyou define class that uses abcmeta as metaclass for exampleimport abc class stackable_ _metaclass_ abc abcmeta in python use the syntax class stackable(metaclass=abc abcmetaa class created in this manner differs from an ordinary class in few critical waysn firstif the abstract class defines methods or properties that are decorated with the abstractmethod and abstractproperty decorators described laterthen instances of derived classes can' be created unless those classes provide nonabstract implementation of those methods and properties secondan abstract class has class method register(subclassthat can be used to register additional types as logical subclass for any type subclass registered with this functionthe operation isinstance(xabstractclasswill return true if is an instance of subclass final feature of abstract classes is that they can optionally define special class method _subclasshook_ (clssubclassthis method should return true if the type subclass is considered to be subclassreturn false if subclass is not subclassor raise notimplemented exception if nothing is known lib fl ff
18,105
data structuresalgorithmsand code simplification abstractmethod(methoda decorator that declares method to be abstract when used in an abstract base classderived classes defined directly via inheritance can only be instantiated if they define nonabstract implementation of the method this decorator has no effect on subclasses registered using the register(method of an abstract base abstractproperty(fget [fset [fdel [doc]]]creates an abstract property the parameters are the same as the normal property(function when used in an abstract basederived classes defined directly via inheritance can only be instantiated if they define nonabstract implementation of the property the following code provides an example of defining simple abstract classfrom abc import abcmetaabstractmethodabstractproperty class stackablein python use the syntax _metaclass_ abcmeta class stackable(metaclass=abcmeta@abstractmethod def push(self,item)pass @abstractmethod def pop(self)pass @abstractproperty def size(self)pass here is an example of class that derives from stackableclass stack(stackable)def _init_ (self)self items [def push(self,item)self items append(itemdef pop(self)return self items pop(here is the error message that you get if you try to create stacks stack(traceback (most recent call last)file ""line in typeerrorcan' instantiate abstract class stack with abstract methods size this error can be fixed by adding size(property to stack you can either do this by modifying the definition of stack itself or inheriting from it and adding the required method or propertyclass completestack(stack)@property def size(self)return len(self itemshere is an example of using the complete stack objects completestack( push("foo" size lib fl ff
18,106
see also"classes and object-oriented programming,numbers ( )collections ( array the array module defines new object typearraythat works almost exactly like listexcept that its contents are constrained to single type the type of an array is determined at the time of creationusing one of the type codes shown in table table type codes type code description type minimum size (in bytes' ' ' ' ' ' ' ' ' ' ' ' -bit character -bit integer -bit unsigned integer unicode character -bit integer -bit unsigned integer integer unsigned integer long integer unsigned long integer single-precision float double-precision float char signed char unsigned char py_unicode short unsigned short int unsigned int long unsigned long float double or or or or or the representation of integers and long integers is determined by the machine architecture (they may be or bitswhen values stored as 'lor 'iare returnedthey're returned as long integers in python the module defines the following typearray(typecode [initializer]creates an array of type typecode initializer is string or list of values used to initialize values in the array the following attributes and methods apply to an array objectaitem description typecode itemsize append(xa buffer_info(type code character used to create the array size of items stored in the array (in bytesappends to the end of the array returns (addresslength)giving the memory location and length of the buffer used to store the array swaps the byte ordering of all items in the array from big-endian to little-endianor vice versa this is only supported for integer values byteswap(continues lib fl ff
18,107
data structuresalgorithmsand code simplification item description returns the number of occurrences of in appends to the end of array can be an array or an iterable object whose elements are the same type as in fromfile(fnreads items (in binary formatfrom the file object and appends to the end of the array must be file object raises eoferror if fewer than items can be read fromlist(listappends items from list to the end of the array list can be any iterable object fromstring(sappends items from string swhere is interpreted as string of binary values--same as would have been read using fromfile( index(xreturns the index of the first occurrence of in raises valueerror if not found insert(ixinserts before position pop([ ]removes item from the array and returns it if is omittedthe last element is removed remove(xremoves the first occurrence of from the array raises valueerror if not found reverse(reverses the order of the array tofile(fwrites all items to file data is saved in native binary format tolist(converts the array to an ordinary list of values tostring(converts to string of binary data--the same data as would be written using tofile( tounicode(converts the array to unicode string raises valueerror if the array is not of type 'ua count(xa extend(bwhen items are inserted into an arraya typeerror exception is generated if the type of the item doesn' match the type used to create the array the array module is useful if you need to have space-efficient storage for lists of data and you know that all items in the list are going to be the same type for examplestoring million integers in list requires about mb of memory whereas an array of million integers requires only mb despite this space savingsnone of the basic operations on an array tend to be faster than their list counterparts--in factthey may be slower in performing calculations with arraysyou will want to be careful with operations that create lists for exampleusing list comprehension on an array will convert the entire array into listdefeating any space-saving benefit better way to handle this is to create new arrays using generator expressions for examplea array array(" "[ , , , , ] array array( typecode( * for in )create new array from because the point of using an array is to save spaceit may be more desirable to perform "in-placeoperations an efficient way to do this is with code that uses enumerate()like thisa array array(" "[ , , , , ]for ix in enumerate( ) [ * lib fl ff
18,108
for large arraysthis in-place modification runs about percent faster than the code that creates new array with generator expression notes the arrays created by this module are not suitable for numeric work such as matrix or vector math for examplethe addition operator doesn' add the corresponding elements of the arraysinsteadit appends one array to the other to create storage and calculation efficient arraysuse the numpy extension available at the +operator can be used to append the contents of another array the *operator can be used to repeat an array see alsostruct ( bisect the bisect module provides support for keeping lists in sorted order it uses bisection algorithm to do most of its work bisect(listitem [low [high]]returns the index of the insertion point for item to be placed in list in order to maintain list in sorted order low and high are indices specifying subset of the list to examine if items is already in the listthe insertion point will always be to the right of existing entries in the list bisect_left(listitem [low [high]]returns the index of the insertion point for item to be placed in list in order to maintain list in sorted order low and high are indices specifying subset of the list to examine if items is already in the listthe insertion point will always be to the left of existing entries in the list bisect_right(listitem [low [high]]the same as bisect(insort(listitem [low [high]]inserts item into list in sorted order if item is already in the listthe new entry is inserted to the right of any existing entries insort_left(listitem [low [high]]inserts item into list in sorted order if item is already in the listthe new entry is inserted to the left of any existing entries insort_right(listitem [low [high]]the same as insort( lib fl ff
18,109
data structuresalgorithmsand code simplification collections the collections module contains high-performance implementations of few useful container typesabstract base classes for various kinds of containersand utility function for creating name-tuple objects each is described in the sections that follow deque and defaultdict two new containers are defined in the collections moduledeque and defaultdict deque([iterable [maxlen]]type representing double-ended queue (dequepronounced "deck"object iterable is an iterable object used to populate the deque deque allows items to be inserted or removed from either end of the queue the implementation has been optimized so that the performance of these operations is approximately the same as ( ( )this is slightly different from list where operations at the front of the list may require shifting of all the elements that follow if the optional maxlen argument is suppliedthe resulting deque object becomes circular buffer of that size that isif new items are addedbut there is no more spaceitems are deleted from the opposite end to make room an instancedof deque has the following methodsd append(xadds to the right side of appendleft(xadds to the left side of clear(removes all items from extend(iterableextends by adding all the items in iterable on the right extendleft(iterableextends by adding all the items in iterable on the left due to the sequence of left appends that occuritems in iterable will appear in reverse order in pop(returns and removes an item from the right side of raises indexerror if is empty popleft(returns and removes an item from the left side of raises indexerror if is empty remove(itemremoves the first occurrence of item raises valueerror if no match is found lib fl ff
18,110
rotate(nrotates all the items steps to the right if is negativeitems are rotated to the left deques are often overlooked by many python programmers howeverthis type offers many advantages firstthe implementation is highly efficient--even to level of using internal data structures that provide good processor cache behavior appending items at the end is only slightly slower than the built-in list typewhereas inserting items at the front is significantly faster operations that add new items to deque are also thread-safemaking this type appropriate for implementing queues deques can also be serialized using the pickle module defaultdict([default_factory] type that is exactly the same as dictionary except for the handling of missing keys when lookup occurs on key that does not yet existthe function supplied as default_factory is called to provide default value which is then saved as the value of the associated key the remaining arguments to defaultdict are exactly the same as the built-in dict(function an instance of defaultdictionary has the same operations as built-in dictionary the attribute default_factory contains the function passed as the first argument and can be modified as necessary defaultdict object is useful if you are trying to use dictionary as container for tracking data for examplesuppose you wanted to keep track of the position of each word in string here is how you could use defaultdict to do this easilyfrom collections import defaultdict "yeah but no but yeah but no but yeahwords split(wordlocations defaultdict(listfor nw in enumerate(words)wordlocations[wappend(nwordlocations defaultdict({'yeah'[ ]'but'[ ]'no'[ ]}in this examplethe lookup wordlocations[wwill "failthe first time word is encountered howeverinstead of raising keyerrorthe function list supplied as default_factory is called to create new value built-in dictionaries have method setdefault(that can be used to achieve similar resultbut it often makes code confusing to read and run slower for examplethe statement that appends new item shown previously could be replaced by wordlocations setdefault( ,[]append(nthis is not nearly as clear and in simple timing testit runs nearly twice as slow as using defaultdict object named tuples tuples are frequently used to represent simple data structures for examplea network address might be represented as tuple addr (hostnameporta common complaint with tuples is that the individual items have to be accessed by numerical index-for exampleaddr[ or addr[ this leads to code that is confusing to read and hard to maintain unless you can remember what all of the index values mean (and the problem gets worse the larger the tuple getsf lib fl ff
18,111
data structuresalgorithmsand code simplification the collections module contains function namedtuple(that is used to create subclasses of tuple in which attribute names can be used to access tuple elements namedtuple(typenamefieldnames [verbose]creates subclass of tuple with name typename fieldnames is list of attribute names specified as strings the names in this list must be valid python identifiersmust not start with an underscoreand are specified in the same order as the items appearing in the tuple--for example['hostname','port'alternativelyfieldnames can be specified as string such as 'hostname portor 'hostnameportthe value returned by this function is class whose name has been set to the value supplied in typename you use this class to create instances of named tuples the verbose flagif set to trueprints the resulting class definition to standard output here is an example of using this functionfrom collections import namedtuple networkaddress namedtuple('networkaddress',['hostname','port'] networkaddress('www python org', hostname 'www python orga port hostport len( type(aisinstance(atupletrue in this examplethe named tuple networkaddress isin every wayindistinguished from normal tuple except for the added support of being able to use attribute lookup such as hostname or port to access tuple components the underlying implementation is efficient--the class that is created does not use an instance dictionary or add any additional memory overhead in built-in tuple all of the normal tuple operations still work named tuple can be useful if defining objects that really only serve as data structures for exampleinstead of defining classlike thisclass stock(object)def _init_ (self,name,shares,price)self name name self shares shares self price price you could define named tuple insteadimport collections stock collections namedtuple('stock','name shares price'both versions are going to work in nearly identical manner for examplein either caseyou would access fields by writing names sharesand so on howeverthe benefit of the named tuple is that it is more memory-efficient and supports various tuple operations such as unpacking (for exampleif you had list of named tuplesyou could unpack values in for-loop with statement such as for namesharesf lib fl ff
18,112
price in stocklistthe downside to named tuple is that attribute access is not as efficient as with class for exampleaccessing shares is more than twice as slow if is an instance of named tuple instead of an ordinary class named tuples are frequently used in other parts of the python standard library heretheir use is partly historical--in many library modulestuples were originally used as the return value of various functions that would return information about filesstack framesor other low-level details code that used these tuples wasn' always so elegant thusthe switch to named tuple was made to clean up their usage without breaking backwards compatibility another subtle problem with tuples is that once you start using tuplethe expected number of fields is locked forever ( if you suddenly add new fieldold code will breakvariants of named tuples have been used in the library to add new fields to the data returned by certain functions for examplean object might support legacy tuple interfacebut then provide additional values that are only available as named attributes abstract base classes the collections module defines series of abstract base classes the purpose of these classes is to describe programming interfaces on various kinds of containers such as listssetsand dictionaries there are two primary uses of these classes firstthey can be used as base class for user-defined objects that want to emulate the functionality of built-in container types secondthey can be used for type checking for exampleif you wanted to check that worked like sequenceyou could use isinstance(scollections sequencecontainer base class for all containers defines single abstract method _contains_ ()which implements the in operator hashable base class for objects that can be used as hash table key defines single abstract method _hash_ (iterable base class for objects that support the iteration protocol defines single abstract method _iter_ (iterator base class for iterator objects defines the abstract method next(but also inherits from iterable and provides default implementation of _iter_ (that simply does nothing sized base class for containers whose size can be determined defines the abstract method _len_ (callable base class for objects that support function call defines the abstract method _call_ ( lib fl ff
18,113
data structuresalgorithmsand code simplification sequence base class for objects that look like sequences inherits from containeriterableand sized and defines the abstract methods _getitem_ (and _len_ (also provides default implementation of _contains_ () _iter_ () _reversed_ ()index()and count(that are implemented using nothing but the _getitem_ (and _len_ (methods mutablesequence base class for mutable sequences inherits from sequence and adds the abstract methods _setitem_ (and _delitem_ (also provides default implementation of append()reverse()extend()pop()remove()and _iadd_ (set base class for objects that work like sets inherits from containeriterableand sized and defines the abstract methods _len_ () _iter_ ()and _contains_ (also provides default implementation of the set operators _le_ () _lt_ () _eq_ () _ne_ () _gt_ () _ge_ () _and_ () _or_ () _xor_ () _sub_ ()and isdisjoint(mutableset base class for mutable sets inherits from set and adds the abstract methods add(and discard(also provides default implementation of clear()pop()remove() _ior_ () _iand_ () _ixor_ ()and _isub_ (mapping base class for objects that support mapping (dictionarylookup inherits from sizediterableand container and defines the abstract methods _getitem_ () _len_ ()and _iter_ ( default implementation of _contains_ ()keys()items()values()get() _eq_ ()and _ne_ (is also provided mutablemapping base class for mutable mapping objects inherits from mapping and adds the abstract methods _setitem_ (and _delitem_ (an implementation of pop()popitem()clear()update()and setdefault(is also added mappingview base class for mapping views mapping view is an object that is used for accessing the internals of mapping object as set for examplea key view is set-like object that shows the keys in mapping see appendix "python for more details keysview base class for key view of mapping inherits from mappingview and set itemsview base class for item view of mapping inherits from mappingview and set valuesview base class for (keyitemview of mapping inherits from mappingview and set lib fl ff
18,114
python' built-in types are already registered with all of these base classes as appropriate alsoby using these base classesit is possible to write programs that are more precise in their type checking here are some examplespull off the last item of sequence if isinstance(xcollections sequence)last [- only iterate over an object if its size is known if isinstance(xcollections iterableand isinstance(xcollections sized)for item in xstatements add new item to set if isinstance(xcollections mutableset) add(itemsee also"classes and object-oriented programming contextlib the contextlib module provides decorator and utility functions for creating context managers used in conjunction with the with statement contextmanager(funca decorator that creates context manager from generator function func the way in which you use this decorator is as follows@contextmanager def foo(args)statements tryyield value except exception as eerror handling (if anystatements when the statement with foo(argsas value appearsthe generator function is executed with the supplied arguments until the first yield statement is reached the value returned by yield is placed into the variable value at this pointthe body of the with statement executes upon completionthe generator function resumes if any kind of exception is raised inside the with-bodythat exception is raised inside the generator function where it can be handled as appropriate if the error is to be propagatedthe generator should use raise to re-raise the exception an example of using this decorator can be found in the "context managerssection of nested(mgr mgr mgrna function that invokes more than one context manager mgr mgr and so on as single operation returns tuple containing the different return values of the with statements the statement with nested( , as ( , )statements is the same as lib fl ff
18,115
data structuresalgorithmsand code simplification saying with as xwith as ystatements be aware that if an inner context manager traps and suppresses an exceptionno exception information is passed along to the outer managers closing(objectcreates context manager that automatically executes object close(when execution leaves the body of the with statement the value returned by the with statement is the same as object functools the functools module contains functions and decorators that are useful for creating higher-order functionsfunctional programmingand decorators partial(function [*args [**kwargs]]creates function-like objectpartialthat when calledcalls function with positional arguments argskeyword arguments kwargsand any additional positional or keyword arguments that are supplied additional positional arguments are added to the end of argsand additional keyword arguments are merged into kwargsoverwriting any previously defined values (if anya typical use of partial(is when making large number of function calls where many of the arguments are held fixed for examplefrom functools import partial mybutton partial(buttonrootfg="black",bg="white",font="times",size=" " mybutton(text="ok"calls button(with text="okand all of the mybutton(text="cancel"additional arguments supplied to partial(above mybutton(text="restart"an instance of the object created by partial has the following attributesitem description func args function that is called when is called tuple containing the leftmost positional arguments supplied to func when called additional positional arguments are concatenated to the end of this value dictionary containing the keyword arguments supplied to func when called additional keyword arguments are merged into this dictionary keywords use caution when using partial object as stand-in for regular function the result is not exactly the same as normal function for instanceif you use partial(inside class definitionit behaves like static methodnot an instance method reduce(functionitems [initial]applies functionfunctioncumulatively to the items in the iterable items and returns single value function must take two arguments and is first applied to the first two items of items this result and subsequent elements of items are then combined one at time in similar manneruntil all elements of items have been consumed initial is an optional starting value used in the first computation and when items is lib fl ff
18,116
empty this function is the same as the reduce(function that was built-in in python for future compatibilityuse this version instead update_wrapper(wrapperwrapped [assigned [updated]]this is utility function that is useful when writing decorators copies attributes from function wrapped to wrapper function wrapper in order to make the wrapped function look like the original function assigned is tuple of attribute names to copy and is set to (' _name_ ',' _module_ ',' _doc_ 'by default updated is tuple containing the names of function attributes that are dictionaries and which you want values merged in the wrapper by defaultit is tuple (' _dict_ ',wraps(function [assigned [updated ]] decorator carries out the same task as update_wrapper(on the function to which it is applied assigned and updated have the same meaning typical use of this decorator is when writing other decorators for examplefrom functools import wraps def debug(func)@wraps(funcdef wrapped(*args,**kwargs)print("calling %sfunc _name_ _r func(*args,**kwargsprint("done calling %sfunc _name_ _return wrapped @debug def add( , )return + see also"functions and functional programming heapq the heapq module implements priority queue using heap heaps are simply lists of ordered items in which the heap condition has been imposed specificallyheap[ <heap[ * + and heap[ <heap[ * + for all nstarting with heap[ always contains the smallest item heapify(xconverts listxinto heapin place heappop(heapreturns and removes the smallest item from heappreserving the heap condition raises indexerror if heap is empty heappush(heapitemadds item to the heappreserving the heap condition lib fl ff
18,117
data structuresalgorithmsand code simplification heappushpop(heapitemadds item to the heap and removes the smallest item from heap in single operation this is more efficient than calling heappush(and heappop(separately heapreplace(heapitemreturns and removes the smallest item from the heap at the same timea new item is added the heap condition is preserved in the process this function is more efficient than calling heappop(and heappush(in sequence in additionthe returned value is obtained prior to adding the new item thereforethe return value could be larger than item raises indexerror if heap is empty merge( creates an iterator that merges the sorted iterables and so on into single sorted sequence this function does not consume the inputs but returns an iterator that incrementally processes the data nlargest(niterable [key]creates list consisting of the largest items in iterable the largest item appears first in the returned list key is an optional function that takes single input parameter and computes the comparison key for each item in iterable nsmallest(niterable [key]creates list consisting of the smallest items in iterable the smallest item appears first in the returned list key is an optional key function note the theory and implementation of heap queues can be found in most books on algorithms itertools the itertools module contains functions for creating efficient iteratorsuseful for looping over data in various ways all the functions in this module return iterators that can be used with the for statement and other functions involving iterators such as generators and generator expressions chain(iter iter iterngiven group of iterators (iter itern)this function creates new iterator that chains all the iterators together the returned iterator produces items from iter until it is exhausted then items from iter are produced this continues until all the items in itern are exhausted chain from_iterable(iterablesan alternative constructor for chain where the iterables is an iterable that produces sequence of iterable objects the result of this operation is the same as what would be produced by the following fragment of generator codef lib fl ff
18,118
for it in iterablesfor in ityield combinations(iterablercreates an iterator that returns all -length subsequences of items taken from iterable the items in the returned subsequences are ordered in the same way in which they were ordered in the input iterable for exampleif iterable is the list [ , , , ]the sequence produced by combinations([ , , , ] is [ , ][ , ][ , ][ , ][ , count([ ]creates an iterator that produces consecutive integers starting with if is omittedcounting starts at (note that this iterator does not support long integers if sys maxint is exceededthe counter overflows and continues to count starting with -sys maxint cycle(iterablecreates an iterator that cycles over the elements in iterable over and over again internallya copy of the elements in iterable is made this copy is used to return the repeated items in the cycle dropwhile(predicateiterablecreates an iterator that discards items from iterable as long as the function predicate(itemis true once predicate returns falsethat item and all subsequent items in iterable are produced groupby(iterable [key]creates an iterator that groups consecutive items produced by iterable the grouping process works by looking for duplicate items for instanceif iterable produces the same item on several consecutive iterationsthat defines group if this is applied to sorted listthe groups would define all the unique items in the list keyif suppliedis function that is applied to each item if presentthe return value of this function is used to compare successive items instead of the items themselves the iterator returned by this function produces tuples (keygroup)where key is the key value for the group and group is an iterator that yields all the items that made up the group ifilter(predicateiterablecreates an iterator that only produces items from iterable for which predicate(itemis true if predicate is noneall the items in iterable that evaluate as true are returned ifilterfalse(predicateiterablecreates an iterator that only produces items from iterable for which predicate(itemis false if predicate is noneall the items in iterable that evaluate as false are returned lib fl ff
18,119
data structuresalgorithmsand code simplification imap(functioniter iter iterncreates an iterator that produces items function( , in)where in are items taken from the iterators iter iter iternrespectively if function is nonethe tuples of the form ( inare returned iteration stops whenever one of the supplied iterators no longer produces any values islice(iterable[start,stop [step]creates an iterator that produces items in manner similar to what would be returned by sliceiterable[start:stop:stepthe first start items are skipped and iteration stops at the position specified in stop step specifies stride that' used to skip items unlike slicesnegative values may not be used for any of startstopor step if start is omittediteration starts at if step is omitteda step of is used izip(iter iter iterncreates an iterator that produces tuples ( in)where in are taken from the iterators iter iter iternrespectively iteration stops whenever one of the supplied iterators no longer produces any values this function produces the same values as the built-in zip(function izip_longest(iter iter itern [,fillvalue=none]the same as izip(except that iteration continues until all of the input iterables iter iter and so on are exhausted none is used to fill in values for the iterables that are already consumed unless different value is specified with the fillvalue keyword argument permutations(iterable [ ]creates an iterator that returns all -length permutations of items from iterable if is omittedthen permutations have the same length as the number of items in iterable product(iter iter itern[repeat= ]creates an iterator that produces tuples representing the cartesian product of items in item item and so on repeat is keyword argument that specifies the number of times to repeat the produced sequence repeat(object [times]creates an iterator that repeatedly produces object timesif suppliedspecifies repeat count otherwisethe object is returned indefinitely starmap(func [iterable]creates an iterator that produces the values func(*item)where item is taken from iterable this only works if iterable produces items suitable for calling function in this manner takewhile(predicate [iterable]creates an iterator that produces items from iterable as long as predicate(itemis true iteration stops immediately once predicate evaluates as false lib fl ff
18,120
tee(iterable [ ]creates independent iterators from iterable the created iterators are returned as an -tuple the default value of is this function works with any iterable object howeverin order to clone the original iteratorthe items produced are cached and used in all the newly created iterators great care should be taken not to use the original iterator iterable after tee(has been called otherwisethe caching mechanism may not work correctly examples the following examples illustrate how some of the functions in the itertools module operatefrom itertools import iterate over the numbers , , , , , in an endless cycle for in cycle(chain(range( ),range( , ,- )))print create list of unique items in [ , , , , , , , , , , sort( [ for , in groupby( ) [ , , , , , iterate over all possible combinations of pairs of values from and [ , , , , [ , , for in product( , )print(rproduces output ( , ),( , ),( , )( , ),( , ),( , operator the operator module provides functions that access the built-in operators and special methods of the interpreter described in "types and objects for exampleadd( is the same as for operations that also have an in-place versionyou can use function such as iadd( ,ywhich is the same as + the following list shows functions defined in the operator module and how they are mapped onto various operatorsfunction description add(absub(abmul(abdiv(abfloordiv(abtruediv(abmod(abneg(apos(aabs(ainv( )invert(areturns for numbers returns returns for numbers returns (old divisionreturns / returns (new divisionreturns returns - returns + returns the absolute value of returns the inverse of continues lib fl ff
18,121
data structuresalgorithmsand code simplification function description returns < returns > returns (bitwise andreturns (bitwise orxor(abreturns (bitwise xornot_(areturns not lt(abreturns le(abreturns < eq(abreturns = ne(abreturns ! gt(abreturns ge(abreturns > truth(areturns true if is truefalse otherwise concat(abreturns for sequences repeat(abreturns for sequence and integer contains(abreturns the result of in countof(abreturns the number of occurrences of in indexof(abreturns the index of the first occurrence of in getitem(abreturns [bsetitem(abca [bc delitem(abdel [bgetslice(abcreturns [ :csetslice(abcvsets [ :cv delslice(abcdel [ :cis_(aba is is_not(aba is not lshift(abrshift(aband_(abor_(abat first glanceit might not be obvious why anyone would want to use these functions because the operations they perform can easily be accomplished by simply typing the normal syntax where these functions are useful is when working with code uses callback functions and where you might otherwise be defining an anonymous function with lambda for exampleconsider the following timing benchmark that uses the functools reduce(functionfrom timeit import timeit timeit("reduce(operator add, )","import operatora range( )" timeit("reduce(lambda ,yx+ , )","import operatora range( )" in the examplenotice how using operator add as the callback runs more than twice as fast as the version that uses lambda ,yx+ lib fl ff
18,122
the operator module also defines the following functions that create wrappers around attribute accessitem lookupand method calls attrgetter(name [name [[namen]]]creates callable objectfwhere call to (objreturns obj name if more than one argument is givena tuple of results is returned for exampleattrgetter('name','shares'returns (obj nameobj shareswhen called name can also include additional dot lookups for exampleif name is "address hostname"then (objreturns obj address hostname itemgetter(item [item [[itemn]]]creates callable objectfwhere call to (objreturns obj[itemif more than one item is given as argumentsa call to (objreturns tuple containing (obj[item]obj[item ]obj[itemn]methodcaller(name [*args [**kwargs]]creates callable objectfwhere call to (objreturns obj name(*args**kwargsthese functions are also useful for optimizing the performance of operations involving callback functionespecially those involving common data processing operations such as sorting for exampleif you wanted to sort list of tuples rows on column you could either use sorted(rowskey=lambda rr[ ]or use sorted(rowskey=itemgetter( )the second version runs much faster because it avoids the overhead associated with lambda lib fl ff
18,123
lib fl ff
18,124
string and text handling his describes the most commonly used python modules related to basic string and text processing the focus of this is on the most common string operations such as processing textregular expression pattern matchingand text formatting codecs the codecs module is used to handle different character encodings used with unicode text / the module is used both to define new character encodings and to process character data using wide range of existing encodings such as utf- utf- etc it is far more common for programmers to simply use one of the existing encodingsso that is what is discussed here if you want to create new encodingsconsult the online documentation for further details low-level codecs interface each character encoding is assigned common name such as 'utf- or 'big the following function is used to perform lookup lookup(encodinglooks up codec in the codec registry encoding is string such as 'utf- if nothing is known about the requested encodinglookuperror is raised otherwisean instance of codecinfo is returned codecinfo instance has the following methodsc encode( [errors] stateless encoding function that encodes the unicode string and returns tuple (byteslength_consumedbytes is an -bit string or byte-array containing the encoded data length_consumed is the number of characters in that were encoded errors is the error handling policy and is set to 'strictby default decode(bytes [errors] stateless encoding function that decodes byte string bytes and returns tuple (slength_consumeds is unicode stringand length_consumed is the number of bytes in bytes that were consumed during decoding errors is the error-handling policy and is set to 'strictby default lib fl ff
18,125
string and text handling streamreader(bytestream [errors]returns streamreader instance that is used to read encoded data bytestream is file-like object that has been opened in binary mode errors is the error-handling policy and is 'strictby default an instance of streamreader supports the following low-level / operationsmethod description read([size [chars [firstline]]]returns at most chars characters of decoded text size is the maximum number of bytes to read from low-level byte-stream and is used to control internal buffering firstline is flag thatif setreturns the first line even if decoding error occurs later in the file readline([size [keepends]]returns single line of decoded text keepends is flag that controls whether or not the line endings are preserved (true by defaultr readlines([size [keepends]]reads all of the lines into list reset(resets the internal buffers and state streamwriter(bytestream [errors]returns streamwriter instance that is used to write encoded data bytestream is file-like object that has been opened in byte-mode errors is the error handling policy and is 'strictby default an instance of streamwriter supports the following low-level / operationsmethod description write(sw writelines(linesw reset(writes an encoded representation of string writes list of strings in lines to the file resets the internal buffers and state incrementalencoder([errors]returns an incrementalencoder instance that can be used to encode strings in multiple steps errors is 'strictby default an instance of incrementalencoder has these methodsmethod description encode( [,final]returns an encoded representation of string as byte string final is flag that should be set to true on the final call to encode(resets the internal buffers and state reset( lib fl ff
18,126
incrementaldecoder([errors]returns an incrementaldecoder instance that can be used to decode byte strings in multiple steps errors is 'strictby default an instance of incrementaldecoder has these methodsmethod description decode(bytes [,final]returns decoded string from the encoded bytes in bytes final is flag that should be set to true on the final call to decode(resets the internal buffers and state reset( / -related functions the codecs module provides collection of high-level functions that are used to simplify / involving encoded text most programmers will use one of these functions instead of the low-level codecs interface described in the first section open(filenamemode[encoding[errors[buffering]]]opens filename in the given mode and provides transparent data encoding/decoding according to the encoding specified in encoding errors is one of 'strict''ignore''replace''backslashreplace'or 'xmlcharrefreplacethe default is 'strictbuffering has the same meaning as for the built-in open(function regardless of the mode specified in modethe underlying file is always opened in binary mode in python you can use the built-in open(function instead of codecs open(encodedfile(fileinputenc[outputenc [errors]] class that provides an encoding wrapper around an existing file objectfile data written to the file is first interpreted according to the input encoding inputenc and then written to the file using the output encoding outputenc data read from the file is decoded according to inputenc if outputenc is omittedit defaults to inputenc errors has the same meaning as for open(and defaults to 'strictiterencode(iterableencoding [errors] generator function that incrementally encodes all of the strings in iterable to the specified encoding errors is 'strictby default iterdecode(iterableencoding [errors] generator function that incrementally decodes all of the byte strings in iterable according to the specified encoding errors is 'strictby default useful constants codecs defines the following byte-order marker constants that can be used to help interpret files when you don' know anything about the underlying encoding these lib fl ff
18,127
byte-order markers are sometimes written at the beginning of file to indicate its character encoding and can be used to pick an appropriate codec to use constant description bom bom_be native byte-order marker for the machine (bom_be or bom_lebig-endian byte-order marker ('\xfe\xff'little-endian byte-order marker ('\xff\xfe'utf- marker ('\xef\xbb\xbf' -bit utf- big-endian marker ('\xfe\xff' -bit utf- little-endian marker ('\xff\xfe' -bit utf- big-endian marker ('\ \ \xfe\xff' -bit utf- little-endian marker ('\xff\xfe\ \ 'bom_le bom_utf bom_utf _be bom_utf _le bom_utf _be bom_utf _le standard encodings the following is list of some of the most commonly used character encodings the encoding name is what you would pass to functions such as open(or lookup(when specifying an encoding full list of encodings can be found by consulting the online documentation for the codecs module (codec name description ascii cp cp latin- iso- - utf- utf- -be utf- -le utf- utf- -be utf- -le utf- -bit ascii characters extended ascii character set from ms-dos extended ascii character set from windows ascii extended with latin characters utf- utf- big-endian utf- little-endian utf- utf- big-endian utf- little-endian utf- notes further use of the codecs module is described in "input and output consult the online documentation for information on how to create new kinds of character encodings great care needs to be taken with the inputs to encode(and decode(operations all encode(operations should be given unicode stringsand all decode(operations should be given byte strings python is not entirely consistent in this regardwhereas python strictly enforces the distinction between strings for examplepython has some codecs that map byte-strings to bytestrings ( the "bz codecthese are unavailable in python and should not be used if you care about compatibility lib fl ff
18,128
re the re module is used to perform regular-expression pattern matching and replacement in strings both unicode and byte-strings are supported regular-expression patterns are specified as strings containing mix of text and special-character sequences because patterns often make extensive use of special characters and the backslashthey're usually written as "rawstringssuch as '(? \ +)(\ *)for the remainder of this sectionall regular-expression patterns are denoted using the raw string syntax pattern syntax the following special-character sequences are recognized in regular expression patternscharacter(sdescription text matches the literal string text matches any character except newline matches the start of string matches the end of string matches zero or more repetitions of the preceding expressionmatching as many repetitions as possible matches one or more repetitions of the preceding expressionmatching as many repetitions as possible matches zero repetitions or one repetition of the preceding expression matches zero or more repetitions of the preceding expressionmatching as few repetitions as possible matches one or more repetitions of the preceding expressionmatching as few repetitions as possible matches zero or one repetitions of the preceding expressionmatching as few repetitions as possible matches exactly repetitions of the preceding expression matches from to repetitions of the preceding expressionmatching as many repetitions as possible if is omittedit defaults to if is omittedit defaults to infinity matches from to repetitions of the preceding expressionmatching as few repetitions as possible matches set of characters such as '[abcdef]or '[ -za- ]special characters such as are not active inside set matches the characters not in the setsuch as '[^ - ]matches either or bwhere and are both regular expressions matches the regular expression inside the parentheses as group and saves the matched substring the contents of group can be obtained using the group(method of matchobject objects obtained while matching *+?{ {mn{mn}[ | continues lib fl ff
18,129
string and text handling character(sdescription interprets the letters " "" "" "" "" "" "and "xas flag settings corresponding to the re are ire lre mre sre ure flag settings given to re compile("aonly available in python (?matches the regular expression inside the parentheses but discards the matched substring (? matches the regular expression in the parentheses and creates named group the group name must be valid python identifier (? =namematches the same text that was matched by an earlier named group (? comment the contents of the parentheses are ignored (?matches the preceding expression only if followed by the pattern in the parentheses for exampler'hello (?=world)matches 'hello only if followed by 'world(?matches the preceding expression only if it' not followed by the pattern in parentheses for exampler'hello (?!world)matches 'hello only if it' not followed by 'world(?<matches the following expression if it' preceded by match of the pattern in parentheses for exampler'(?<=abc)defmatches 'defonly if it' preceded by 'abc(?<matches the following expression only if it' not preceded by match of the pattern in parentheses for exampler'(?<!abc)defmatches 'defonly if it' not preceded by 'abc(?(id|name)ypat|npatchecks to see whether the regular expression group identified by id or name exists if sothe regular expression ypat is matched if notthe optional expression npat is matched for examplethe pattern '(hello)?(?( world|howdy)matches the string 'hello worldor the string 'howdy(?ailmsuxstandard character escape sequences such as '\nand '\tare recognized as standard characters in regular expression (for exampler'\ +would match one or more newline charactersin additionliteral symbols that normally have special meaning in regular expression can be specified by preceding them with backslash for exampler'\*matches the character in additiona number of backslash sequences correspond to special sets of characterscharacter(sdescription \number matches the text that was matched by previous group number groups are numbered from to starting from the left matches only at the start of the string matches the empty string at the beginning or end of word word is sequence of alphanumeric characters terminated by whitespace or any other nonalphanumeric character \ \ lib fl ff
18,130
character(sdescription \ \ \ \ matches the empty string not at the beginning or end of word matches any decimal digit same as '[ - ]matches any nondigit character same as '[^ - ]matches any whitespace character same as '[\ \ \ \ \ ]matches any nonwhitespace character same as '[\ \ \ \ \ ]matches any alphanumeric character matches any character not contained in the set defined by \ matches only at the end of the string matches literal backslash \ \ \ \ \the \ \ \ \ \wand \ special characters are interpreted differently if matching unicode strings in this casethey match all unicode characters that match the described property for example\ matches any unicode character that is classified as digit such as europeanarabicand indic digits which each occupy different range of unicode characters functions the following functions are used to perform pattern matching and replacementcompile(str [flags]compiles regular-expression pattern string into regular-expression object this object can be passed as the pattern argument to all the functions that follow the object also provides number of methods that are described shortly flags is the bitwise or of the followingflag description or ascii or ignorecase or locale or multiline perform -bit ascii-only matching (python onlyperforms non-case-sensitive matching uses locale settings for \ \ \band \ makes and apply to each line in addition to the beginning and end of the entire string (normally and apply only to the beginning and end of an entire string makes the dot character match all charactersincluding the newline uses information from the unicode character properties database for \ \ \band \ (python only python uses unicode by default ignores unescaped whitespace and comments in the pattern string or dotall or unicode or verbose escape(stringreturns string with all nonalphanumerics backslashed findall(patternstring [,flags]returns list of all nonoverlapping matches of pattern in stringincluding empty matches if the pattern has groupsa list of the text matched by the groups is returned lib fl ff
18,131
string and text handling if more than one group is usedeach item in the list is tuple containing the text for each group flags has the same meaning as for compile(finditer(patternstring[flags]the same as findall()but returns an iterator object instead the iterator returns items of type matchobject match(patternstring [flags]checks whether zero or more characters at the beginning of string match pattern returns matchobject on success or none otherwise flags has the same meaning as for compile(search(patternstring [flags]searches string for the first match of pattern flags has the same meaning as for compile(returns matchobject on success or none if no match was found split(patternstring [maxsplit ]splits string by the occurrences of pattern returns list of strings including the text matched by any groups in the pattern maxsplit is the maximum number of splits to perform by defaultall possible splits are performed sub(patternreplstring [count ]replaces the leftmost nonoverlapping occurrences of pattern in string by using the replacement repl repl can be string or function if it' functionit' called with matchobject and should return the replacement string if repl is stringbackreferences such as '\ are used to refer to groups in the pattern the sequence '\gis used to refer to named group count is the maximum number of substitutions to perform by defaultall occurrences are replaced although these functions don' accept flags parameter like compile()the same effect can be achieved by using the (?ilmsuxnotation described earlier in this section subn(patternreplstring [count ]same as sub()but returns tuple containing the new string and the number of substitutions regular expression objects compiled regular-expression objectrcreated by the compile(function has the following methods and attributesr flags the flags argument used when the regular expression object was compiledor if no flags were specified groupindex dictionary mapping symbolic group names defined by '(? )to group numbers pattern the pattern string from which the regular expression object was compiled lib fl ff
18,132
findall(string [pos [endpos]]identical to the findall(function pos and endpos specify the starting and ending positions for the search finditer(string [pos [endpos]]identical to the finditer(function pos and endpos specify the starting and ending positions for the search match(string [pos[endpos]checks whether zero or more characters at the beginning of string match pos and endpos specify the range of string to be searched returns matchobject for match and returns none otherwise search(string [pos[endpos]searches string for match pos and endpos specify the starting and ending positions for the search returns matchobject for match and returns none otherwise split(string [maxsplit ]identical to the split(function sub(replstring [count ]identical to the sub(function subn(replstring [count ]identical to the subn(function match objects the matchobject instances returned by search(and match(contain information about the contents of groups as well as positional data about where matches occurred matchobject instancemhas the following methods and attributesm expand(templatereturns string that would be obtained by doing regular-expression backslash substitution on the string template numeric back-references such as "\ and "\ and named references such as "\gand "\gare replaced by the contents of the corresponding group note that these sequences should be specified using raw strings or with literal backslash character such as '\ or '\\ group([group group ]returns one or more subgroups of the match the arguments specify group numbers or group names if no group name is giventhe entire match is returned if only one group is givena string containing the text matched by the group is returned otherwisea tuple containing the text matched by each of the requested groups is returned an indexerror is raised if an invalid group number or name is given groups([default]returns tuple containing the text matched by all groups in pattern default is the value returned for groups that didn' participate in the match (the default is nonef lib fl ff
18,133
string and text handling groupdict([default]returns dictionary containing all the named subgroups of the match default is the value returned for groups that didn' participate in the match (the default is nonem start([group] end([group]these two methods return the indices of the start and end of the substring matched by group if group is omittedthe entire matched substring is used returns none if the group exists but didn' participate in the match span([group]returns -tuple ( start(group) end(group)if group didn' contribute to the matchthis returns (nonenoneif group is omittedthe entire matched substring is used pos the value of pos passed to the search(or match(function endpos the value of endpos passed to the search(or match(function lastindex the numerical index of the last group that was matched it' none if no groups were matched lastgroup the name of the last named group that was matched it' none if no named groups were matched or present in the pattern re the regular-expression object whose match(or search(method produced this matchobject instance string the string passed to match(or search(example the following example shows how to use the re module to search forextract data fromand replace text pattern in string import re text "guido will be out of the office from regex pattern for date datepat re compile('(\ +)/(\ +)/(\ +)'find and print all dates for in datepat finditer(text)print( group() lib fl ff
18,134
find all datesbut print in different format monthnames [none,'jan','feb','mar','apr','may','jun''jul','aug','sep','oct','nov','dec'for in datepat finditer(text)print ("% % % (monthnames[int( group( )] group( ) group( ))replace all dates with fields in the european format (day/month/yeardef fix_date( )return "% /% /% ( group( ), group( ), group( )newtext datepat sub(fix_datetextan alternative replacement newtext datepat sub( '\ /\ /\ 'textnotes detailed information about the theory and implementation of regular expressions can be found in textbooks on compiler construction the book mastering regular expressions by jeffrey friedl ( 'reilly associates may also be useful the most difficult part of using the re module is writing the regular expression patterns for writing patternsconsider using tool such as kodos ( string the string module contains number of useful constants and functions for manipulating strings it also contains classes for implementing new string formatters constants the following constants define various sets of characters that may be useful in various string processing operations constant description ascii_letters ascii_lowercase ascii_uppercase digits hexdigits letters lowercase string containing all lowercase and uppercase ascii letters the string 'abcdefghijklmnopqrstuvwxyzthe string 'abcdefghijklmnopqrstuvwxyzthe string ' the string ' abcdefabcdefconcatenation of lowercase and uppercase string containing all lowercase letters specific to the current locale setting the string ' string of ascii punctuation characters string of printable characters-- combination of lettersdigitspunctuationand whitespace string containing all uppercase letters specific to the current locale setting string containing all whitespace characters this usually includes spacetablinefeedreturnformfeedand vertical tab octdigits punctuation printable uppercase whitespace lib fl ff
18,135
string and text handling note that some of these constants (for exampleletters and uppercasewill vary depending on the locale settings of the system formatter objects the str format(method of strings is used to perform advanced string formatting operations as seen in "types and objects,and "operators and expressions,this method can access items of sequences or mappingsattributes of objectsand other kinds of related operations the string module defines class formatter that can be used to implement your own customized formatting operation this class exposes the pieces that implement the string formatting operation and allow you to customize them formatter(creates new formatter instance an instance of formatter supports the following operations format(format_string*args**kwargsformats the string format_string by defaultthe output is the same as calling format_string format(*args**kwargsfor examplef format("{nameis { :dyears old" ,name="dave"creates the string "dave is years oldf vformat(format_stringargskwargsa method that actually carries out the work of format(args is tuple of positional argumentsand kwargs is dictionary of keyword arguments this is faster method to use if you have already captured argument information in tuple and dictionary parse(format_stringa function that creates an iterator for parsing the contents of the format string format_string the iterator sweeps over the format string and produces tuples of the format (literal_textfield_nameformat_specconversionliteral_text is any literal text that precedes the next format specifier enclosed in braces it may be an empty string if there is no leading text field_name is string that specifies the field name in the format specifier for exampleif the specifier is '{ : }'then the field name is ' format_spec is the format specifier that appears after the colon--for example'din the previous example it will be an empty string if it wasn' specified conversion is string containing the conversion specifier (if anyin the previous exampleit is nonebut if the specifier was '{ ! : }'it would be set to 'sfield_nameformat_specand conversion will all be none for the last fragment of the format string get_field(fieldnameargskwargsextracts the value associated with given fieldname from args and kwargs fieldname is string such as " or "nameas returned by the parse(method shown previously returns tuple (valuekeywhere value is the field value and key is used to locate the value in args or kwargs if key is an integerit is an index in args if it is stringit is the key used in kwargs the fieldname may include additional indexing and attribute lookup such as ' nameor ' [name]in this casethe method lib fl ff
18,136
carries out the extra lookup and returns the appropriate value howeverthe value of key in the returned tuple is just set to ' get_value(keyargskwargsextracts the object from args or kwargs corresponding to key if key is an integerthe object is taken from args if it is stringit is taken from kwargs check_unused_args(used_argsargskwargschecks for unused arguments in the format(operation used_args is set of all of the used argument keys (see get_field()that were found in the format string args and kwargs are the positional and keyword arguments passed to format(the default behavior is to raise typeerror for unused arguments format_value(valueformat_specformats single value according to the given format specification by defaultthis simply executes the built-in function format(valueformat_specf convert_field(valueconversionconverts value returned by get_field(according to the specified conversion code if conversion is nonevalue is returned unmodified if conversion is 'sor ' 'value is converted to string using str(or repr()respectively if you want to create your own customized string formattingyou can create formatter object and simply use the default methods to carry out the formatting as you wish it is also possible to define new class that inherits from formatter and reimplements any of the methods shown earlier for details on the syntax of format specifiers and advanced string formattingrefer to and template strings the string module defines new string typetemplatethat simplifies certain string substitutions an example can be found in the following creates new template string objecttemplate(sheres is string and template is defined as class template objecttsupports the following methodst substitute( [**kwargs]this method takes mapping objectm (for examplea dictionary)or list of keyword arguments and performs keyword substitution on the string this substitution replaces the string '$$with single '$and the strings '$keyor '${key}with ['key'or kwargs['key'if keyword arguments were supplied key must spell valid python identifier if the final string contains any unresolved '$keypatternsa keyerror exception is raised safe_substitute( [**kwargs]the same as substitute(except that no exceptions or errors will be generated insteadunresolved $key references will be left in the string unmodified lib fl ff
18,137
string and text handling template contains the original strings passed to template(the behavior of the template class can be modified by subclassing it and redefining the attributes delimiter and idpattern for examplethis code changes the escape character to and restricts key names to letters onlyclass mytemplate(string template)delimiter '@literal character for escape sequence idpattern '[ - ]*identifier regular expression pattern utility functions the string module also defines couple of functions for manipulating strings that aren' defined as method on string objects capwords(scapitalizes the first letter of each word in sreplaces repeated whitespace characters with single spaceand removes leading and trailing whitespace maketrans(fromtocreates translation table that maps each character in from to the character in the same position in to from and to must be the same length this function is used to create arguments suitable for use with the translate(method of strings struct the struct module is used to convert data between python and binary data structures (represented as python byte stringsthese data structures are often used when interacting with functions written in cbinary file formatsnetwork protocolsor binary communication over serial ports packing and unpacking functions the following module-level functions are used to pack and unpack data in byte strings if your program is repeatedly performing these operationsconsider the use of struct object described in the next section pack(fmtv packs the values and so on into byte string according to the format string in fmt pack_into(fmtbufferoffsetv packs the values and so forth into writable buffer object buffer starting at byte offset offset this only works with objects that support the buffer interface examples include array array and bytearray objects unpack(fmtstringunpacks the contents of byte string according to the format string in fmt returns tuple of the unpacked values the length of string must exactly match the size of the format as determined by the calcsize(function lib fl ff
18,138
unpack_from(fmtbufferoffsetunpacks the contents of buffer object according to the format string in fmt starting at offset offset returns tuple of the unpacked values calcsize(fmtcalculates the size in bytes of the structure corresponding to format string fmt struct objects the struct module defines class struct that provides an alternative interface for packing and unpacking using this class is more efficient because the format string is only interpreted once struct(fmtcreates struct instance representing data packed according to the given format code an instance of struct has the following methods that work exactly the same as their functional counterparts described in the previous sectionmethod description pack( packs values into byte string pack_into(bufferoffsetv packs values into buffer object unpack(bytesunpacks values from byte string unpack_from(bufferoffsetunpacks values from buffer object format the format code being used size the size in bytes of the format format codes the format strings used in the struct module are sequence of characters with the following interpretationsformat type python type ' ' ' ' '?' ' ' ' ' ' ' 'qpad byte char signed char unsigned char _bool ( short unsigned short int unsigned int long unsigned long long long unsigned long long no value string of length integer integer boolean integer integer integer integer integer integer long long continues lib fl ff
18,139
format type python type ' ' ' 'pfloat double char[char['pvoid float float string string with length encoded in the first byte integer each format character can be preceded by an integer to indicate repeat count (for example' iis the same as 'iiii'for the 'sformatthe count represents the maximum length of the stringso ' srepresents -byte string format of ' sindicates string of zero length the 'pformat is used to encode string in which the length appears in the first bytefollowed by the string data this is useful when dealing with pascal codeas is sometimes necessary on the macintosh note that the length of the string in this case is limited to characters when the 'iand 'lformats are used to unpack valuethe return value is python long integer in additionthe 'pformat may return an integer or long integerdepending on the word size of the machine the first character of each format string can also specify byte ordering and alignment of the packed dataas shown hereformat byte order size and alignment '@'='<'>'!native native little-endian big-endian network (big-endiannative standard standard standard standard native byte ordering may be little-endian or big-endiandepending on the machine architecture the native sizes and alignment correspond to the values used by the compiler and are implementation-specific the standard alignment assumes that no alignment is needed for any type the standard size assumes that short is bytesint is byteslong is bytesfloat is bitsand double is bits the 'pformat can only use native byte ordering notes sometimes it' necessary to align the end of structure to the alignment requirements of particular type to do thisend the structure-format string with the code for that type with repeat count of zero for examplethe format 'llh lspecifies structure that ends on -byte boundary (assuming that longs are aligned on -byte boundariesin this casetwo pad bytes would be inserted after the short value specified by the 'hcode this only works when native size and alignment are being used--standard size and alignment don' enforce alignment rules the 'qand 'qformats are only available in "nativemode if the compiler used to build python supports the long long data type lib fl ff
18,140
see alsoarray ( )ctypes ( unicodedata the unicodedata module provides access to the unicode character databasewhich contains character properties for all unicode characters bidirectional(unichrreturns the bidirectional category assigned to unichr as string or an empty string if no such value is defined returns one of the followingvalue description lre lro al rle rlo pdf en es et an cs nsm bn ws on left-to-right left-to-right embedding left-to-right override right-to-left right-to-left arabic right-to-left embedding right-to-left override pop directional format european number european number separator european number terminator arabic number common number separator nonspacing mark boundary neutral paragraph separator segment separator whitespace other neutrals category(unichrreturns string describing the general category of unichr the returned string is one of the following valuesvalue description lu ll lt mn mc me letteruppercase letterlowercase lettertitle case marknonspacing markspacing combining markenclosing continues lib fl ff
18,141
string and text handling value description nd nl no zs numberdecimal digit numberletter numberother separatorspace separatorline separatorparagraph othercontrol otherformat othersurrogate otherprivate use othernot assigned lettermodifier letterother punctuationconnector punctuationdash punctuationopen punctuationclose punctuationinitial quote punctuationfinal quote punctuationother symbolmath symbolcurrency symbolmodifier symbolother zl zp cc cf cs co cn lm lo pc pd ps pe pi pf po sm sc sk so combining(unichrreturns an integer describing the combining class for unichr or if no combining class is defined one of the following values is returnedvalue description - spacingsplitenclosingreordrantand tibetan subjoined overlays and interior nuktas hiragana/katakana voicing marks viramas fixed-position classes below left attached below attached below right attached left attached right attached above left attached above attached above right attached lib fl ff
18,142
value description below left below below right left right above left above above right double below double above below (iota subscript decimal(unichr[default]returns the decimal integer value assigned to the character unichr if unichr is not decimal digitdefault is returned or valueerror is raised decomposition(unichrreturns string containing the decomposition mapping of unichr or the empty string if no such mapping is defined typicallycharacters containing accent marks can be decomposed into multicharacter sequences for exampledecomposition( "\ fc"(" "returns the string " corresponding to the letter and the umlaut ("accent mark the string returned by this function may also include the following stringsvalue description font variant (for examplea blackletter forma nonbreaking version of space or hyphen an initial presentation form (arabica medial presentation form (arabica final presentation form (arabican isolated presentation form (arabican encircled form superscript form subscript form vertical layout presentation form wide (or zenkakucompatibility character narrow (or hankakucompatibility character small variant form (cns compatibilitya cjk squared-font variant vulgar fraction form otherwise unspecified compatibility character digit(unichr[default]returns the integer digit value assigned to the character unichr if unichr is not digitdefault is returned or valueerror is raised this function differs from lib fl ff
18,143
string and text handling decimal(in that it works with characters that may represent digits but that are not decimal digits east_asian_width(unichrreturns the east asian width assigned to unichr lookup(namelooks up character by name for examplelookup('copyright sign'returns the corresponding unicode character common names can be found at mirrored(unichrreturns if unichr is "mirroredcharacter in bidirectional text and returns otherwise mirrored character is one whose appearance might be changed to appear properly if text is rendered in reverse order for examplethe character '(is mirrored because it might make sense to flip it to ')in cases where text is printed from right to left name(unichr [default]returns the name of unicode characterunichr raises valueerror if no name is defined or returns default if provided for examplename( '\xfc'returns 'latin small letter with diaeresisnormalize(formunistrnormalizes the unicode string unistr according to normal form form form is one of 'nfc''nfkc''nfd'or 'nfkdthe normalization of string partly pertains to the composition and decomposition of certain characters for examplethe unicode string for the word "resumecould be represented as 'resum\ or as the string 'resume\ in the first stringthe accented character is represented as single character in the second stringthe accented character is represented by the letter followed by combining accent mark (''nfcnormalization converts the string unistr so that all of the characters are fully composed (for examplee is single character'nfdnormalization converts unistr so that characters are decomposed (for examplee is the letter followed by an accent'nfkcand 'nfkdperform the same function as 'nfcand 'nfdexcept that they additionally transform certain characters that may be represented by more than one unicode character value into single standard value for exampleroman numerals have their own unicode character values but are also just represented by the latin letters ivmand so on 'nfkcand 'nfkdwould convert the special roman numeral characters into their latin equivalents numeric(unichr[default]returns the value assigned to the unicode character unichr as floating-point number if no numeric value is defineddefault is returned or valueerror is raised for examplethe numeric value of + (the character for the fraction " / "is unidata_version string containing the unicode database version used (for example''note for further details about the unicode character databasesee lib fl ff
18,144
python database access his describes the programming interfaces that python uses to interface with relational and hash table style databases unlike other that describe specific library modulesthe material in this partly applies to third-party extensions for exampleif you want python to interface with mysql or oracle databaseyou would first have to download third-party extension module that modulein turnwould then follow the basic conventions described here relational database api specification for accessing relational databasesthe python community has developed standard known as the python database api specification or pep for short (the formal description can be found at database modules ( mysqloracleand so onfollow this specificationbut may add even more features this section covers the essential elements needed to use it for most applications at high levelthe database api defines set of functions and objects for connecting to database serverexecuting sql queriesand obtaining results two primary objects are used for thisa connection object that manages the connection to the database and cursor object that is used to perform queries connections to connect to databaseevery database module provides module-level function connect(parametersthe exact parameters depend on the database but typically include information such as the data source nameuser namepasswordhost nameand database name typically these are provided with keyword arguments dsnuserpasswordhostand databaserespectively soa call to connect(might look like thisconnect(dsn="hostname:dbname",user="michael",password="peekaboo"if successfula connection object is returned an instance of connection has the following methodsc close(closes the connection to the server lib fl ff
18,145
python database access commit(commits all pending transactions to the database if the database supports transactionsthis must be called for any changes to take effect if the underlying database does not support transactionsthis method does nothing rollback(rolls back the database to the start of any pending transactions this method is sometimes used in databases that do not support transactions in order to undo any changes made to the database for exampleif an exception occurred in code that was in the middle of updating databaseyou might use this to undo changes made before the exception cursor(creates new cursor object that uses the connection cursor is an object that you will use to execute sql queries and obtain results this is described in the next section cursors in order to perform any operations on the databaseyou first create connection and then you call cursor(method to create cursor object an instance cur of cursor has number of standard methods and attributes that are used to execute queriescur callproc(procname [parameters]calls stored procedure with name procname parameterswhich is sequence of values that are used as the arguments to the procedure the result of this function is sequence with the same number of items as parameters this sequence is copy of parameters where the values of any output arguments have been replaced with their modified values after execution if procedure also produces an output setit can be read using the fetch*(methods described next cur close(closes the cursorpreventing any further operations on it cur execute(query [parameters]executes query or command query on the database query is string containing the command (usually sql)and parameters is either sequence or mapping that is used to supply values to variables in the query string (this is described in the next sectioncur executemany(query [parametersequence]repeatedly executes query or command query is query stringand parametersquence is sequence of parameters each item in this sequence is sequence or mapping object that you would have used with the execute(method shown earlier cur fetchone(returns the next row of the result set produced by execute(or executemany(the result is typically list or tuple containing values for the different columns of the result none is returned if there are no more rows available an exception is raised if there is no pending result or if the previously executed operation didn' create result set lib fl ff
18,146
cur fetchmany([size]returns sequence of result rows ( list of tuplessize is the number of rows to return if omittedthe value of cur arraysize is used as default the actual number of rows returned may be less than requested an empty sequence is returned if no more rows are available cur fetchall(returns sequence of all remaining result rows ( list of tuplescur nextset(discards all remaining rows in the current result set and skips to the next result set (if anyreturns none if there are no more result setsotherwisea true value is returned and subsequent fetch*(operations return data from the new set cur setinputsize(sizesgives the cursor hint about the parameters to be passed on subsequent execute*(methods sizes is sequence of type objects (described shortlyor integers which give the maximum expected string length for each parameter internallythis is used to predefine memory buffers for creating the queries and commands sent to the database using this can speed up subsequent execute*(operations cur setoutputsize(size [column]sets the buffer size for specific column in result sets column is an integer index into the result rowand size is the number of bytes typical use of this method is to set limits on large database columns such as stringsblobsand longs prior to making any execute*(calls if column is omittedit sets limit for all columns in the result cursors have number of attributes that describe the current result set and give information about the cursor itself cur arraysize an integer that gives the default value used for the fetchmany(operation this value may vary between database modules and may be initially set to value that the module considers to be "optimal cur description sequence of tuples that give information about each column in the current result set each tuple has the form (nametype_codedisplay_sizeinternal_sizeprecisionscalenull_okthe first field is always defined and corresponds to the column name the type_code can be used in comparisons involving the type objects described in the "type objectssection the other fields may be set to none if they don' apply to the column cur rowcount the number of rows in the last result produced by one of the execute*(methods if set to - it means that there is either no result set or that the row count can' be determined although not required by the specificationthe cursor object in most database modules also implements the iteration protocol in this casea statement such as for row in curwill iterate over the rows the result set created by the last execute*(method lib fl ff
18,147
python database access here is simple example showing how some of these operations are used with the sqlite database modulewhich is built-in libraryimport sqlite conn sqlite connect("dbfile"cur conn cursor(example of simple query cur execute("select namesharesprice from portfolio where account= "looping over the results while truerow cur fetchone(if not rowbreak process the row namesharesprice row an alternative approach (using iterationcur execute("select namesharesprice from portfolio where account= "for namesharesprice in curprocess the row forming queries critical part of using the database api involves forming sql query strings to pass into the execute*(methods of cursor objects part of the problem here is that you need to fill in parts of the query string with parameters supplied by the user for exampleyou might be inclined to write code like thissymbol "aigaccount cur execute("select shares from portfolio where name='%sand account=% (symbolaccount)although this "works,you should never manually form queries using python string operations like this if you doit opens up your code to potential sql injection attack-- vulnerability that someone can use to execute arbitrary statements on the database server for examplein the previous codesomeone might supply value for symbol that looks like "evil laugh'drop table portfolio;--which probably does something other than what you anticipated all database modules provide their own mechanism for value substitution for exampleinstead of forming the entire query as shownyou might do this insteadsymbol "aigaccount cur execute("select shares from portfolio where name=and account=?"(symbolaccount)herethe '?placeholders are successively replaced with values from the tuple (symbolaccountsadlythere is no standard convention for placeholders across database module implementations howevereach module defines variable paramstyle that indicates the formatting of value substitutions to be used in queries possible values of this variable are as followsf lib fl ff
18,148
parameter style description 'qmarkquestion mark style where each in the query is replaced by successive items in sequence for examplecur execute(where name=and account=?"(symbolaccount)the parameters are specified as tuple numeric style where : is filled in with the parameter value at index for examplecur execute(where name=: and account=: ",(symbolaccount)named style where :name is filled in with named value for this stylethe parameters must be given as mapping for examplecur execute(where name=:symbol and account=:account"{'symbol':symbol'account'account}printf-style format codes such as % %detc for examplecur execute(where name=% and account=% "(symbolaccount)python extended format codes such as %(name) similar to the 'namedstyle parameters must be specified as mapping instead of tuple 'numeric'named'format'pyformattype objects when working with database databuilt-in types such as integers and strings are usually mapped to an equivalent type in the database howeverfor datesbinary dataand other special typesdata management is more tricky to assist with this mappingdatabase modules implement set of constructor functions for creating objects of various types date(yearmonthdaycreates an object representing date time(hourminutesecondcreates an object representing time timestamp(yearmonthdayhourminutesecondcreates an object representing timestamp datefromticks(tickscreates date object from value of the system time ticks is the number of seconds as returned by function such as time time(timefromticks(tickscreates time object from value of the system time timestampfromticks(tickscreates timestamp object from value of the system time binary(screates binary object from byte-string lib fl ff
18,149
python database access in addition to these constructor functionsthe following type objects might be defined the purpose of these codes is to perform type checking against the type_code field of cur descriptionwhich describes the contents of the current result set type object description string character or text data binary data such as blobs numeric data date and time data row id data binary number datetime rowid error handling database modules define top-level exception error that is base class for all other errors the following exceptions are for more specific kinds of database errorsexception description interfaceerror errors related to the database interfacebut not the database itself errors related to the database itself errors related to the processed data for examplebad type conversionsdivision by zeroetc errors related to the operation of the database itself for examplea lost connection error when relational integrity of the database is broken internal error in the database for exampleif stale cursor errors in sql queries error for methods in the database api that aren' supported by the underlying database databaseerror dataerror operationalerror integrityerror internalerror programmingerror notsupportederror modules may also define warning exception that is used by the database module to warn about things such as data truncation during updates multithreading if you are mixing database access with multithreadingthe underlying database module may or may not be thread-safe the following variable is defined in each module to provide more information threadsafety an integer that indicates the thread safety of the module possible values are no thread safety threads may not share any part of the module the module is thread-safebut connections may not be shared the module and connections are thread-safebut cursors may not be shared the moduleconnectionsand cursors are all thread-safe lib fl ff
18,150
mapping results into dictionaries common issue concerning database results is the mapping of tuples or lists into dictionary of named fields for exampleif the result set of query contains large number of columnsit may be easier to work with this data using descriptive field names instead of hard-coding the numeric index of specific fields within tuple there are many ways to handle thisbut one of the most elegant ways to process result data is through the use of generator functions for exampledef generate_dicts(cur)import itertools fieldnames [ [ lower(for in cur description while truerows cur fetchmany(if not rowreturn for row in rowsyield dict(itertools izip(fieldnames,row)sample use cur execute("select namesharesprice from portfolio"for in generate_dicts(cur)print ['name'], ['shares'], ['price'be aware that the naming of columns is not entirely consistent between databases-especially with respect to things such as case sensitivity soyou'll need to be little careful if you try to apply this technique to code that' meant to work with variety of different database modules database api extensions finallymany extensions and advanced features can be added to specific database modules--for examplesupport for two-phase commits and extended error handling pep- has additional information about the recommended interface for these features and should be consulted by advanced users third-party library modules also may simplify the use of relational database interfaces sqlite module the sqlite module provides python interface to the sqlite database library (attractive for various reasons for oneit does not rely upon separate database server nor does it require any kind of special configuration--you can start to use it right away in your programs by simply connecting to database file (and if it doesn' exista new file is createdthe database also supports transactions for improved reliability (even across system crashesas well as locking to allow the same database file to be simultaneously accessed from multiple processes the programming interface to the library follows the conventions described in the previous section on the database apiso much of that detail is not repeated here insteadthis section focuses on the technical details of using this module as well as features that are specific to the sqlite module lib fl ff
18,151
python database access module-level functions the following functions are defined by the sqlite moduleconnect(database [timeout [isolation_level [detect_types]]]creates connection to sqlite database database is string that specifies the name of the database file it can also be string ":memory:"in which case an in-memory database is used (note that this kind of database only persists as long as the python process remains running and would be lost on program exitthe timeout parameter specifies the amount of time to wait for an internal reader-writer lock to be released when other connections are updating the database by defaulttimeout is seconds when sql statements such as insert or update are useda new transaction is automatically started if one wasn' already in effect the isolation_level parameter is string that provides an optional modifier to the underlying sql begin statement that is used to start this transaction possible values are "(the default)"deferred""exclusive"or "immediatethe meaning of these settings is related to the underlying database lock and is as followsisolation level description "(empty string"deferreduse the default setting (deferredstarts new transactionbut does not acquire the lock until the first database operation is actually performed starts new transaction and guarantees that no other connections can read or write the database until changes are committed starts new transaction and guarantees that no other connection can make database modifications until changes are committed other connections can still read from the databasehowever "exclusive"immediatethe detect_types parameter enables some extra type detection (implemented by extra parsing of sql querieswhen returning results by default it is (meaning no extra detectionit can be set to the bitwise-or of parse_decltypes and parse_colnames if parse_decltypes is enabledqueries are examined for sql typenames such as "integeror "number( )in order to determine the type of result columns if parse_colnames is enabledspecial strings of the form "colname [typename](including the double quotescan be embedded into queries where colname is the column name and typename is the name of type registered with the register_converter(function described next these strings are simply transformed into colname when passed to the sqlite enginebut the extra type specifier is used when converting values in the results of query for examplea query such as 'select price as "price [decimal]from portfoliois interpreted as 'select price as price from portfolio'and the results will be converted according to the "decimalconversion rule register_converter(typenamefuncregisters new type name for use with the detect_types option to connect(typename is string containing the type name as it will be used in queriesand func is function that takes single bytestring as input and returns python datatype as result lib fl ff
18,152
for exampleif you call sqlite register_converter('decimal'decimal decimal)then you can have values in queries converted to decimal objects by writing queries such as 'select price as "price [decimal]from stocksregister_adapter(typefuncregisters an adapter function for python type type that is used when storing values of that type in the datatype func is function that accepts an instance of type type as input and returns intfloatutf- -encoded byte stringunicode stringor buffer as result for exampleif you wanted to store decimal objectsyou might use sqlite register_adapter(decimal decimal,floatcomplete_statement(sreturns true if the string represents one or more complete sql statements separated by semicolons this might be useful if writing an interactive program that reads queries from the user enable_callback_tracebacks(flagdetermines the handling of exceptions in user-defined callback functions such as converters and adapters by defaultexceptions are ignored if flag is set to truetraceback messages will be printed on sys stderr connection objects the connection object returned by the connect(function supports the standard operations described in the database api in additionthe following methods specific to the sqlite module are provided create_function(namenum_paramsfunccreates user-defined function that can be used in sql statements name is string containing the name of the functionnum_params is an integer giving the number of parametersand func is python function that provides the implementation here is simple exampledef toupper( )return upper( create_function("toupper", ,touppersample use in query execute("select toupper(name),foo,bar from sometable"although python function is being definedthe parameters and inputs of this function should only be intfloatstrunicodebufferor none create_aggregate(namenum_paramsaggregate_classcreates user-defined aggregation function for use in sql statements name is string containing the name of the functionand num_params is an integer giving the number of input parameters aggregate_class is class that implements the aggregation operation this class must support initialization with no arguments and implements step(paramsmethod that accepts the same number of parameters as given in num_params and finalize(method that returns the final result here is simple exampleclass averager(object)def _init_ (self)self total self count lib fl ff
18,153
python database access def step(self,value)self total +value self count + def finalize(self)return self total self count create_aggregate("myavg", ,averagersample use in query execute("select myavg(numfrom sometable"aggregation works by making repeated calls to the step(method with input values and then calling finalize(to obtain the final value create_collation(namefuncregisters user-defined collation function for use in sql statements name is string containing the name of the collation functionand func is function that accepts two inputs and returns - depending on whether or not the first input is belowequal toor above the second input you use the user-defined function using sql expression such as "select from table order by colname collate namec execute(sql [params] shortcut method that creates cursor object using cursor(and executes the cursor' execute(method with sql statements in sql with the parameters in params executemany(sql [params] shortcut method that creates cursor object using cursor(and executes the cursor' executemany(method with sql statements in sql with the parameters in params executescript(sqla shortcut method that creates cursor object using cursor(and executes the cursor' executescript(method with sql statements in sql interrupt(aborts any currently executing queries on the connection this is meant to be called from separate thread iterdump(returns an iterator that dumps the entire database contents to series of sql statements that could be executed to recreate the database this could be useful if exporting the database elsewhere or if you need to dump the contents of an in-memory database to file for later restoration set_authorizer(auth_callbackregisters an authorization callback function that gets executed on every access to column of data in the database the callback function must take five arguments as auth_callback(codearg arg dbnameinnernamethe value returned by this callback is one of sqlite_ok if access is allowedsqlite_deny if the sql statement should fail with an erroror sqlite_ignore if the column should be ignored by treating it as null value the first argument code is an integer action code arg and lib fl ff
18,154
arg are parameters whose values depend on the value of code dbname is string containing the name of the database (usually "main")and innername is the name of the innermost view or trigger that is attempting access or none if no view or trigger is active the following table lists the values for code and meaning of the arg and arg parameterscode arg arg sqlite_create_index sqlite_create_table sqlite_create_temp_index sqlite_create_temp_table sqlite_create_temp_trigger sqlite_create_temp_view sqlite_create_trigger sqlite_create_view sqlite_delete sqlite_drop_index sqlite_drop_table sqlite_drop_temp_index sqlite_drop_temp_table sqlite_drop_temp_trigger sqlite_drop_temp_view sqlite_drop_trigger sqlite_drop_view sqlite_insert sqlite_pragma sqlite_read sqlite_select sqlite_transaction sqlite_update sqlite_attach sqlite_detach sqlite_alter_table sqlite_reindex sqlite_analyze sqlite_create_vtable sqlite_drop_vtable sqlite_function index name table name index name table name trigger name view name trigger name view name table name index name table name index name table name trigger name view name trigger name view name table name pragma name table name none none table name filename database name database name index name table name table name table name function name table name none table name none table name none table name none none table name none table name none table name none table name none none none column name none none column name none none table name none none module name module name none set_progress_handler(handlernregisters callback function that gets executed every instructions of the sqlite virtual machine handler is function that takes no arguments lib fl ff
18,155
python database access the following attributes are also defined on connection objects row_factory function that gets called to create the object representing the contents of each result row this function takes two argumentsthe cursor object used to obtain the result and tuple with the raw result row text_factory function that is called to create the objects representing text values in the database the function must take single argument that is utf- -encoded byte string the return value should be some kind of string by defaulta unicode string is returned total_changes an integer representing the number of rows that have been modified since the database connection was opened final feature of connection objects is that they can be used with the contextmanager protocol to automatically handle transactions for exampleconn sqlite connect("somedb"with connconn execute("insert into sometable values (?,?)"("foo","bar"))in this examplea commit(operation is automatically performed after all statements in the with block have executed and no errors have occurred if any kind of exception is raiseda rollback(operation is performed and the exception is reraised cursors and basic operations to perform basic operations on sqlite databaseyou first have to create cursor object using the cursor(method of connection you then use the execute()executemany()or executescript(methods of the cursor to execute sql statements see the database api section for further details about the general operation of these methods instead of repeating that information herea set of common database use cases are presented along with sample code the goal is to show both the operation of cursor objects and some common sql operations for those programmers who might need brief refresher on the syntax creating new database tables the following code shows how to open database and create new tableimport sqlite conn sqlite connect("mydb"cur conn cursor(cur execute("create table stocks (symbol textshares integerprice real)"conn commit(when defining tablesa few primitive sqlite datatypes should be usedtextintegerrealand blob the blob type is bytestringwhereas the text type is assumed to be utf- -encoded unicode lib fl ff
18,156
inserting new values into table the following code shows how to insert new items into tableimport sqlite conn sqlite connect("mydb"cur conn cursor(cur execute("insert into stocks values (?,?,?)",('ibm', , )cur execute("insert into stocks values (?,?,?)",('aapl', , )conn commit(when inserting valuesyou should always use the substitutions as shown each is replaced by value from tuple of values supplied as parameters if you have sequence of data to insertyou can use the executemany(method of cursor like thisstocks ('goog', , )('aa', , )('aig', cur executemany("insert into stocks values (?,?,?)",stocksupdating an existing row the following code shows how you might update columns for an existing rowcur execute("update stocks set shares=where symbol=?",( ,'ibm')againwhen you need to insert values into the sql statementmake sure you use the placeholders and supply tuple of values as parameters deleting rows the following code shows how to delete rowscur execute("delete from stocks where symbol=?",('scox',)performing basic queries the following code shows how you can perform basic queries and obtain the resultsselect all columns from table for row in cur execute("select from stocks")statements select few columns for sharesprice in cur execute("select shares,price from stocks")statements select matching rows for row in cur execute("select from stocks where symbol=?",('ibm',)statements select matching rows with ordering for row in cur execute("select from stocks order by shares")statements select matching rows with ordering in reverse for row in cur execute("select from stocks order by shares desc")statements joining tables on common column name (symbolfor row in cur execute("""select symbols sharesp price from stocks as sprices as using(symbol)""")statements lib fl ff
18,157
python database access dbm-style database modules python includes number of library modules for supporting unix dbm-style database files several standard types of these databases are supported the dbm module is used to read standard unix-dbm database files the gdbm module is used to read gnu dbm database files (to read database files created by the berkeley db library (database/berkeley-db/index htmlthe dumbdbm module is pure-python module that implements simple dbm-style database on its own all of these modules provide an object that implements persistent string-based dictionary that isit works like python dictionary except that all keys and values are restricted to strings database file is typically opened using variation of the open(function open(filename [flag [mode]]this function opens the database file filename and returns database object flag is 'rfor read-only access'wfor read-write access'cto create the database if it doesn' existor 'nto force the creation of new database mode is the integer fileaccess mode used when creating the database (the default is on unixthe object returned by the open(function minimally supports the following dictionary-like operationsoperation description [keyvalue value [keydel [keyd close(key in sync(inserts value into the database gets data from the database removes database entry closes the database tests for key writes all changes out to the database specific implementations may also add additional features (consult the appropriate module reference for detailsone issue with the various dbm-style database modules is that not every module is installed on every platform for exampleif you use python on windowsthe dbm and gdbm modules are typically unavailable howevera program may still want to create dbm-style database for its own use to address this issuepython provides module anydbm that can be used to open and create dbm-style database file this module provides an open(function as described previouslybut it is guaranteed to work on all platforms it does this by looking at the set of available dbm modules and picking the most advanced library that is available (typically dbhash if it' installedas fallbackit uses the dumbdbm module which is always available another module is whichdbwhich has function whichdb(filenamethat can be used to probe file in order to determine what kind of dbm-database created it as general ruleit is probably best not to rely upon these low-level modules for any application where portability is important for exampleif you create dbm database on one machine and then transfer the database file to another machinethere is chance that python won' be able to read it if the underlying dbm module isn' lib fl ff
18,158
installed high degree of caution is also in order if you are using these database modules to store large amounts of datahave situation where multiple python programs might be opening the same database file concurrentlyor need high reliability and transactions (the sqlite module might be safer choice for thatshelve module the shelve module provides support for persistent objects using special "shelf object this object behaves like dictionary except that all the objects it contains are stored on disk using hash-table based database such as dbhashdbm or gdbm unlike those moduleshoweverthe values stored in shelf are not restricted to strings insteadany object that is compatible with the pickle module may be stored shelf is created using the shelve open(function open(filename [,flag=' [protocol [writeback]]]opens shelf file if the file doesn' existit' created filename should be the database filename and should not include suffix flag has the same meaning as described in the introduction and is one of ' '' '' 'or 'nif the database file doesn' existit is created protocol specifies the protocol used to pickle objects stored in the database it has the same meaning as described in the pickle module writeback controls the caching behavior of the database object if trueall accessed entries are cached in memory and only written back when the shelf is closed the default value is false returns shelf object once shelf is openedthe following dictionary operations can be performed on itoperation description [keydata data [keydel [keyd has_key(keyd keys( close( sync(stores data at key overwrites existing data retrieves data at key deletes data at key tests for the existence of key returns all keys closes the shelf writes unsaved data to disk the key values for shelf must be strings the objects stored in shelf must be serializable using the pickle module shelf(dict [protocol [writeback]] mixin class that implements the functionality of shelf on top of dictionary objectdict when this is usedobjects stored in the returned shelf object will be pickled and stored in the underlying dictionary dict both protocol and writeback have the same meaning as for shelve open(the shelve module uses the anydbm module to select an appropriate dbm module for use in most standard python installationsit is likely to be the dbhashwhich relies upon the berkeley db library lib fl ff
18,159
lib fl ff
18,160
file and directory handling his describes python modules for high-level file and directory handling topics include modules for processing various kinds of basic file encodings such as gzip and bzip filesmodules for extracting file archives such as zip and tar filesand modules for manipulating the file system itself ( directory listingsmovingrenamingcopyingand so onlow-level operating system calls related to files are covered in "operating system services modules for parsing the contents of files such as xml and html are mostly covered in "internet data handling and encoding bz the bz module is used to read and write data compressed according to the bzip compression algorithm bz file(filename [mode [buffering [compresslevel]]]opens bz filefilenameand returns file-like object mode is 'rfor reading or 'wfor writing universal newline support is also available by specifying mode of 'rubuffering specifies the buffer size in bytes with default value of (no bufferingcompresslevel is number between and value of (the defaultprovides the highest level of compression but consumes the most processing time the returned object supports all the common file operationsincluding close()read()readline()readlines()seek()tell()write()and writelines(bz compressor([compresslevel]creates compressor object that can be used to sequentially compress sequence of data blocks compresslevel specifies the compression level as number between and (the defaultan instancecof bz compressor has the following two methodsc compress(datafeeds new string data to the compressor objectc returns string of compressed data if possible because compression involves chunks of datathe returned string may not include all the data and may include compressed data from previous calls to compress(the flush(method should be used to return any remaining data stored in the compressor after all input data has been supplied lib fl ff
18,161
file and directory handling flush(flushes the internal buffers and returns string containing the compressed version of all remaining data after this operationno further compress(calls should be made on the object bz decompressor(creates decompressor object an instancedof bz decompressor supports just one methodd decompress(datagiven chunk of compressed data in the string datathis method returns uncompressed data because data is processed in chunksthe returned string may or may not include decompressed version of everything supplied in data repeated calls to this method will continue to decompress data blocks until an end-of-stream marker is found in the input if subsequent attempts are made to decompress data after thatan eoferror exception will be raised compress(data [compresslevel]returns compressed version of the data supplied in the string data compresslevel is number between and (the defaultdecompress(datareturns string containing the decompressed data in the string data filecmp the filecmp module provides the following functionswhich can be used to compare files and directoriescmp(file file [shallow]compares the files file and file and returns true if they're equalfalse if not by defaultfiles that have identical attributes as returned by os stat(are considered to be equal if the shallow parameter is specified and is falsethe contents of the two files are compared to determine equality cmpfiles(dir dir common [shallow]compares the contents of the files contained in the list common in the two directories dir and dir returns tuple containing three lists of filenames (matchmismatcherrorsmatch lists the files that are the same in both directoriesmismatch lists the files that don' matchand errors lists the files that could not be compared for some reason the shallow parameter has the same meaning as for cmp(dircmp(dir dir [ignore[hide]]creates directory comparison object that can be used to perform various comparison operations on the directories dir and dir ignore is list of filenames to ignore and has default value of ['rcs','cvs','tags'hide is list of filenames to hide and defaults to the list [os curdiros pardir([''on unixf lib fl ff
18,162
directory objectdreturned by dircmp(has the following methods and attributesd report(compares directories dir and dir and prints report to sys stdout report_partial_closure(compares dir and dir and common immediate subdirectories results are printed to sys stdout report_full_closure(compares dir and dir and all subdirectories recursively results are printed to sys stdout left_list lists the files and subdirectories in dir the contents are filtered by hide and ignore right_list lists the files and subdirectories in dir the contents are filtered by hide and ignore common lists the files and subdirectories found in both dir and dir left_only lists the files and subdirectories found only in dir right_only lists the files and subdirectories found only in dir common_dirs lists the subdirectories that are common to dir and dir common_files lists the files that are common to dir and dir common_funny lists the files in dir and dir with different types or for which no information can be obtained from os stat( same_files lists the files with identical contents in dir and dir diff_files lists the files with different contents in dir and dir funny_files lists the files that are in both dir and dir but that could not be compared for some reason (for exampleinsufficient permission to accessd subdirs dictionary that maps names in common_dirs to additional dircmp objects lib fl ff
18,163
file and directory handling note the attributes of dircmp object are evaluated lazily and not determined at the time the dircmp object is first created thusif you're interested in only some of the attributesthere' no added performance penalty related to the other unused attributes fnmatch the fnmatch module provides support for matching filenames using unix shell-style wildcard characters this module only performs filename matchingwhereas the glob module can be used to actually obtain file listings the pattern syntax is as followscharacter(sdescription [seq[!seqmatches everything matches any single character matches any character in seq matches any character not in seq the following functions can be used to test for wildcard matchfnmatch(filenamepatternreturns true or false depending on whether filename matches pattern case sensitivity depends on the operating system (and may be non-case-sensitive on certain platforms such as windowsfnmatchcase(filenamepatternperforms case-sensitive comparison of filename against pattern filter(namespatternapplies the fnmatch(function to all of the names in the sequence names and returns list of all names that match pattern examples fnmatch('foo gif''gif'returns true fnmatch('part html''part [ - html'returns false example of finding files in an entire directory tree using os walk()fnmatchand generators def findall(topdirpattern)for pathfilesdirs in os walk(topdir)for name in filesif fnmatch fnmatch(name,pattern)yield os path join(path,namefind all py files for pyfile in findall(","py")print pyfile lib fl ff
18,164
glob the glob module returns all filenames in directory that match pattern specified using the rules of the unix shell (as described in the fnmatch moduleglob(patternreturns list of pathnames that match pattern iglob(patternreturns the same results as glob(but using an iterator example htmlfile glob('html'imgfiles glob('image[ - ]gif'note tilde (~and shell variable expansion are not performed use os path expanduser(and os path expandvars()respectivelyto perform these expansions prior to calling glob(gzip the gzip module provides classgzipfilethat can be used to read and write files compatible with the gnu gzip program gzipfile objects work like ordinary files except that data is automatically compressed or decompressed gzipfile([filename [mode [compresslevel [fileobj]]]]opens gzipfile filename is the name of fileand mode is one of ' ''rb'' ''ab'' 'or 'wbthe default is 'rbcompresslevel is an integer from to that controls the level of compression is the fastest and produces the least compression is the slowest and produces the most compression (the defaultfileobj is an existing file object that should be used if suppliedit' used instead of the file named by filename open(filename [mode [compresslevel]]same as gzipfile(filenamemodecompresslevelthe default mode is 'rbthe default compresslevel is notes calling the close(method of gzipfile object doesn' close files passed in fileobj this allows additional information to be written to file after the compressed data files produced by the unix compress program are not supported this module requires the zlib module lib fl ff
18,165
file and directory handling shutil the shutil module is used to perform high-level file operations such as copyingremovingand renaming the functions in this module should only be used for proper files and directories in particularthey do not work for special kinds of files on the file system such as named pipesblock devicesetc alsobe aware that these functions don' always correctly deal with advanced kinds of file metadata ( resource forkscreator codesetc copy(src,dstcopies the file src to the file or directory dstretaining file permissions src and dst are strings copy (srcdstlike copy(but also copies the last access and modification times copyfile(srcdstcopies the contents of src to dst src and dst are strings copyfileobj( [length]copies all data from open file object to open file object length specifies maximum buffer size to use negative length will attempt to copy the data entirely with one operation (that isall data will be read as single chunk and then writtencopymode(srcdstcopies the permission bits from src to dst copystat(srcdstcopies the permission bitslast access timeand last modification time from src to dst the contentsownerand group of dst are unchanged copytree(srcdstsymlinks [,ignore]]recursively copies an entire directory tree rooted at src the destination directory dst will be created (and should not already existindividual files are copied using copy (if symlinks is truesymbolic links in the source tree are represented as symbolic links in the new tree if symlinks is false or omittedthe contents of linked files are copied to the new directory tree ignore is an optional function that can be used to filter out specific files as inputthis function should accept directory name and list of directory contents as return valueit should return list of filenames to be ignored if errors occur during the copy processthey are collected and the error exception is raised at the end of processing the exception argument is list of tuples containing (srcnamedstnameexceptionfor all errors that occurred ignore_pattern(pattern pattern creates function that can be used for ignoring all of the glob-style patterns given in pattern pattern etc the returned function accepts as input two argumentsthe first of which is directory name and the second of which is list of directory contents as resulta list of filenames to be ignored is returned the primary use of the returned function is as the ignore parameter to the copytree(function shown earlier howeverthe resulting function might also be used for operations involving the os walk(function lib fl ff
18,166
move(srcdstmoves file or directory src to dst will recursively copy src if it is being moved to different file system rmtree(path [ignore_errors [onerror]]deletes an entire directory tree if ignore_errors is trueerrors will be ignored otherwiseerrors are handled by the onerror function (if suppliedthis function must accept three parameters (funcpathand excinfo)where func is the function that caused the error (os remove(or os rmdir())path is the pathname passed to the functionand excinfo is the exception information returned by sys exc_info(if an error occurs and onerror is omittedan exception is raised tarfile the tarfile module is used to manipulate tar archive files using this moduleit is possible to read and write tar fileswith or without compression is_tarfile(namereturns true if name appears to be valid tar file that can be read by this module open([name [mode [fileobj [bufsize]]]]creates new tarfile object with the pathname name mode is string that specifies how the tar file is to be opened the mode string is combination of file mode and compression scheme specified as 'filemode[:compression]valid combinations include the followingmode description 'ropen for reading if the file is compressedit is decompressed transparently this is the default mode open for reading without compression open for reading with gzip compression open for reading with bzip compression open for appending with no compression open for writing with no compression open for writing with gzip compression open for writing with bzip compression ' :' :gz' :bz ' '' :' '' :' :gz' :bz the following modes are used when creating tarfile object that only allows sequential / access (no random seeks)mode description ' |' |gz' |bz ' |' |gz' |bz open stream of uncompressed blocks for reading open gzip compressed stream for reading open bzip compressed stream for reading open an uncompressed stream for writing open gzip compressed stream for writing open bzip compressed stream for writing lib fl ff
18,167
file and directory handling if the parameter fileobj is specifiedit must be an open file object in this casethe file overrides any filename specified with name bufsize specifies the block size used in tar file the default is * bytes tarfile instancetreturned by open(supports the following methods and attributest add(name [arcname [recursive]]adds new file to the tar archive name is the name of any kind of file (directorysymbolic linkand so onarcname specifies an alternative name to use for the file inside the archive recursive is boolean flag that indicates whether or not to recursively add the contents of directories by defaultit is set to true addfile(tarinfo [fileobj]adds new object to the tar archive tarinfo is tarinfo structure that contains information about the archive member fileobj is an open file object from which data will be read and saved in the archive the amount of data to read is determined by the size attribute of tarinfo close(closes the tar archivewriting two zero blocks to the end if the archive was opened for writing debug controls the amount of debugging information producedwith producing no output and producing all debugging messages messages are written to sys stderr dereference if this attribute is set to truesymbolic and hard links are dereferenced and the entire contents of the referenced file are added to the archive if it' set to falsejust the link is added errorlevel determines how errors are handled when an archive member is being extracted if this attribute is set to errors are ignored if it' set to errors result in oserror or ioerror exceptions if it' set to nonfatal errors additionally result in tarerror exceptions extract(member [path]extracts member from the archivesaving it to the current directory member is either an archive member name or tarinfo instance path is used to specify different destination directory extractfile(memberextracts member from the archivereturning read-only file-like object that can be used to read its contents using read()readline()readlines()seek()and tell(operations member is either an archive member name or tarinfo object if member refers to linkan attempt will be made to open the target of the link getmember(namelooks up archive member name and returns tarinfo object containing information about it raises keyerror if no such archive member exists if member name appears lib fl ff
18,168
more than once in the archiveinformation for the last entry is returned (which is assumed to be the more recentt getmembers(returns list of tarinfo objects for all members of the archive getnames(returns list of all archive member names gettarinfo([name [arcname [fileobj]]]returns tarinfo object corresponding to filenameon the file system or an open file objectfileobj arcname is an alternative name for the object in the archive the primary use of this function is to create an appropriate tarinfo object for use in methods such as add( ignore_zeros if this attribute is set to trueempty blocks are skipped when reading an archive if it' set to false (the default)an empty block signals the end of the archive setting this method to true may be useful for reading damaged archive list([verbose]lists the contents of the archive to sys stdout verbose determines the level of detail if this method is set to falseonly the archive names are printed otherwisefull details are printed (the defaultt next( method used for iterating over the members of an archive returns the tarinfo structure for the next archive member or none posix if this attribute is set to truethe tar file is created according to the posix standard this places restrictions on filename lengths and file size (filenames must be less than characters and files must be less than gb in sizeif this attribute is set to falsethe archive is created using gnu extensions that lift these restrictions the default value is false many of the previous methods manipulate tarinfo instances the following table shows the methods and attributes of tarinfo instance ti attribute description ti gid ti gname ti isblk(ti ischr(ti isdev(ti isdir(ti isfifo(ti isfile(ti islnk(ti isreg(group id group name returns true if the object is block device returns true if the object is character device returns true if the object is device (characterblockor fiforeturns true if the object is directory returns true if the object is fifo returns true if the object is regular file returns true if the object is hard link same as isfile( lib fl ff
18,169
file and directory handling attribute description ti issym(ti linkname ti mode ti mtime ti name ti size ti type returns true if the object is symbolic link target filename of hard or symbolic link permission bits last modification time archive member name size in bytes file type that is one of the constants regtypearegtypelnktypesymtypedirtypefifotypeconttypechrtypeblktypeor gnutype_sparse user id username ti uid ti uname exceptions the following exceptions are defined by the tarfile moduletarerror base class for all other exceptions readerror raised when an error occurs while opening tar file (for examplewhen opening an invalid filecompressionerror raised when data can' be decompressed streamerror raised when an unsupported operation is performed on stream-like tarfile object (for instancean operation that requires random accessextracterror raised for nonfatal errors during extraction (only if errorlevel is set to example open tar file and put some files into it tarfile open("foo tar"," " add("readme"import glob for pyfile in glob glob("py") add(pyfilet close(open tar file and iterate over all of its members tarfile open("foo tar"for in tprint("% % ( namef size)scan tar file and print the contents of "readmefiles tarfile open("foo tar" lib fl ff
18,170
for in tif os path basename( name="readme"data extractfile(fread(print("***% **** nametempfile the tempfile module is used to generate temporary filenames and files mkdtemp([suffix [,prefix [dir]]]creates temporary directory accessible only by the owner of the calling process and returns its absolute pathname suffix is an optional suffix that will be appended to the directory nameprefix is an optional prefix that will be inserted at the beginning of the directory nameand dir is directory where the temporary directory should be created mkstemp([suffix [,prefix [dir [,text]]]]creates temporary file and returns tuple (fdpathname)where fd is an integer file descriptor returned by os open(and pathname is absolute pathname of the file suffix is an optional suffix appended to the filenameprefix is an optional prefix inserted at the beginning of the filenamedir is the directory in which the file should be createdand text is boolean flag that indicates whether to open the file in text mode or binary mode (the defaultthe creation of the file is guaranteed to be atomic (and secureprovided that the system supports the o_excl flag for os open(mktemp([suffix [prefix [,dir]]]returns unique temporary filename suffix is an optional file suffix to append to the filenameprefix is an optional prefix inserted at the beginning of the filenameand dir is the directory in which the file is created this function only generates unique filename and doesn' actually create or open temporary file because this function generates name before the file is actually openedit introduces potential security problem to address thisconsider using mkstemp(instead gettempdir(returns the directory in which temporary files are created gettempprefix(returns the prefix used to generate temporary files does not include the directory in which the file would reside temporaryfile([mode [bufsize [suffix [,prefix [dir]]]]]creates temporary file using mkstemp(and returns file-like object that supports the same methods as an ordinary file object mode is the file mode and defaults to ' +bbufsize specifies the buffering behavior and has the same meaning as for the open(function suffixprefixand dir have the same meaning as for mkstemp(the object returned by this function is only wrapper around built-in file object that' accessible in the file attribute the file created by this function is automatically destroyed when the temporary file object is destroyed lib fl ff
18,171
file and directory handling namedtemporaryfile([mode [bufsize [suffix [,prefix [dir [delete ]]]]]]creates temporary file just like temporaryfile(but makes sure the filename is visible on the file system the filename can be obtained by accessing the name attribute of the returned file object note that certain systems may prevent the file from being reopened using this name until the temporary file has been closed the delete parameterif set to true (the default)forces the temporary file to be deleted as soon as it is closed spooledtemporaryfile([max_size [mode [bufsize [suffix [prefix [dir]]]]]]creates temporary file such as temporaryfile except that the file contents are entirely held in memory until they exceed the size given in max_size this internal spooling is implemented by first holding the file contents in stringio object until it is necessary to actually go to the file system if any kind of low-level file / operation is performed involving the fileno(methodthe memory contents are immediately written to proper temporary file as defined by the temporaryfile object the file object returned by spooledtemporaryfile also has method rollover(that can be used to force the contents to be written to the file system two global variables are used to construct temporary names they can be assigned to new values if desired their default values are system-dependent variable description tempdir template the directory in which filenames returned by mktemp(reside the prefix of filenames generated by mktemp( string of decimal digits is added to template to generate unique filenames note by defaultthe tempfile module creates files by checking few standard locations for exampleon unixfiles are created in one of /tmp/var/tmpor /usr/tmp on windowsfiles are created in one of :\tempc:\tmp\tempor \tmp these directories can be overridden by setting one or more of the tmpdirtempand tmp environment variables iffor whatever reasontemporary files can' be created in any of the usual locationsthey will be created in the current working directory zipfile the zipfile module is used to manipulate files encoded in the popular zip format (originally known as pkzipalthough now supported by wide variety of programszip files are widely used by pythonmainly for the purpose of packaging for exampleif zip files containing python source code are added to sys paththen files contained within the zip file can be loaded via import (the zipimport library module implements this functionalityalthough it' never necessary to use that library directlypackages distributed as egg files (created by the setuptools extensionare also just zip files in disguise (an egg file is actually just zip file with some extra metadata added to itf lib fl ff
18,172
the following functions and classes are defined by the zipfile moduleis_zipfile(filenametests filename to see if it' valid zip file returns true if filename is zip filereturns false otherwise zipfile(filename [mode [compression [,allowzip ]]]opens zip filefilenameand returns zipfile instance mode is 'rto read from an existing file'wto truncate the file and write new fileor 'ato append to an existing file for 'amodeif filename is an existing zip filenew files are added to it if filename is not zip filethe archive is simply appended to the end of the file compression is the zip compression method used when writing to the archive and is either zip_stored or zip_deflated the default is zip_stored the allowzip argument enables the use of zip extensionswhich can be used to create zip files that exceed gb in size by defaultthis is set to false pyzipfile(filename [mode[compression [,allowzip ]]]opens zip file like zipfile(but returns special pyzipfile instance with one extra methodwritepy()used to add python source files to the archive zipinfo([filename [date_time]]manually creates new zipinfo instanceused to contain information about an archive member normallyit' not necessary to call this function except when using the writestr(method of zipfile instance (described laterthe filename and date_time arguments supply values for the filename and date_time attributes described below an instancezof zipfile or pyzipfile supports the following methods and attributesz close(closes the archive file this must be called in order to flush records to the zip file before program termination debug debugging level in the range of (no outputto (most outputz extract(name [path [pwd ]]extracts file from the archive and places it in the current working directory name is either string that fully specifies the archive member or zipinfo instance path specifies different directory in which the file will extractedand pwd is the password to use for encrypted archives extractall([path [members [pwd]]]extracts all members of an archive into the current working directory path specifies different directoryand pwd is password for encrypted archives members is list of members to extractwhich must be proper subset of the list returned by the namelist(method (described nextf lib fl ff
18,173
file and directory handling getinfo(namereturns information about the archive member name as zipinfo instance (described shortlyz infolist(returns list of zipinfo objects for all the members of the archive namelist(returns list of the archive member names open(name [mode [pwd]]opens an archive member named name and returns file-like object for reading the contents name can either be string or zipinfo instance describing one of the archive members mode is the file mode and must be one of the read-only file modes such as ' ''ru'or 'upwd is the password to use for encrypted archive members the file object that is returned supports the read()readline()and readlines(methods as well as iteration with the for statement printdir(prints the archive directory to sys stdout read(name [,pwd]reads archive contents for member name and returns the data as string name is either string or zipinfo instance describing the archive member pwd is the password to use for encrypted archive members setpassword(pwdsets the default password used to extract encrypted files from the archive testzip(reads all the files in the archive and verifies their crc checksums returns the name of the first corrupted file or none if all files are intact write(filename[arcname[compress_type]]writes filename to the archive with the archive name arcname compress_type is the compression parameter and is either zip_stored or zip_deflated by defaultthe compression parameter given to the zipfile(or pyzipfile(function is used the archive must be opened in 'wor 'amode for writes to work writepy(pathnamethis methodavailable only with pyzipfile instancesis used to write python source files (py filesto zip archive and can be used to easily package python applications for distribution if pathname is fileit must end with py in this caseone of the corresponding pyopycor py files will be added (in that orderif pathname is directory and the directory is not python package directoryall the corresponding pyopycor py files are added at the top level if the directory is packagethe files are added under the package name as file path if any subdirectories are also package directoriesthey are added recursively lib fl ff
18,174
writestr(arcinfoswrites the string into the zip file arcinfo is either filename within the archive in which the data will be stored or zipinfo instance containing filenamedateand time zipinfo instances returned by the zipinfo() getinfo()and infolist(functions have the following attributesattribute description filename date_time archive member name tuple (year,month,day,hours,minutes,secondscontaining the last modification time month and day are numbers in the range - and - respectively all other values start at compression type for the archive member only zip_stored and zip_deflated are currently supported by this module archive member comment expansion field dataused to contain additional file attributes the data stored here depends on the system that created the file integer code describing the system that created the archive common values are (ms-dos fat) (unix) (macintosh)and (windows ntfspkzip version code that created the zip archive minimum version needed to extract the archive reserved field currently set to zip flag bits that describe the data encoding including encryption and compression volume number of the file header describes the internal structure of the archive contents if the low-order bit is the data is ascii text otherwisebinary data is assumed external file attributes which are operating system dependent byte offset to the file header byte offset to the start of the file data crc checksum of the uncompressed file size of the compressed file data size of the uncompressed file compress_type comment extra create_system create_version extract_version reserved flag_bits volume internal_attr external_attr header_offset file_offset crc compress_size file_size note detailed documentation about the internal structure of zip files can be found as pkzip application note at lib fl ff
18,175
file and directory handling zlib the zlib module supports data compression by providing access to the zlib library adler (string [value]computes the adler- checksum of string value is used as the starting value (which can be used to compute checksum over the concatenation of several stringsotherwisea fixed default value is used compress(string [level]compresses the data in stringwhere level is an integer from to controlling the level of compression is the least (fastestcompressionand is the best (slowestcompression the default value is returns string containing the compressed data or raises error if an error occurs compressobj([level]returns compression object level has the same meaning as in the compress(function crc (string [value]computes crc checksum of string if value is presentit' used as the starting value of the checksum otherwisea fixed value is used decompress(string [wbits [buffsize]]decompresses the data in string wbits controls the size of the window bufferand buffsize is the initial size of the output buffer raises error if an error occurs decompressobj([wbits]returns compression object the wbits parameter controls the size of the window buffer compression objectchas the following methodsc compress(stringcompresses string returns string containing compressed data for at least part of the data in string this data should be concatenated to the output produced by earlier calls to compress(to create the output stream some input data may be stored in internal buffers for later processing flush([mode]compresses all pending input and returns string containing the remaining compressed output mode is z_sync_flushz_full_flushor z_finish (the defaultz_sync_flush and z_full_flush allow further compression and are used to allow partial error recovery on decompression z_finish terminates the compression stream decompression objectdhas the following methods and attributesd decompress(string [,max_length]decompresses string and returns string containing uncompressed data for at least part of the data in string this data should be concatenated with data produced by earlier calls to decompress(to form the output stream some input data may be lib fl ff
18,176
stored in internal buffers for later processing max_length specifies the maximum size of returned data if exceededunprocessed data will be placed in the unconsumed_tail attribute flush(all pending input is processedand string containing the remaining uncompressed output is returned the decompression object cannot be used again after this call unconsumed_tail string containing data not yet processed by the last decompress(call this would contain data if decompression needs to be performed in stages due to buffer size limitations in this casethis variable would be passed to subsequent decompress(calls unused_data string containing extra bytes that remain past the end of the compressed data note the zlib library is available at lib fl ff
18,177
lib fl ff
18,178
operating system services he modules in this provide access to wide variety of operating system services with an emphasis on low-level /oprocess managementand the operating environment modules that are commonly used in conjunction with writing systems programs are also included--for examplemodules to read configuration fileswrite log filesand so forth "file and directory handling,covers high-level modules related to file and filesystem manipulation--the material presented here tends be at lower level than that most of python' operating system modules are based on posix interfaces posix is standard that defines core set of operating system interfaces most unix systems support posixand other platforms such as windows support large portions of the interface throughout this functions and modules that only apply to specific platform are noted as such unix systems include both linux and mac os windows systems include all versions of windows unless otherwise noted readers may want to supplement the material presented here with additional references the programming languagesecond edition by brian kernighan and dennis ritchie (prentice hall provides good overview of filesfile descriptorsand the low-level interfaces on which many of the modules in this section are based more advanced readers may want to consult book such as advanced programming in the unix environment nd edition by richard stevens and stephen rago (addison wesley for an overview of general conceptsyou may want to locate college textbook on operating systems howevergiven the high cost and limited day-to-day practical utility of these booksyou're probably better off asking nearby computer science student to loan you their copy for weekend commands the commands module is used to execute simple system commands specified as string and return their output as string it only works on unix systems the functionality provided by this module is somewhat similar to using backquotes (`in unix shell script for exampletyping commands getoutput('ls - 'is similar to saying =`ls -lgetoutput(cmdexecutes cmd in shell and returns string containing both the standard output and standard error streams of the command lib fl ff
18,179
getstatusoutput(cmdlike getoutput()except that -tuple (statusoutputis returnedwhere status is the exit codeas returned by the os wait(functionand output is the string returned by getoutput(notes this module is only available in python in python both of the previous functions are found in the subprocess module although this module can be used for simple shell operationsyou are almost always better off using the subprocess module for launching subprocesses and collecting their output see alsosubprocess ( configparserconfigparser the configparser module (called configparser in python is used to read ini format configuration files based on the windows ini format these files consist of named sectionseach with its own variable assignments such as the followinga comment comment [section name value name value [section alternative syntax for assigning values name value name value the configparser class the following class is used to manage configuration variablesconfigparser([defaults [dict_type]]creates new configparser instance defaults is an optional dictionary of values that can be referenced in configuration variables by including string format specifiers such as '%(key)swhere key is key of defaults dict_type specifies the type of dictionary that is used internally for storing configuration variables by defaultit is dict (the built-in dictionaryan instance of configparser has the following operationsc add_section(sectionadds new section to the stored configuration parameters section is string with the section name lib fl ff
18,180
defaults(returns the dictionary of default values get(sectionoption [raw [vars]]returns the value of option option from section section as string by defaultthe returned string is processed through an interpolation step where format strings such as '%(option)sare expanded in this caseoption may the name of another configuration option in the same section or one of the default values supplied in the defaults parameter to configparser raw is boolean flag that disables this interpolation featurereturning the option unmodified vars is an optional dictionary containing more values for use in '%expansions getboolean(sectionoptionreturns the value of option from section section converted to boolean value values such as " ""true""yes""no""on"and "offare all understood and checked in case-insensitive manner variable interpolation is always performed by this method (see get() getfloat(sectionoptionreturns the value of option from section section converted to float with variable interpolation getint(sectionoptionreturns the value of option from section section converted to an integer with variable interpolation has_option(sectionoptionreturns true if section section has an option named option has_section(sectionreturns true if there is section named section items(section [raw [vars]]returns list of (optionvaluepairs from section section raw is boolean flag that disables the interpolation feature if set to true vars is dictionary of additional values that can be used in '%expansions options(sectionreturns list of all options in section section optionxform(optiontransforms the option name option to the string that' used to refer to the option by defaultthis is lowercase conversion read(filenamesreads configuration options from list of filenames and stores them filenames is either single stringin which case that is the filename that is reador list of filenames if any of the given filenames can' be foundthey are ignored this is useful if you want to read configuration files from many possible locationsbut where such files may or may not be defined list of the successfully parsed filenames is returned lib fl ff
18,181
operating system services readfp(fp [filename]reads configuration options from file-like object that has already been opened in fp filename specifies the filename associated with fp (if anyby defaultthe filename is taken from fp name or is set to 'if no such attribute is defined remove_option(sectionoptionremoves option from section section remove_section(sectionremoves section section sections(returns list of all section names set(sectionoptionvaluesets configuration option option to value in section section value should be string write(filewrites all of the currently held configuration data to file file is file-like object that has already been opened example the configparser module is often overlookedbut it is an extremely useful tool for controlling programs that have an extremely complicated user configuration or runtime environment for exampleif you're writing component that has to run inside of large frameworka configuration file is often an elegant way to supply runtime parameters similarlya configuration file may be more elegant approach than having program read large numbers of command-line options using the optparse module there are also subtlebut importantdifferences between using configuration files and simply reading configuration data from python source script the following few examples illustrate some of the more interesting features of the configparser module firstconsider sample ini fileappconfig ini configuration file for my mondo application [outputlogfile=%(logdir) /app log logging=on logdir=%(basedir) /logs [inputinfile=%(indir) /initial dat indir=%(basedir) /input lib fl ff
18,182
the following code illustrates how you read configuration file and supply default values to some of the variablesfrom configparser import configparser use from configparser in python dictionary of default variable settings defaults 'basedir'/users/beazley/appcreate configparser object and read the ini file cfg configparser(defaultscfg read('appconfig ini'after you have read configuration fileyou use the get(method to retrieve option values for examplecfg get('output','logfile''/users/beazley/app/logs/app logcfg get('input','infile''/users/beazley/app/input/initial datcfg getboolean('output','logging'true hereyou immediately see some interesting features firstconfiguration parameters are case insensitive thusif your program is reading parameter 'logfile'it does not matter if the configuration file uses 'logfile''logfile'or 'logfilesecondconfiguration parameters can include variable substitutions such as '%(basedir)sand '%(logdir)sas seen in the file these substitutions are also case insensitive moreoverthe definition order of configuration parameters does not matter in these substitutions for examplein appconfig inithe logfile parameter makes reference to the logdir parameterwhich is defined later in the file finallyvalues in configuration files are often interpreted correctly even if they don' exactly match python syntax or datatypes for examplethe 'onvalue of the logging parameter is interpreted as true by the cfg getboolean(method configuration files also have the ability to be merged together for examplesuppose the user had their own configuration file with custom settingsuserconfig ini per-user settings [outputlogging=off [inputbasedir=/tmp you can merge the contents of this file in with already loaded configuration parameters for examplecfg read('userconfig ini'['userconfig ini'cfg get('output','logfile''/users/beazley/app/logs/app logcfg get('output','logging''offcfg get('input','infile''/tmp/input/initial datf lib fl ff
18,183
operating system services hereyou will notice that the newly loaded configuration selectively replaces the parameters that were already defined moreoverif you change one of the configuration parameters that' used in variable substitutions of other configuration parametersthe changes correctly propagate for examplethe new setting of basedir in the input section affects previously defined configuration parameters in that section such as infile this behavior is an important but subtle difference between using config file and simply defining set of program parameters in python script notes two other classes can be used in place of configparser the class rawconfigparser provides all of the functionality of configparser but doesn' perform any variable interpolation the safeconfigparser class provides the same functionality as configparserbut it addresses some subtle problems that arise if configuration values themselves literally include special formatting characters used by the interpolation feature ( '%'datetime the datetime module provides variety of classes for representing and manipulating dates and times large parts of this module are simply related to different ways of creating and outputting date and time information other major features include mathematical operations such as comparisons and calculations of time deltas date manipulation is complex subjectand readers would be strongly advised to consult python' online documentation for an introductory background concerning the design of this module date objects date object represents simple date consisting of yearmonthand day the following four functions are used to create datesdate(yearmonthdaycreates new date object year is an integer in the range datetime minyear to datetime maxyear month is an integer in the range to and day is an integer in the range to the number of days in the given month the returned date object is immutable and has the attributes yearmonthand day corresponding to the values of the supplied arguments date today( class method that returns date object corresponding to the current date date fromtimestamp(timestampa class method that returns date object corresponding to the timestamp timestamp timestamp is value returned by the time time(function date fromordinal(ordinala class method that returns date object corresponding to an ordinal number of days from the minimum allowable date (january of year has ordinal value and january has ordinal value lib fl ff
18,184
the following class attributes describe the maximum rate and resolution of date instances date min class attribute representing the earliest date that can be represented (datetime date( , , )date max class attribute representing the latest possible date (datetime date( , , )date resolution smallest resolvable difference between non-equal date objects (datetime timedelta( )an instancedof date has read-only attributes yeard monthand day and additionally provides the following methodsd ctime(returns string representing the date in the same format as normally used by the time ctime(function isocalendar(returns the date as tuple (iso_yeariso_weekiso_weekday)where iso_week is in the range to and iso_weekday is the range (mondayto (sundaythe first iso_week is the first week of the year that contains thursday the range of values for the three tuple components are determined by the iso standard isoformat(returns an iso -formatted string of the form 'yyyy-mm-ddrepresenting the date isoweekday(returns the day of the week in the range (mondayto (sundayd replace([year [month [day ]]]returns new date object with one or more of the supplied components replaced by new value for exampled replace(month= returns new date where the month has been replaced by strftime(formatreturns string representing the date formatted according to the same rules as the time strftime(function this function only works for dates later than the year moreoverformat codes for components missing from date objects (such as hoursminutesand so onshould not be used timetuple(returns time struct_time object suitable for use by functions in the time module values related to the time of day (hoursminutessecondswill be set to toordinal(converts to an ordinal value january of year has ordinal value lib fl ff
18,185
operating system services weekday(returns the day of the week in the range (mondayto (sundaytime objects time objects are used to represent time in hoursminutessecondsand microseconds times are created using the following class constructortime(hour [minute [second [microsecond [tzinfo]]]]creates time object representing time where <hour <minute <second and <microsecond tzinfo provides time zone information and is an instance of the tzinfo class described later in this section the returned time object has the attributes hourminutesecondmicrosecondand tzinfowhich hold the corresponding values supplied as arguments the following class attributes of time describe the range of allowed values and resolution of time instancestime min class attribute representing the minimum representable time (datetime time( , )time max class attribute representing the maximum representable time (datetime time( , )time resolution smallest resolvable difference between non-equal time objects (datetime timedelta( , , )an instancetof time object has attributes hourt minutet secondt microsecondand tzinfo in addition to the following methodst dst(returns the value of tzinfo dst(nonethe returned object is timedelta object if no time zone is setnone is returned isoformat(returns string representing the time as 'hh:mm:ss mmmmmmif the microseconds are that part of the string is omitted if time zone information has been suppliedthe time may have an offset added to it (for example'hh:mm:ss mmmmmm+hh:mm' replace([hour [minute [second [microsecond [tzinfo ]]]]]returns new time objectwhere one or more components have been replaced by the supplied values for examplet replace(second= changes the seconds field to and returns new time object the arguments have the same meaning as those supplied to the time(function shown earlier strftime(formatreturns string formatted according to the same rules as the time strftime(function in the time module because date information is unavailableonly the formatting codes for time-related information should be used lib fl ff
18,186
tzname(returns the value of tzinfo tzname(if no time zone is setnone is returned utcoffset(returns the value of tzinfo utcoffset(nonethe returned object is timedelta object if no time zone has been setnone is returned datetime objects datetime objects are used to represent dates and times together there are many possible ways to create datetime instancedatetime(yearmonthday [hour [minute [second [microsecond [tzinfo]]]]]creates new datetime object that combines all the features of date and time objects the arguments have the same meaning as arguments provided to date(and time(datetime combine(date,timea class method that creates datetime object by combining the contents of date objectdateand time objecttime datetime fromordinal(ordinala class method that creates datetime object given an ordinal day (integer number of days since datetime minthe time components are all set to and tzinfo is set to none datetime fromtimestamp(timestamp [tz] class method that creates datetime object from timestamp returned by the time time(function tz provides optional time zone information and is tzinfo instance datetime now([tz] class method that creates datetime object from the current local date and time tz provides optional time zone information and is an instance of tzinfo datetime strptime(datestringformata class method that creates datetime object by parsing the date string in datestring according to the date format in format the parsing is performed using the strptime(function in the time module datetime utcfromtimestamp(timestampa class method that creates datetime object from timestamp typically returned by time gmtime(datetime utcnow( class method that creates datetime object from the current utc date and time lib fl ff
18,187
operating system services the following class attributes describe the range of allowed dates and resolutiondatetime min earliest representable date and time (datetime datetime( , , , , )datetime max latest representable date and time (datetime datetime( , , , , , , )datetime resolution smallest resolvable difference between non-equal datetime objects (datetime timedelta( , , )an instancedof datetime object has the same methods as date and time objects combined in additionalthe following methods are availabled astimezone(tzreturns new datetime object but in different time zonetz the members of the new object will be adjusted to represent the same utc time but in the time zone tz date(returns date object with the same date replace([year [month [day [hour [minute [second [microsecond [tzinfo]]]]]]]returns new datetime object with one or more of the listed parameters replaced by new values use keyword arguments to replace an individual value time(returns time object with the same time the resulting time object has no time zone information set timetz(returns time object with the same time and time zone information utctimetuple(returns time struct_time object containing date and time information normalized to utc time timedelta objects timedelta objects represent the difference between two dates or times these objects are normally created as the result of computing difference between two datetime instances using the operator howeverthey can be manually constructed using the following classtimedelta([days [seconds [microseconds [milliseconds [minutes [hours [weeks ]]]]]]]creates timedelta object that represents the difference between two dates and times the only significant parameters are dayssecondsand microsecondswhich are used internally to represent difference the other parametersif suppliedare converted into dayssecondsand microseconds the attributes dayssecondsand microseconds of the returned timedelta object contain these values lib fl ff
18,188
the following class attributes describe the maximum range and resolution of timedelta instancestimedelta min the most negative timedelta object that can be represented (timedelta(- )timedelta max the most positive timedelta object that can be represented (timedelta(days= hours= minutes= seconds= microseconds= )timedelta resolution timedelta object representing the smallest resolvable difference between non-equal timedelta objects (timedelta(microseconds= )mathematical operations involving dates significant feature of the datetime module is that it supports mathematical operations involving dates both date and datetime objects support the following operationsoperation description td date date date date td date date td date date date <date date =date date !date date date date >date returns timedelta object adds timedelta to date subtracts timedelta from date date comparison when comparing datesyou must use care when time zone information has been supplied if date includes tzinfo informationthat date can only be compared with other dates that include tzinfootherwisea typeerror is generated when two dates in different time zones are comparedthey are first adjusted to utc before being compared timedelta objects also support variety of mathematical operationsoperation description td td td adds two time deltas subtracts two time deltas multiplication by an integer td td td td td td td td td / td -td td +td abs(tdfloor division by an integeri unary subtractionaddition absolute value lib fl ff
18,189
operating system services operation description td td td <td td =td td !td td td td >td comparison here are some examplestoday datetime datetime now(today ctime('thu oct : : oneday datetime timedelta(days= tomorrow today oneday tomorrow ctime('fri oct : : in addition to these operationsall datedatetimetimeand timedelta objects are immutable this means that they can be used as dictionary keysplaced in setsand used in variety of other operations tzinfo objects many of the methods in the datetime module manipulate special tzinfo objects that represent information about time zone tzinfo is merely base class individual time zones are created by inheriting from tzinfo and implementing the following methodstz dst(dtreturns timedelta object representing daylight savings time adjustmentsif applicable returns none if no information is known about dst the argument dt is either datetime object or none tz fromutc(dtconverts datetime objectdtfrom utc time to the local time zone and returns new datetime object this method is called by the astimezone(method on datetime objects default implementation is already provided by tzinfoso it' usually not necessary to redefine this method tz tzname(dtreturns string with the name of the time zone (for example"us/central"dt is either datetime object or none tz utcoffset(dtreturns timedelta object representing the offset of local time from utc in minutes east of utc the offset incorporates all elements that make up the local timeincluding daylight savings timeif applicable the argument dt is either datetime object or none lib fl ff
18,190
the following example shows basic prototype of how one would define time zonevariables that must be defined tzoffset timezone offset in hours from utc for exampleus/cst is - hours dstname name of timezone when dst is in effect stdname name of timezone when dst not in effect class somezone(datetime tzinfo)def utcoffset(self,dt)return datetime timedelta(hours=tzoffsetself dst(dtdef dst(self,dt)is_dst(is function you must implement to see whether dst is in effect according to local timezone rules if is_dst(dt)return datetime timedelta(hours= elsereturn datetime timedelta( def tzname(self,dt)if is_dst(dt)return dstname elsereturn stdname number of examples of defining time zones can also be found in the online documentation for datetime date and time parsing common question that arises with date handling is how to parse different kinds of time and date strings into an appropriate datetime object the only parsing function that is really provided by the datetime module is datetime strptime(howeverin order to use thisyou need to specify the precise date format using various combinations of format codes (see time strptime()for exampleto parse the date string ="aug "you would have to use datetime datetime strptime( "% % % "for "fuzzydate parsing that automatically understands number of common date formatsyou must turn to third-party modules go to the python package index (see alsotime ( errno the errno module defines symbolic names for the integer error codes returned by various operating system callsespecially those found in the os and socket modules these codes are typically found in the errno attribute of an oserror or ioerror exception the os strerror(function can be used to translate an error code into string error message the following dictionary can also be used to translate an integer error code into its symbolic namef lib fl ff
18,191
operating system services errorcode this dictionary maps errno integers to symbolic names (such as 'eperm'posix error codes the following table shows the posix symbolic names for common system error codes the error codes listed here are supported on almost every version of unixmacintosh os-xand windows different unix systems may provide additional error codes that are less common and not listed here if such errors occuryou can consult the errorcode dictionary to find the appropriate symbolic name to use in your program error code description big eacces eaddrinuse eaddrnotavail eafnosupport eagain ealready ebadf ebusy echild econnaborted econnrefused econnreset edeadlk edeadlock edestaddrreq edom edquot eexist efault efbig ehostdown ehostunreach eilseq einprogress eintr einval eio eisconn eisdir eloop emfile emlink arg list too long permission denied address already in use cannot assign requested address address family not supported by protocol try again operation already in progress bad file number device or resource busy no child processes software caused connection abort connection refused connection reset by peer resource deadlock would occur file-locking deadlock error destination address required math argument out of domain of function quota exceeded file exists bad address file too large host is down no route to host illegal byte sequence operation now in progress interrupted system call invalid argument / error transport endpoint is already connected is directory too many symbolic links encountered too many open files too many links lib fl ff
18,192
error code description emsgsize enetdown enetreset enetunreach message too long network is down network dropped connection due to reset network is unreachable file table overflow no buffer space available no such device no such file or directory exec format error no record locks available out of memory protocol not available no space left on device function not implemented transport endpoint is not connected not directory directory not empty socket operation on non-socket not terminal no such device or address operation not supported on transport endpoint operation not permitted protocol family not supported broken pipe protocol not supported protocol wrong type for socket math result not representable object is remote read-only file system cannot send after transport endpoint shutdown socket type not supported illegal seek no such process stale nfs file handle connection timed out too many referencescannot splice too many users operation would block cross-device link enfile enobufs enodev enoent enoexec enolck enomem enoprotoopt enospc enosys enotconn enotdir enotempty enotsock enotty enxio eopnotsupp eperm epfnosupport epipe eprotonosupport eprototype erange eremote erofs eshutdown esocktnosupport espipe esrch estale etimedout etoomanyrefs eusers ewouldblock exdev lib fl ff
18,193
operating system services windows error codes the error codes in the following table are only available on windows error code description wsaeacces wsaeaddrinuse permission denied address already in use cannot assign requested address address family not supported by protocol family operation already in progress invalid file handle software caused connection abort connection refused connection reset by peer destination address required remote shutdown disk quota exceeded bad address host is down no route to host operation now in progress interrupted system call invalid argument socket already connected cannot translate name too many open files message too long name too long network is down network dropped connection on reset network is unreachable no buffer space is available bad protocol option socket is not connected cannot remove non-empty directory socket operation on non-socket operation not supported protocol family not supported too many processes protocol not supported protocol wrong type for socket item not available locally cannot send after socket shutdown socket type not supported file handle no longer available connection timed out wsaeaddrnotavail wsaeafnosupport wsaealready wsaebadf wsaeconnaborted wsaeconnrefused wsaeconnreset wsaedestaddrreq wsaediscon wsaedquot wsaefault wsaehostdown wsaehostunreach wsaeinprogress wsaeintr wsaeinval wsaeisconn wsaeloop wsaemfile wsaemsgsize wsaenametoolong wsaenetdown wsaenetreset wsaenetunreach wsaenobufs wsaenoprotoopt wsaenotconn wsaenotempty wsaenotsock wsaeopnotsupp wsaepfnosupport wsaeproclim wsaeprotonosupport wsaeprototype wsaeremote wsaeshutdown wsaesocktnosupport wsaestale wsaetimedout lib fl ff
18,194
error code description wsaetoomanyrefs wsaeusers wsaewouldblock wsanotinitialised too many references to kernel object quota exceeded resource temporarily unavailable successful wsa startup not performed network subsystem not available winsock dll version out of range wsasysnotready wsavernotsupported fcntl the fcntl module performs file and / control on unix file descriptors file descriptors can be obtained using the fileno(method of file or socket object fcntl(fdcmd [arg]performs commandcmdon an open file descriptorfd cmd is an integer command code arg is an optional argument that' either an integer or string if arg is passed as an integerthe return value of this function is an integer if arg is stringit' interpreted as binary data structureand the return value of the call is the contents of the buffer converted back into string object in this casethe supplied argument and return value should be less than , bytes to avoid possible data corruption the following commands are availablecommand description f_dupfd duplicates file descriptor arg is the lowest number that the new file descriptor can assume similar to the os dup(system call sets the close-on-exec flag to arg ( or if setthe file is closed on an exec(system call returns the close-on-exec flag sets status flags to argwhich is the bitwise or of the followingo_ndelay--nonblocking / (system vo_append--append mode (system vo_sync--synchronous write (system vfndelay--nonblocking / (bsdfappend--append mode (bsdfasync--sends sigio signal to process group when / is possible (bsdgets status flags as set by f_setfl gets process id or process group id set to receive sigio and sigurg signals (bsdsets process id or process group id to receive sigio and sigurg signals (bsdreturns flock structure used in file-locking operations locks filereturning - if the file is already locked locks file but waits if the lock cannot be acquired f_setfd f_getfd f_setfl f_getfl f_getown f_setown f_getlk f_setlk f_setlkw lib fl ff
18,195
operating system services an ioerror exception is raised if the fcntl(function fails the f_getlk and f_setlk commands are supported through the lockf(function ioctl(fdoparg [mutate_flag]this function is like the fcntl(functionexcept that the operations supplied in op are generally defined in the library module termios the extra mutate_flag controls the behavior of this function when mutable buffer object is passed as an argument further details about this can be found in the online documentation because the primary use of ioctl(is to interact with device-drivers and other low-level components of the operating systemits use depends highly on the underlying platform it should not be used in code that aims to be portable flock(fdopperforms lock operationopon the file descriptor fd op is the bitwise or of the following constantswhich are found in fnctlitem description lock_ex exclusive lock all further attempts to acquire the lock will block until the lock is released non-blocking mode returns immediately with an ioerror if the lock is already in use shared lock blocks any attempts to acquire an exclusive lock (lock_ex)but shared locks can still be acquired unlock releases any previous held lock lock_nb lock_sh lock_un in nonblocking modean ioerror exception is raised if the lock cannot be acquired on some systemsthe process of opening and locking file can be performed in single operation by adding special flags to the os open(operation consult the os module for more details lockf(fdop [len [start [whence]]]performs record or range locking on part of file op is the same as for the flock(function len is the number of bytes to lock start is the starting position of the lock relative to the value of whence whence is for the beginning of the file for the current positionand for the end of the file example import fcntl open file open("foo"," "set the close-on-exec bit for file object fcntl fcntl( fileno()fcntl f_setfd lock file (blockingfcntl flock( fileno()fcntl lock_exf lib fl ff
18,196
lock the first bytes of file (non-blockingtryfcntl lockf( fileno()fcntl lock_ex fcntl lock_nb except ioerror,eprint "unable to acquire lock" notes the set of available fcntl(commands and options is system-dependent the fcntl module may contain more than constants on some platforms although locking operations defined in other modules often make use of the context-manager protocolthis is not the case for file locking if you acquire file lockmake sure your code is written to properly release the lock many of the functions in this module can also be applied to the file descriptors of sockets io the io module implements classes for various forms of / as well as the built-in open(function that is used in python the module is also available for use in python the central problem addressed by the io module is the seamless handling of different forms of basic / for exampleworking with text is slightly different than working with binary data because of issues related to newlines and character encodings to handle these differencesthe module is built as series of layerseach of which adds more functionality to the last base / interface the io module defines basic / programming interface that all file-like objects implement this interface is defined by base class iobase an instance of iobase supports these basic operationsattribute description closed close( fileno( flush( isatty( readable( readline([limit]flag indicating whether or not the file is closed closes the file returns the integer file descriptor flushes the / buffers (if anyreturns true if is terminal returns true if was opened for reading reads one line from the stream limit is the maximum number of bytes to read reads all lines from and return as list limitif providedis the maximum number of bytes that can be read before stopping the actual number of bytes read will be slightly greater to accommodate the last linewhich is kept intact readlines([limit] lib fl ff
18,197
operating system services attribute description seek(offset[whence]moves the file pointer to new position relative to the location specified in whence offset is the number of bytes whence is for the start of the file for the current positionand for the end of the file seekable(returns true if is seekable tell(returns the current value of the file pointer truncate([size]truncates the file size so that it is at most size bytes if size isn' givenit truncates the file to bytes writable(returns true if was opened for writing writelines(lineswrites sequence of lines to line endings are not added so they must already be part of each line raw / the lowest level of the / system is related to direct / involving raw bytes the core object for this is fileiowhich provides fairly direct interface to low-level system calls such as read(and write(fileio(name [mode [closefd]] class for performing raw low-level / on file or system file descriptor name is either filename or an integer file descriptor such as that returned by the os open(function or the fileno(method of other file objects mode is one of ' (the default)' 'or 'afor readingwritingor appending '+can be added to the mode for update mode in which both reading and writing is supported closefd is flag that determines if the close(method actually closes the underlying file by defaultthis is truebut it can be set false if you're using fileio to put wrapper around file that was already opened elsewhere if filename was giventhe resulting file object is opened directly using the operating system' open(call there is no internal bufferingand all data is processed as raw byte strings an instance of fileio has all of the basic / operations described earlier plus the following attributes and methodsattribute description closefd flag that determines if the underlying file descriptor will be closed on close((read-onlyfile mode used when opening (read-onlyfilename (read-onlyreads at most size bytes using single system call if size is omittedas much data as possible is returned using readall(this operation may returns fewer bytes than requested so you must use len(to check none is returned if no data is available in non-blocking mode reads as much data as is available and returns as single byte string an empty string is returned on eof in non-blocking modeonly as much data as is immediately available is returned writes byte string or byte-array to using single system call the number of bytes actually written is returned--which may be less than the number supplied in bytes mode name read([size] readall( write(bytesf lib fl ff
18,198
it is important to emphasize that fileio objects are extremely low-levelproviding rather thin layer over operating system calls such as read(and write(specificallyusers of this object will need to diligently check return codes as there is no guarantee that the read(or write(operations will read or write all of the requested data the fcntl module can be used to change low-level aspects of files such as file lockingblocking behaviorand so forth fileio objects should not be used for line-oriented data such as text although methods such as readline(and readlines(are definedthese come from the iobase base class where they are both implemented entirely in python and work by issuing read(operations for single byte at time needless to saythe resulting performance is horrible for exampleusing readline(on fileio object is more than times slower than using readline(on standard file object created by the open(function in python buffered binary / the buffered / layer contains collection of file objects that read and write raw binary databut with in-memory buffering as inputthese objects all require file object that implements raw / such as the fileio object in the previous section all of the classes in this section inherit from bufferediobase bufferedreader(raw [buffer_size] class for buffered binary reading on raw file specified in raw buffer_size specifies the buffer size to use in bytes if omittedthe value of default_buffer_size is used ( , bytes as of this writingan instance of bufferedreader supports all of the operations provided on iobase in addition to these operationsmethod description peek([ ]returns at most bytes of data from the / buffer without moving the file pointer if is omitteda single byte is returned if necessarya read operation will be issued to fill the buffer if it is currently empty this operation never returns more bytes than the current buffer sizeso the result may be smaller than the requested number of bytes in reads bytes and returns as byte string if is omittedall available data (up to eofis read and returned if the underlying file is non-blockingany available data is read and returned if non-blocking file is read and no data is availablea blockingioerror exception is raised reads up to bytes and returns as byte string using single system call if any data is already loaded in the bufferit is simply returned otherwisea single read(is made on the raw file to return data unlike read()this operation may return less data than requested even if the underlying file is not at eof reads len(bbytes of data from the file into an existing bytearray object the actual number of bytes read is returned if the underlying file is in non-blocking modea blockingioerror exception is raised if no data is available read([ ] read ([ ] readinto(bf lib fl ff
18,199
operating system services bufferedwriter(raw [buffer_size [max_buffer_size]] class for buffered binary writing on raw file specified in raw buffer_size specifies the number of bytes that can be saved in the buffer before data is flushed to the underlying / stream the default value is default_buffer_size max_buffer_size specifies the maximum buffer size to use for storing output data that is being written to non-blocking stream and defaults to twice the value of buffer_size this value is larger to allow for continued writing while the previous buffer contents are written to the / stream by the operating system an instance of bufferedwriter supports the following operationsmethod description flush(writes all bytes stored in the buffer to the underlying / stream raises blockingioerror exception if the file is in nonblocking mode and the operation would block ( if the stream can' accept any new data at the momentwrites the bytes in bytes to the / stream and returns the number of bytes actually written if the underlying stream is nonblockinga blockingioerror exception is raised if write operation would block write(bytesbufferedrwpair(readerwriter [buffer_size [max_buffer_size]] class for buffered binary reading and writing on pair of raw / streams reader is raw file that supports readingand writing is raw file that supports writing these files may be differentwhich may be useful for certain kinds of communication involving pipes and sockets the buffer size parameters have the same meaning as for bufferedwriter an instance of bufferedrwpair supports all of the operations for bufferedreader and bufferedwriter bufferedrandom(raw [buffer_size [max_buffer_size]] class for buffered binary reading and writing on raw / stream that supports random access ( seekingraw must be raw file that supports both readwriteand seek operations the buffer size parameters have the same meaning as for bufferedwriter an instance of bufferedrandom supports all of the operations for bufferedreader and bufferedwriter bytesio([bytes]an in-memory file that implements the functionality of buffered / stream bytes is byte string that specifies the initial contents of the file an instance of bytesio supports all of the operations of bufferedreader and bufferedwriter objects in additiona method getvalue(can be used to return the current contents of the file as byte string as with fileio objectsall the file objects in this section should not be used with line-oriented data such as text although it' not quite as bad due to bufferingthe resulting performance is still quite poor ( more than times slower than reading lines with files created using the python built-in open(functionalsobecause of internal bufferingyou need to take care to manage flush(operations when writing for exampleif you use seek(to move the file pointer to new locationyou should first use flush(to flush any previously written data (if anyf lib fl ff