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 typ...
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 num...
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 functio...
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...
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 ...
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 subcl...
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 tab...
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...
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 arrays...
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 def...
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 behav...
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 attribut...
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 pa...
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 usi...
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 ...
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 lea...
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 ord...
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...
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 prod...
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...
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 ta...
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(abreturn...
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','share...
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 ...
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 / operatio...
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 sho...
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 ('\xf...
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 t...
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 (? match...
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 charac...
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 [...
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 ...
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...
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 "% /% /% ( ...
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,th...
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(use...
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(strin...
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 pr...
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 '...
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 t...
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 ...
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(unichrr...
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 na...
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 da...
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 transaction...
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 ...
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 result...
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...
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 b...
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 inde...
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-memor...
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 o...
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 finaliz...
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 a...
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 funct...
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...
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...
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 modu...
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 ( d...
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 decomp...
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 subdire...
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 su...
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...
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 de...
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 ac...
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(na...
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 filena...
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 regtypeareg...
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...
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 ma...
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 e...
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 ret...
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 ...
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 valu...
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 us...
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...
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 ...
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 confi...
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 optio...
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 configpa...
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 n...
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 differenc...
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 representin...
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 possib...
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 be...
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= )timedelt...
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...
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(...
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 s...
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 ava...
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...
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 m...
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 ...
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...
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 t...
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 requ...
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...