id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
18,000 | table continued parameter description maintainer maintainer_email url maintainer' name maintainer' email home page for the package short description of the package long description of the package location where package can be downloaded list of string classifiers description long_description download_url classifiers creating setup py file is enough to create source distribution of your software type the following shell command to make source distributionpython setup py sdist this creates an archive file such as spam- tar gz or spam- zip in the directory spam/dist this is the file you would give to others to install your software to installa user simply unpacks the archive and performs these stepsunzip spam- zip cd spam- python setup py install this installs the software into the local python distribution and makes it available for general use modules and packages are normally installed into directory called "site-packagesin the python library to find the exact location of this directoryinspect the value of sys path scripts are normally installed into the same directory as the python interpreter on unix-based systems or into "scriptsdirectory on windows (found in " :\python \scriptsin typical installationon unixif the first line of script starts with #and contains the text "python"the installer will rewrite the line to point to the local installation of python thusif you have written scripts that have been hard-coded to specific python location such as /usr/local/bin/pythonthey should still work when installed on other systems where python is in different location the setup py file has number of other commands concerning the distribution of software if you type 'python setup py bdist' binary distribution is created in which all of the py files have already been precompiled into pyc files and placed into directory structure that mimics that of the local platform this kind of distribution is needed only if parts of your application have platform dependencies (for exampleif you also have extensions that need to be compiledif you run 'python setup py bdist_wininston windows machinean exe file will be created when openeda windows installer dialog will startprompting the user for information about where the software should be installed this kind of distribution also adds entries to the registrymaking it easy to uninstall your package at later date the distutils module assumes that users already have python installation on their machine (downloaded separatelyalthough it is possible to create software packages where the python runtime and your software are bundled together into single lib fl ff |
18,001 | modulespackagesand distribution binary executablethat is beyond the scope of what can be covered here (look at third-party module such as py exe or py app for further detailsif all you are doing is distributing libraries or simple scripts to peopleit is usually unnecessary to package your code with the python interpreter and runtime as well finallyit should be noted that there are many more options to distutils than those covered here describes how distutils can be used to compile and +extensions although not part of the standard python distributionpython software is often distributed in the form of an egg file this format is created by the popular setuptools extension (simply change the first part of your setup py file as followssetup py tryfrom setuptools import setup except importerrorfrom distutils core import setup setup(name "spam"installing third-party libraries the definitive resource for locating third-party libraries and extensions to python is the python package index (pypi)which is located at packages that also depend on other third-party modules for the more major extensionsyou will often find platform-native installer that simply steps you through the process using series of dialog screens for other modulesyou typically unpack the downloadlook for the setup py fileand type python setup py install to install the software by defaultthird-party modules are installed in the site-packages directory of the python standard library access to this directory typically requires root or administrator access if this is not the caseyou can type python setup py install --user to have the module installed in per-user library directory this installs the package in per-user directory such as "/users/beazleylocal/lib/python /site-packageson unix if you want to install the software somewhere else entirelyuse the --prefix option to setup py for exampletyping python setup py install --prefix=/homebeazley/pypackages installs module under the directory /home/beazleypypackages when installing in nonstandard locationyou will probably have to adjust the setting of sys path in order for python to locate your newly installed modules be aware that many extensions to python involve or +code if you have downloaded source distributionyour system will have to have +compiler installed in order to run the installer on unixlinuxand os xthis is usually not an issue on windowsit has traditionally been necessary to have version of microsoft visual studio installed if you're working on that platformyou're probably better off looking for precompiled version of your extension lib fl ff |
18,002 | if you have installed setuptoolsa script easy_install is available to install packages simply type easy_install pkgname to install specific package if configured correctlythis will download the appropriate software from pypi along with any dependencies and install it for you of courseyour mileage might vary if you would like to add your own software to pypisimply type python setup py register this will upload metadata about the latest version of your software to the index (note that you will have to register username and password firstf lib fl ff |
18,003 | lib fl ff |
18,004 | input and output his describes the basics of python input and output ( / )including command-line optionsenvironment variablesfile /ounicodeand how to serialize objects using the pickle module reading command-line options when python startscommand-line options are placed in the list sys argv the first element is the name of the program subsequent items are the options presented on the command line after the program name the following program shows minimal prototype of manually processing simple command-line argumentsimport sys if len(sys argv! sys stderr write("usage python % inputfile outputfile\nsys argv[ ]raise systemexit( inputfile sys argv[ outputfile sys argv[ in this programsys argv[ contains the name of the script being executed writing an error message to sys stderr and raising systemexit with non-zero exit code as shown is standard practice for reporting usage errors in command-line tools although you can manually process command options for simple scriptsuse the optparse module for more complicated command-line handling here is simple exampleimport optparse optparse optionparser(an option taking an argument add_option("- ",action="store",dest="outfile" add_option("--output",action="store",dest="outfile"an option that sets boolean flag add_option("- ",action="store_true",dest="debug" add_option("--debug",action="store_true",dest="debug"set default values for selected options set_defaults(debug=falseparse the command line optsargs parse_args(retrieve the option settings outfile opts outfile debugmode opts debug lib fl ff |
18,005 | input and output in this exampletwo types of options are added the first option- or --outputhas required argument this behavior is selected by specifying action='storein the call to add_option(the second option- or --debugis merely setting boolean flag this is enabled by specifying action='store_truein add_option(the dest argument to add_option(selects an attribute name where the argument value will be stored after parsing the set_defaults(method sets default values for one or more of the options the argument names used with this method should match the destination names selected for each option if no default value is selectedthe default value is set to none the previous program recognizes all of the following command-line stylespython prog py - outfile - infile infilen python prog py --output=outfile --debug infile infilen python prog py - python prog py --help parsing is performed using the parse_args(method this method returns -tuple (optsargswhere opts is an object containing the parsed option values and args is list of items on the command line not parsed as options option values are retrieved using opts dest where dest is the destination name used when adding an option for examplethe argument to the - or --output argument is placed in opts outfilewhereas args is list of the remaining arguments such as ['infile ''infilen'the optparse module automatically provides - or --help option that lists the available options if requested by the user bad options also result in an error message this example only shows the simplest use of the optparse module further details on some of the more advanced options can be found in "operating system services environment variables environment variables are accessed in the dictionary os environ here' an exampleimport os path os environ["path"user os environ["user"editor os environ["editor"etc to modify the environment variablesset the os environ variable for exampleos environ["foo""barmodifications to os environ affect both the running program and subprocesses created by python files and file objects the built-in function open(name [,mode [,bufsize]]opens and creates file objectas shown heref open("foo" open("foo",' ' open("foo",' 'opens "foofor reading opens "foofor reading (same as aboveopen for writing lib fl ff |
18,006 | the file mode is 'rfor read'wfor writeor 'afor append these file modes assume text-mode and may implicitly perform translation of the newline character '\nfor exampleon windowswriting the character '\nactually outputs the twocharacter sequence '\ \ (and when reading the file back'\ \nis translated back into single '\ncharacterif you are working with binary dataappend 'bto the file mode such as 'rbor 'wbthis disables newline translation and should be included if you are concerned about portability of code that processes binary data (on unixit is common mistake to omit the 'bbecause there is no distinction between text and binary filesalsobecause of the distinction in modesyou might see text-mode specified as 'rt''wt'or 'at'which more clearly expresses your intent file can be opened for in-place updates by supplying plus (+charactersuch as ' +or ' +when file is opened for updateyou can perform both input and outputas long as all output operations flush their data before any subsequent input operations if file is opened using ' +modeits length is first truncated to zero if file is opened with mode 'uor 'ru'it provides universal newline support for reading this feature simplifies cross-platform work by translating different newline encodings (such as '\ ''\ 'and '\ \ 'to standard '\ncharacter in the strings returned by various file / functions this can be useful iffor exampleyou are writing scripts on unix systems that must process text files generated by programs on windows the optional bufsize parameter controls the buffering behavior of the filewhere is unbuffered is line bufferedand negative number requests the system default any other positive number indicates the approximate buffer size in bytes that will be used python adds four additional parameters to the open(functionwhich is called as open(name [,mode [,bufsize [encoding [errors [newline [closefd]]]]]]encoding is an encoding name such as 'utf- or 'asciierrors is the error-handling policy to use for encoding errors (see the later sections in this on unicode for more informationnewline controls the behavior of universal newline mode and is set to none'''\ ''\ 'or '\ \nif set to noneany line ending of the form '\ ''\ 'or '\ \nis translated into '\nif set to '(the empty string)any of these line endings are recognized as newlinesbut left untranslated in the input text if newline has any other legal valuethat value is what is used to terminate lines closefd controls whether the underlying file descriptor is actually closed when the close(method is invoked by defaultthis is set to true table shows the methods supported by file objects table file methods method description read([ ] readline([ ]reads at most bytes reads single line of input up to characters if is omittedthis method reads the entire line reads all the lines and returns list size optionally specifies the approximate number of characters to read on the file before stopping writes string writes all strings in sequence lines closes the file readlines([size] write(sf writelines(linesf close( lib fl ff |
18,007 | input and output table continued method description tell(returns the current file pointer seek(offset [whence]seeks to new file position isatty(returns if is an interactive terminal flush(flushes the output buffers truncate([size]truncates the file to at most size bytes fileno(returns an integer file descriptor next(returns the next line or raises stopiteration in python it is called __next__(the read(method returns the entire file as string unless an optional length parameter is given specifying the maximum number of characters the readline(method returns the next line of inputincluding the terminating newlinethe readlines(method returns all the input lines as list of strings the readline(method optionally accepts maximum line lengthn if line longer than characters is readthe first characters are returned the remaining line data is not discarded and will be returned on subsequent read operations the readlines(method accepts size parameter that specifies the approximate number of characters to read before stopping the actual number of characters read may be larger than this depending on how much data has been buffered both the readline(and readlines(methods are platform-aware and handle different representations of newlines properly (for example'\nversus '\ \ 'if the file is opened in universal newline mode ('uor 'ru')newlines are converted to '\nread(and readline(indicate end-of-file (eofby returning an empty string thusthe following code shows how you can detect an eof conditionwhile trueline readline(if not lineeof break convenient way to read all lines in file is to use iteration with for loop for examplefor line in fiterate over all lines in the file do something with line be aware that in python the various read operations always return -bit stringsregardless of the file mode that was specified (text or binaryin python these operations return unicode strings if file has been opened in text mode and byte strings if the file is opened in binary mode the write(method writes string to the fileand the writelines(method writes list of strings to the file write(and writelines(do not add newline characters to the outputso all output that you produce should already include all necessary formatting these methods can write raw-byte strings to filebut only if the file has been opened in binary mode lib fl ff |
18,008 | internallyeach file object keeps file pointer that stores the byte offset at which the next read or write operation will occur the tell(method returns the current value of the file pointer as long integer the seek(method is used to randomly access parts of file given an offset and placement rule in whence if whence is (the default)seek(assumes that offset is relative to the start of the fileif whence is the position is moved relative to the current positionand if whence is the offset is taken from the end of the file seek(returns the new value of the file pointer as an integer it should be noted that the file pointer is associated with the file object returned by open(and not the file itself the same file can be opened more than once in the same program (or in different programseach instance of the open file has its own file pointer that can be manipulated independently the fileno(method returns the integer file descriptor for file and is sometimes used in low-level / operations in certain library modules for examplethe fcntl module uses the file descriptor to provide low-level file control operations on unix systems file objects also have the read-only data attributes shown in table table file object attributes attribute description closed boolean value indicates the file statefalse if the file is opentrue if closed the / mode for the file name of the file if created using open(otherwiseit will be string indicating the source of the file boolean value indicating whether space character needs to be printed before another value when using the print statement classes that emulate files must provide writable attribute of this name that' initially initialized to zero (python onlywhen file is opened in universal newline modethis attribute contains the newline representation actually found in the file the value is none if no newlines have been encountereda string containing '\ ''\ 'or '\ \ 'or tuple containing all the different newline encodings seen string that indicates file encodingif any (for example'latin- or 'utf- 'the value is none if no encoding is being used mode name softspace newlines encoding standard inputoutputand error the interpreter provides three standard file objectsknown as standard inputstandard outputand standard errorwhich are available in the sys module as sys stdinsys stdoutand sys stderrrespectively stdin is file object corresponding to the stream of input characters supplied to the interpreter stdout is the file object that receives output produced by print stderr is file that receives error messages more often than notstdin is mapped to the user' keyboardwhereas stdout and stderr produce text onscreen lib fl ff |
18,009 | input and output the methods described in the preceding section can be used to perform raw / with the user for examplethe following code writes to standard output and reads line of input from standard inputimport sys sys stdout write("enter your name "name sys stdin readline(alternativelythe built-in function raw_input(promptcan read line of text from stdin and optionally print promptname raw_input("enter your name "lines read by raw_input(do not include the trailing newline this is different than reading directly from sys stdin where newlines are included in the input text in python raw_input(has been renamed to input(keyboard interrupts (typically generated by ctrl+cresult in keyboardinterrupt exception that can be caught using an exception handler if necessarythe values of sys stdoutsys stdinand sys stderr can be replaced with other file objectsin which case the print statement and input functions use the new values should it ever be necessary to restore the original value of sys stdoutit should be saved first the original values of sys stdoutsys stdinand sys stderr at interpreter startup are also available in sys _stdout_ _sys _stdin_ _and sys _stderr_ _respectively note that in some cases sys stdinsys stdoutand sys stderr may be altered by the use of an integrated development environment (idefor examplewhen python is run under idlesys stdin is replaced with an object that behaves like file but is really an object in the development environment in this casecertain lowlevel methodssuch as read(and seek()may be unavailable the print statement python uses special print statement to produce output on the file contained in sys stdout print accepts comma-separated list of objects such as the followingprint "the values are"xyz for each objectthe str(function is invoked to produce an output string these output strings are then joined and separated by single space to produce the final output string the output is terminated by newline unless trailing comma is supplied to the print statement in this casethe next print statement will insert space before printing more items the output of this space is controlled by the softspace attribute of the file being used for output print "the values are "xyzw print the same textusing two print statements print "the values are "xyomits trailing newline print zw space is printed before to produce formatted outputuse the string-formatting operator (%or the format(method as described in "operators and expressions here' an exampleprint "the values are % % % ( , ,zformatted / print "the values are { : { : { }format( , ,zf lib fl ff |
18,010 | you can change the destination of the print statement by adding the special >>file modifier followed by commawhere file is file object that allows writes here' an examplef open("output"," "print >> "hello worldf close(the print(function one of the most significant changes in python is that print is turned into function in python it is also possible to use print as function if you include the statement from _future_ import print_function in each module where used the print(function works almost exactly the same as the print statement described in the previous section to print series of values separated by spacesjust supply them all to print(like thisprint("the values are"xyzto suppress or change the line endinguse the end=ending keyword argument for exampleprint("the values are"xyzend=''suppress the newline to redirect the output to fileuse the file=outfile keyword argument for exampleprint("the values are"xyzfile=fredirect to file object to change the separator character between itemsuse the sep=sepchr keyword argument for exampleprint("the values are"xyzsep=','put commas between the values variable interpolation in text output common problem when generating output is that of producing large text fragments containing embedded variable substitutions many scripting languages such as perl and php allow variables to be inserted into strings using dollar-variable substitutions (that is$name$addressand so onpython provides no direct equivalent of this featurebut it can be emulated using formatted / combined with triple-quoted strings for exampleyou could write short form letterfilling in namean item nameand an amountas shown in the following examplenotetrailing slash right after ""prevents blank line from appearing as the first line form """dear %(name)sf lib fl ff |
18,011 | input and output please send back my %(item) or pay me $%(amount) sincerely yoursjoe python user ""print form 'name''mr bush''item''blender''amount' this produces the following outputdear mr bushplease send back my blender or pay me $ sincerely yoursjoe python user the format(method is more modern alternative that cleans up some of the previous code for exampleform """dear {name}please send back my {itemor pay me {amount: fsincerely yoursjoe python user ""print form format(name='mr bush'item='blender'amount= for certain kinds of formsyou can also use template stringsas followsimport string form string template("""dear $nameplease send back my $item or pay me $amount sincerely yoursjoe python user """print form substitute({'name''mr bush''item''blender''amount'"% }in this casespecial variables in the string indicate substitutions the form substitute(method takes dictionary of replacements and returns new string although the previous approaches are simplethey aren' always the most powerful solutions to text generation web frameworks and other large application frameworks tend to provide their own template string engines that support embedded control-flowvariable substitutionsfile inclusionand other advanced features generating output working directly with files is the / model most familiar to programmers howevergenerator functions can also be used to emit an / stream as sequence of data fragments to do thissimply use the yield statement like you would use write(or print statement here is an examplef lib fl ff |
18,012 | def countdown( )while yield " -minus % \nn - yield "kaboom!\nproducing an output stream in this manner provides great flexibility because the production of the output stream is decoupled from the code that actually directs the stream to its intended destination for exampleif you wanted to route the above output to file fyou could do thiscount countdown( writelines(countifinsteadyou wanted to redirect the output across socket syou could do thisfor chunk in counts sendall(chunkorif you simply wanted to capture all of the output in stringyou could do thisout "join(countmore advanced applications can use this approach to implement their own / buffering for examplea generator could be emitting small text fragmentsbut another function could be collecting the fragments into large buffers to create largermore efficient / operationchunks [buffered_size for chunk in countchunks append(chunkbuffered_size +len(chunkif buffered_size >maxbuffersizeoutf write("join(chunks)chunks clear(buffered_size outf write("join(chunksfor programs that are routing output to files or network connectionsa generator approach can also result in significant reduction in memory use because the entire output stream can often be generated and processed in small fragments as opposed to being first collected into one large output string or list of strings this approach to output is sometimes seen when writing programs that interact with the python web services gateway interface (wsgithat' used to communicate between components in certain web frameworks unicode string handling common problem associated with / handling is that of dealing with international characters represented as unicode if you have string of raw bytes containing an encoded representation of unicode stringuse the decode([encoding [,errors]]method to convert it into proper unicode string to convert unicode stringuto an encoded byte stringuse the string method encode([encoding [errors]]both of these conversion operators require the use of special encoding name that specifies how unicode character values are mapped to sequence of -bit characters in byte stringsand vice versa the encoding parameter is specified as string lib fl ff |
18,013 | input and output and is one of more than hundred different character encodings the following valueshoweverare most commonvalue description 'ascii'latin- or 'iso- - -bit ascii iso - latin- windows encoding -bit variable-length encoding -bit variable-length encoding (may be little or big endianutf- little endian encoding utf- big endian encoding same format as unicode literals "stringsame format as raw unicode literals ur"string'cp 'utf- 'utf- 'utf- -le'utf- -be'unicode-escape'raw-unicode-escapethe default encoding is set in the site module and can be queried using sys getdefaultencoding(in many casesthe default encoding is 'ascii'which means that ascii characters with values in the range [ , fare directly mapped to unicode characters in the range [ + + fhowever'utf- is also very common setting technical details concerning common encodings appears in later section when using the decode(methodit is always assumed that is string of bytes in python this means that is standard stringbut in python must be special bytes type similarlythe result of encode(is always byte sequence one caution if you care about portability is that these methods are little muddled in python for instancepython strings have both decode(and encode(methodswhereas in python strings only have an encode(method and the bytes type only has decode(method to simplify code in python make sure you only use encode(on unicode strings and decode(on byte strings when string values are being converteda unicodeerror exception might be raised if character that can' be converted is encountered for instanceif you are trying to encode string into 'asciiand it contains unicode character such as + you will get an encoding error because this character value is too large to be represented in the ascii character set the errors parameter of the encode(and decode(methods determines how encoding errors are handled it' string with one of the following valuesvalue description 'strictraises unicodeerror exception for encoding and decoding errors ignores invalid characters replaces invalid characters with replacement character ( +fffd in unicode'?in standard stringsreplaces invalid characters with python character escape sequence for examplethe character + is replaced by '\ replaces invalid characters with an xml character reference for examplethe character + is replaced by '&# ;'ignore'replace'backslashreplace'xmlcharrefreplacef lib fl ff |
18,014 | the default error handling is 'strictthe 'xmlcharrefreplaceerror handling policy is often useful way to embed international characters into ascii-encoded text on web pages for exampleif you output the unicode string 'jalape\ oby encoding it to ascii with 'xmlcharrefreplacehandlingbrowsers will almost always correctly render the output text as "jalapenoand not some garbled alternative to keep your brain from explodingencoded byte strings and unencoded strings should never be mixed together in expressions (for exampleusing to concatenatepython prohibits this altogetherbut python will silently go ahead with such operations by automatically promoting byte strings to unicode according to the default encoding setting this behavior is often source of surprising results or inexplicable error messages thusyou should carefully try to maintain strict separation between encoded and unencoded character data in your program unicode / when working with unicode stringsit is never possible to directly write raw unicode data to file this is due to the fact that unicode characters are internally represented as multibyte integers and that writing such integers directly to an output stream causes problems related to byte ordering for exampleyou would have to arbitrarily decide if the unicode character +hhll is to be written in "little endianformat as the byte sequence ll hh or in "big endianformat as the byte sequence hh ll moreoverother tools that process unicode would have to know which encoding you used because of this problemthe external representation of unicode strings is always done according to specific encoding rule that precisely defines how unicode characters are to be represented as byte sequence thusto support unicode /othe encoding and decoding concepts described in the previous section are extended to files the built-in codecs module contains collection of functions for converting byte-oriented data to and from unicode strings according to variety of different data-encoding schemes perhaps the most straightforward way to handle unicode files is to use the codecs open(filename [mode [encoding [errors]]]functionas followsf codecs open('foo txt',' ','utf- ','strict' codecs open('bar txt',' ','utf- 'reading writing this creates file object that reads or writes unicode strings the encoding parameter specifies the underlying character encoding that will be used to translate data as it is read or written to the file the errors parameter determines how errors are handled and is one of 'strict''ignore''replace''backslashreplace'or 'xmlcharrefreplaceas described in the previous section if you already have file objectthe codecs encodedfile(fileinputenc [outputenc [errors]]function can be used to place an encoding wrapper around it here' an examplef open("foo txt","rb"fenc codecs encodedfile( ,'utf- ' lib fl ff |
18,015 | input and output in this casedata read from the file will be interpreted according to the encoding supplied in inputenc data written to the file will be interpreted according to the encoding in inputenc and written according to the encoding in outputenc if outputenc is omittedit defaults to the same as inputenc errors has the same meaning as described earlier when putting an encodedfile wrapper around an existing filemake sure that file is in binary mode otherwisenewline translation might break the encoding when you're working with unicode filesthe data encoding is often embedded in the file itself for examplexml parsers may look at the first few bytes of the string 'to determine the document encoding if the first four values are ('<?xm')the encoding is assumed to be utf- if the first four values are or the encoding is assumed to be utf- big endian or utf- little endianrespectively alternativelya document encoding may appear in mime headers or as an attribute of other document elements here' an examplesimilarlyunicode files may also include special byte-order markers (bomthat indicate properties of the character encoding the unicode character +feff is reserved for this purpose typicallythe marker is written as the first character in the file programs then read this character and look at the arrangement of the bytes to determine encoding (for example'\xff\xfefor utf- -le or '\xfe\xffutf- -beonce the encoding is determinedthe bom character is discarded and the remainder of the file is processed unfortunatelyall of this extra handling of the bom is not something that happens behind the scenes you often have to take care of this yourself if your application warrants it when the encoding is read from documentcode similar to the following can be used to turn the input file into an encoded streamf open("somefile","rb"determine encoding of the file put an appropriate encoding wrapper on the file assumes that the bom (if anyhas already been discarded by earlier statements fenc codecs encodedfile( ,encodingdata fenc read(unicode data encodings table lists some of the most commonly used encoders in the codecs module table encoders in the codecs module encoder description 'ascii'latin- ''iso- - 'cp 'cp 'utf- 'utf- ascii encoding latin- or iso- - encoding cp encoding cp encoding -bit variable-length encoding -bit variable-length encoding lib fl ff |
18,016 | table continued encoder description 'utf- -le'utf- -be'unicode-escapeutf- but with explicit little endian encoding utf- but with explicit big endian encoding same format as "stringsame format as ur"string'raw-unicode-escapethe following sections describe each of the encoders in more detail 'asciiencoding in 'asciiencodingcharacter values are confined to the ranges [ , fand [ + + fany character outside this range is invalid 'iso- - ''latin- encoding characters can be any -bit value in the ranges [ , xffand [ + + ffvalues in the range [ , fcorrespond to characters from the ascii character set values in the range [ , xffcorrespond to characters from the iso- - or extended ascii character set any characters with values outside the range [ , xffresult in an error 'cp encoding this encoding is similar to 'iso- - but is the default encoding used by python when it runs as console application on windows certain characters in the range [ , xffcorrespond to special symbols used for rendering menuswindowsand frames in legacy dos applications 'cp encoding this is an encoding that is very similar to 'iso- - used on windows howeverthis encoding defines characters in the range [ - fthat are undefined in 'iso- - and which have different code points in unicode 'utf- encoding utf- is variable-length encoding that allows all unicode characters to be represented single byte is used to represent ascii characters in the range - all other characters are represented by multibyte sequences of or bytes the encoding of these bytes is shown hereunicode characters byte byte byte + + + + ff + +ffff nnnnnnn nnnnn nnnn nnnnnn nnnnnn nnnnnn for -byte sequencesthe first byte always starts with the bit sequence for -byte sequencesthe first byte starts with the bit sequence all subsequent data bytes in multibyte sequences start with the bit sequence in full generalitythe utf- format allows for multibyte sequences of up to bytes in python -byte utf- sequences are used to encode pair of unicode characters lib fl ff |
18,017 | input and output known as surrogate pair both characters have values in the range [ + +dfffand are combined to encode -bit character value the surrogate encoding is as follows:the -byte sequence nnn nnnnnn nmmmm mmmmm is encoded as the pair + nu+dc mwhere is the upper bits and is the lower bits of the -bit character encoded in the -byte utf- sequence fiveand -byte utf- sequences (denoted by starting bit sequences of and respectivelyare used to encode character values up to bits in length these values are not supported by python and currently result in unicodeerror exception if they appear in an encoded data stream utf- encoding has number of useful properties that allow it to be used by older software firstthe standard ascii characters are represented in their standard encoding this means that utf- -encoded ascii string is indistinguishable from traditional ascii string secondutf- doesn' introduce embedded null bytes for multibyte character sequences thereforeexisting software based on the library and programs that expect null-terminated -bit strings will work with utf- strings finallyutf- encoding preserves the lexicographic ordering of strings that isif and are unicode strings and bthen also holds when and are converted to utf- thereforesorting algorithms and other ordering algorithms written for -bit strings will also work for utf- 'utf- ''utf- -be'and 'utf- -leencoding utf- is variable-length -bit encoding in which unicode characters are written as -bit values unless byte ordering is specifiedbig endian encoding is assumed in additiona byte-order marker of +feff can be used to explicitly specify the byte ordering in utf- data stream in big endian encodingu+feff is the unicode character for zero-width nonbreaking spacewhereas the reversed value +fffe is an illegal unicode character thusthe encoder can use the byte sequence fe ff or ff fe to determine the byte ordering of data stream when reading unicode datapython removes the byte-order markers from the final unicode string 'utf- -beencoding explicitly selects utf- big endian encoding 'utf- -leencoding explicitly selects utf- little ending encoding although there are extensions to utf- to support character values greater than bitsnone of these extensions are currently supported 'unicode-escapeand 'raw-unicode-escapeencoding these encoding methods are used to convert unicode strings to the same format as used in python unicode string literals and unicode raw string literals here' an examples '\ \ \ encode('unicode-escape'# '\ \ \ unicode character properties in addition to performing /oprograms that use unicode may need to test unicode characters for various properties such as capitalizationnumbersand whitespace the unicodedata module provides access to database of character properties general character properties can be obtained with the unicodedata category(cfunction for exampleunicodedata category( " "returns 'lu'signifying that the character is an uppercase letter lib fl ff |
18,018 | another tricky problem with unicode strings is that there might be multiple representations of the same unicode string for examplethe character + ( )might be fully composed as single character + or decomposed into multicharacter sequence + + ( ~if consistent processing of unicode strings is an issueuse the unicodedata normalize(function to ensure consistent character representation for exampleunicodedata normalize('nfc'swill make sure that all characters in are fully composed and not represented as sequence of combining characters further details about the unicode character database and the unicodedata module can be found in "strings and text handling object persistence and the pickle module finallyit' often necessary to save and restore the contents of an object to file one approach to this problem is to write pair of functions that simply read and write data from file in special format an alternative approach is to use the pickle and shelve modules the pickle module serializes an object into stream of bytes that can be written to file and later restored the interface to pickle is simpleconsisting of dump(and load(operation for examplethe following code writes an object to fileimport pickle obj someobject( open(filename,'wb'pickle dump(objff close(save object on to restore the objectyou can use the following codeimport pickle open(filename,'rb'obj pickle load(frestore the object close( sequence of objects can be saved by issuing series of dump(operations one after the other to restore these objectssimply use similar sequence of load(operations the shelve module is similar to pickle but saves objects in dictionary-like databaseimport shelve obj someobject(db shelve open("filename"db['key'obj obj db['key'db close(open shelve save object in the shelve retrieve it close the shelve although the object created by shelve looks like dictionaryit also has restrictions firstthe keys must be strings secondthe values stored in shelf must be compatible with pickle most python objects will workbut special-purpose objects such as files and network connections maintain an internal state that cannot be saved and restored in this manner the data format used by pickle is specific to python howeverthe format has evolved several times over python versions the choice of protocol can be selected using an optional protocol parameter to the pickle dump(objfileprotocoloperation lib fl ff |
18,019 | input and output by defaultprotocol is used this is the oldest pickle data format that stores objects in format understood by virtually all python versions howeverthis format is also incompatible with many of python' more modern features of user-defined classes such as slots protocol and use more efficient binary data representation to use these alternative protocolsyou would perform operations such as the followingimport pickle obj someobject( open(filename,'wb'pickle dump(obj, , pickle dump(obj, ,pickle highest_protocolf close(save using protocol use the most modern protocol it is not necessary to specify the protocol when restoring an object using load(the underlying protocol is encoded into the file itself similarlya shelve can be opened to save python objects using an alternative pickle protocol like thisimport shelve db shelve open(filename,protocol= it is not normally necessary for user-defined objects to do anything extra to work with pickle or shelve howeverthe special methods _getstate_ (and _setstate_ (can be used to assist the pickling process the _getstate_ (methodif definedwill be called to create value representing the state of an object the value returned by _getstate_ (should typically be stringtuplelistor dictionary the _setstate_ (method receives this value during unpickling and should restore the state of an object from it here is an example that shows how these methods could be used with an object involving an underlying network connection although the actual connection can' be pickledthe object saves enough information to reestablish it when it' unpickled laterimport socket class client(object)def _init_ (self,addr)self server_addr addr self sock socket socket(socket af_inet,socket sock_streamself sock connect(addrdef _getstate_ (self)return self server_addr def _setstate_ (self,value)self server_addr value self sock socket socket(socket af_inet,socket sock_streamself sock connect(self server_addrbecause the data format used by pickle is python-specificyou would not use this feature as means for exchanging data between applications written in different programming languages moreoverdue to security concernsprograms should not process pickled data from untrusted sources ( knowledgeable attacker can manipulate the pickle data format to execute arbitrary system commands during unpicklingthe pickle and shelve modules have many more customization features and advanced usage options for more detailsconsult "python runtime services lib fl ff |
18,020 | execution environment his describes the environment in which python programs are executed the goal is to describe the runtime behavior of the interpreterincluding program startupconfigurationand program termination interpreter options and environment the interpreter has number of options that control its runtime behavior and environment options are given to the interpreter on the command line as followspython [options[- cmd filename [argshere' list of the most common command-line optionstable option interpreter command-line arguments description enables warnings about features that are being removed or changed in python - prevents the creation of pyc or pyo files on import - ignores environment variables - prints list of all available command-line options - enters interactive mode after program execution - module runs library module module as script - optimized mode -oo optimized mode plus removal of documentation strings when creating pyo files - arg specifies the behavior of the division operator in python one of -qold (the default)-qnew-qwarnor -qwarnall - prevents the addition of the user site directory to sys path - prevents inclusion of the site initialization module - reports warnings about inconsistent tab usage -tt inconsistent tab usage results in taberror exception - unbuffered binary stdout and stdin - unicode literals all string literals are handled as unicode (python only- verbose mode traces import statements - prints the version number and exits - skips the first line of the source program - cmd executes cmd as string - lib fl ff |
18,021 | execution environment the - option starts an interactive session immediately after program has finished execution and is useful for debugging the - option runs library module as script which executes inside the _main_ module prior to the execution of the main script the - and -oo options apply some optimization to byte-compiled files and are described in "modulespackagesand distribution "the - option omits the site initialization module described in the later section "site configuration files the - -ttand - options report additional warnings and debugging information - ignores the first line of program in the event that it' not valid python statement (for examplewhen the first line starts the python interpreter in scriptthe program name appears after all the interpreter options if no name is givenor the hyphen (-character is used as filenamethe interpreter reads the program from standard input if standard input is an interactive terminala banner and prompt are presented otherwisethe interpreter opens the specified file and executes its statements until an end-of-file marker is reached the - cmd option can be used to execute short programs in the form of command-line option--for examplepython - "print('hello world')command-line options appearing after the program name or hyphen (-are passed to the program in sys argvas described in the section "reading options and environment variablesin "input and output additionallythe interpreter reads the following environment variablestable interpreter environment variables environment variable description pythonpath pythonstartup pythonhome pythoninspect pythonunbuffered pythonioencoding colon-separated module search path file executed on interactive startup location of the python installation implies the - option implies the - option encoding and error handling for stdinstdoutand stderr this is string of the form "encoding[:errors]such as "utf- or "utf :ignoreimplies the - option implies the - option implies the - option implies the - option root directory for per-user site packages indicates to use case-insensitive matching for module names used by import pythondontwritebytecode pythonoptimize pythonnousersite pythonverbose pythonuserbase pythoncaseok pythonpath specifies module search path that is inserted into the beginning of sys pathwhich is described in pythonstartup specifies file to execute when the interpreter runs in interactive mode the pythonhome variable is used to set the location of the python installation but is rarely needed because python knows how lib fl ff |
18,022 | to find its own libraries and the site-packages directory where extensions are normally installed if single directory such as /usr/local is giventhe interpreter expects to find all files in that location if two directories are givensuch as /usr/local:/usrlocal/sparc-solaris- the interpreter searches for platform-independent files in the first directory and platform-dependent files in the second pythonhome has no effect if no valid python installation exists at the specified location the pythonioencoding environment setting might be of interest to users of python because it sets both the encoding and error handling of the standard / streams this might be important because python directly outputs unicode while running the interactive interpreter prompt thisin turncan cause unexpected exceptions merely while inspecting data for examplea 'jalape\xf oa traceback (most recent call last)file ""line in file "/tmp/lib/python /io py"line in write encoder encode(sfile "/tmp/lib/python /encodings/ascii py"line in encode return codecs ascii_encode(inputself errors)[ unicodeencodeerror'asciicodec can' encode character '\xf in position ordinal not in range( to fix thisyou can set the environment variable pythonioencoding to something such as 'ascii:backslashreplaceor 'utf- nowyou will get thisa 'jalape\xf oa 'jalape\xf oon windowssome of the environment variables such as pythonpath are additionally read from registry entries found in hkey_local_machine/software/python interactive sessions if no program name is given and the standard input to the interpreter is an interactive terminalpython starts in interactive mode in this modea banner message is printed and the user is presented with prompt in additionthe interpreter evaluates the script contained in the pythonstartup environment variable (if setthis script is evaluated as if it' part of the input program (that isit isn' loaded using an import statementone application of this script might be to read user configuration file such as pythonrc when interactive input is being acceptedtwo user prompts appear the prompt appears at the beginning of new statementthe prompt indicates statement continuation here' an examplefor in range( , )print lib fl ff |
18,023 | execution environment in customized applicationsyou can change the prompts by modifying the values of sys ps and sys ps on some systemspython may be compiled to use the gnu readline library if enabledthis library provides command historiescompletionand other additions to python' interactive mode by defaultthe output of commands issued in interactive mode is generated by printing the output of the built-in repr(function on the result this can be changed by setting the variable sys displayhook to function responsible for displaying results here' an example that truncates long resultsdef my_display( ) repr(xif len( print( [: ]+"+ [- ]elseprint(rsys displayhook my_display + range( [ finallyin interactive modeit is useful to know that the result of the last operation is stored in special variable (_this variable can be used to retrieve the result should you need to use it in subsequent operations here' an example the setting of the variable occurs in the displayhook(function shown previously if you redefine displayhook()your replacement function should also set if you want to retain that functionality launching python applications in most casesyou'll want programs to start the interpreter automaticallyrather than first having to start the interpreter manually on unixthis is done by giving the program execute permission and setting the first line of program to something like this#!/usr/bin/env python python code from this point on print "hello worldon windowsdouble-clicking pypywwpypycor pyo file automatically launches the interpreter normallyprograms run in console window unless they're renamed with pyw suffix (in which case the program runs silentlyif it' necessary to supply options to the interpreterpython can also be started from bat file for examplethis bat file simply runs python on script and passes any options supplied on the command prompt along to the interpreter:foo bat :runs foo py script and passes supplied command line options along (if anyc:\python \python exe :\pythonscripts\foo py % lib fl ff |
18,024 | site configuration files typical python installation may include number of third-party modules and packages to configure these packagesthe interpreter first imports the module site the role of site is to search for package files and to add additional directories to the module search path sys path in additionthe site module sets the default encoding for unicode string conversions the site module works by first creating list of directory names constructed from the values of sys prefix and sys exec_prefix as followssys prefixwindows only sys exec_prefixwindows only sys prefix 'lib/pythonvers/site-packages'sys prefix 'lib/site-python'sys exec_prefix 'lib/pythonvers/site-packages'sys exec_prefix 'lib/site-pythonin additionif enableda user-specific site packages directory may be added to this list (described in the next sectionfor each directory in the lista check is made to see whether the directory exists if soit' added to the sys path variable nexta check is made to see whether it contains any path configuration files (files with pth suffixa path configuration file contains list of directorieszip filesor egg files relative to the location of the path file that should be added to sys path for examplefoo package configuration file 'foo pthfoo bar each directory in the path configuration file must be listed on separate line comments and blank lines are ignored when the site module loads the fileit checks to see whether each directory exists if sothe directory is added to sys path duplicated items are added to the path only once after all paths have been added to sys pathan attempt is made to import module named sitecustomize the purpose of this module is to perform any additional (and arbitrarysite customization if the import of sitecustomize fails with an importerrorthe error is silently ignored the import of sitecustomize occurs prior to adding any user directories to sys path thusplacing this file in your own directory has no effect the site module is also responsible for setting the default unicode encoding by defaultthe encoding is set to 'asciihoweverthe encoding can be changed by placing code in sitecustomize py that calls sys setdefaultencoding(with new encoding such as 'utf- if you're willing to experimentthe source code of site can also be modified to automatically set the encoding based on the machine' locale settings per-user site packages normallythird-party modules are installed in way that makes them accessible to all users howeverindividual users can install modules and packages in per-user site directory on unix and macintosh systemsthis directory is found under ~local and is named something such as ~local/lib/python /site-packages on windows systemsthis directory is determined by the %appdataenvironment variablef lib fl ff |
18,025 | execution environment which is usually something similar to :\documents and settings\david beazley\application data within that folderyou will find "python\python site-packagesdirectory if you are writing your own python modules and packages that you want to use in librarythey can be placed in the per-user site directory if you are installing third-party modulesyou can manually install them in this directory by supplying the --user option to setup py for examplepython setup py install --user enabling future features new language features that affect compatibility with older versions of python are often disabled when they first appear in release to enable these featuresthe statement from _future_ import feature can be used here' an exampleenable new division semantics from _future_ import division when usedthis statement should appear as the first statement of module or program moreoverthe scope of _future_ import is restricted only to the module in which it is used thusimporting future feature does not affect the behavior of python' library modules or older code that requires the previous behavior of the interpreter to operate correctly currentlythe following features have been definedtable feature names in the _future_ module feature name description nested_scopes support for nested scopes in functions first introduced in python and made the default behavior in python support for generators first introduced in python and made the default behavior in python modified division semantics where integer division returns fractional result for example / yields instead of first introduced in python and is still an optional feature as of python this is the default behavior in python modified behavior of package-relative imports currentlywhen submodule of package makes an import statement such as import stringit first looks in the current directory of the package and then directories in sys path howeverthis makes it impossible to load modules in the standard library if package happens to use conflicting names when this feature is enabledthe statement import module is an absolute import thusa statement such as import string will always load the string module from the standard library first introduced in python and still disabled in python it is enabled in python support for context managers and the with statement first introduced in python and enabled by default in python use python print(function instead of the print statement first introduced in python and enabled by default in python generators division absolute_import with_statement print_function lib fl ff |
18,026 | it should be noted that no feature name is ever deleted from _future_ thuseven if feature is turned on by default in later python versionno existing code that uses that feature name will break program termination program terminates when no more statements exist to execute in the input programwhen an uncaught systemexit exception is raised (as generated by sys exit())or when the interpreter receives sigterm or sighup signal (on unixon exitthe interpreter decrements the reference count of all objects in all the currently known namespaces (and destroys each namespace as wellif the reference count of an object reaches zerothe object is destroyed and its _del_ (method is invoked it' important to note that in some cases the _del_ (method might not be invoked at program termination this can occur if circular references exist between objects (in which case objects may be allocated but accessible from no known namespacealthough python' garbage collector can reclaim unused circular references during executionit isn' normally invoked on program termination because there' no guarantee that _del_ (will be invoked at terminationit may be good idea to explicitly clean up certain objectssuch as open files and network connections to accomplish thisadd specialized cleanup methods (for exampleclose()to user-defined objects another possibility is to write termination function and register it with the atexit moduleas followsimport atexit connection open_connection("deaddot com"def cleanup()print "going away close_connection(connectionatexit register(cleanupthe garbage collector can also be invoked in this mannerimport atexitgc atexit register(gc collectone final peculiarity about program termination is that the _del_ method for some objects may try to access global data or methods defined in other modules because these objects may already have been destroyeda nameerror exception occurs in _del_ _and you may get an error such as the followingexception exceptions nameerror'cin <method bar _del_ of bar instance at ignored if this occursit means that _del_ has aborted prematurely it also implies that it may have failed in an attempt to perform an important operation (such as cleanly shutting down server connectionif this is concernit' probably good idea to perform an explicit shutdown step in your coderather than rely on the interpreter to destroy objects cleanly at program termination the peculiar nameerror exception can also be lib fl ff |
18,027 | execution environment eliminated by declaring default arguments in the declaration of the _del_ (methodimport foo class bar(object)def _del_ (selffoo=foo)foo bar(use something in module foo in some casesit may be useful to terminate program execution without performing any cleanup actions this can be accomplished by calling os _exit(statusthis function provides an interface to the low-level exit(system call responsible for killing the python interpreter process when it' invokedthe program immediately terminates without any further processing or cleanup lib fl ff |
18,028 | testingdebuggingprofilingand tuning nlike programs in languages such as or javapython programs are not processed by compiler that produces an executable program in those languagesthe compiler is the first line of defense against programming errors--catching mistakes such as calling functions with the wrong number of arguments or assigning improper values to variables (that istype checkingin pythonhoweverthese kinds of checks do not occur until program runs because of thisyou will never really know if your program is correct until you run and test it not only thatunless you are able to run your program in way that executes every possible branch of its internal control-flowthere is always some chance of hidden error just waiting to strike (fortunatelythis usually only happens few days after shippinghoweverto address these kinds of problemsthis covers techniques and library modules used to testdebugand profile python code at the endsome strategies for optimizing python code are discussed documentation strings and the doctest module if the first line of functionclassor module is stringthat string is known as documentation string the inclusion of documentation strings is considered good style because these strings are used to supply information to python software development tools for examplethe help(command inspects documentation stringsand python ides look at the strings as well because programmers tend to view documentation strings while experimenting in the interactive shellit is common for the strings to include short interactive examples for examplesplitter py def split(linetypes=nonedelimiter=none)"""splits line of text and optionally performs type conversion for examplesplit('goog '['goog'' '' 'split('goog ',[strintfloat]['goog' lib fl ff |
18,029 | testingdebuggingprofilingand tuning by defaultsplitting is performed on whitespacebut different delimiter can be selected with the delimiter keyword argumentsplit('goog, , ',delimiter=','['goog'' '' '""fields line split(delimiterif typesfields ty(valfor ty,val in zip(types,fieldsreturn fields common problem with writing documentation is keeping the documentation synchronized with the actual implementation of function for examplea programmer might modify function but forget to update the documentation to address this problemuse the doctest module doctest collects documentation stringsscans them for interactive sessionsand executes them as series of tests to use doctestyou typically create separate module for testing for exampleif the previous function is in file splitter pyyou would create file testsplitter py for testingas followstestsplitter py import splitter import doctest nfailntests doctest testmod(splitterin this codethe call to doctest testmod(moduleruns tests on the specified module and returns the number of failures and total number of tests executed no output is produced if all of the tests pass otherwiseyou will get failure report that shows the difference between the expected and received output if you want to see verbose output of the testsyou can use testmod(moduleverbose=trueas an alternative to creating separate testing filelibrary modules can test themselves by including code such as this at the end of the fileif _name_ =' _main_ 'test myself import doctest doctest testmod(with this codedocumentation tests will run if the file is run as the main program to the interpreter otherwisethe tests are ignored if the file is loaded with import doctest expects the output of functions to literally match the exact output you get in the interactive interpreter as resultit is quite sensitive to issues of white space and numerical precision for exampleconsider this functiondef half( )"""halves for examplehalf( ""return / lib fl ff |
18,030 | if you run doctest on this functionyou will get failure report such as this*********************************************************************file "half py"line in _main_ half failed examplehalf( expected got *********************************************************************to fix thisyou either need to make the documentation exactly match the output or need to pick better example in the documentation because using doctest is almost trivialthere is almost no excuse for not using it with your own programs howeverkeep in mind that doctest is not module you would typically use for exhaustive program testing doing so tends to result in excessively long and complicated documentation strings--which defeats the point of producing useful documentation ( user will probably be annoyed if he asks for help and the documentation lists examples covering all sorts of tricky corner casesfor this kind of testingyou want to use the unittest module lastthe doctest module has large number of configuration options that concerns various aspects of how testing is performed and how results are reported because these options are not required for the most common use of the modulethey are not covered here consult unit testing and the unittest module for more exhaustive program testinguse the unittest module with unit testinga developer writes collection of isolated test cases for each element that makes up program (for exampleindividual functionsmethodsclassesand modulesthese tests are then run to verify correct behavior of the basic building blocks that make up larger programs as programs grow in sizeunit tests for various components can be combined to create large testing frameworks and testing tools this can greatly simplify the task of verifying correct behavior as well as isolating and fixing problems when they do occur use of this module can be illustrated by the code listing in the previous sectionsplitter py def split(linetypes=nonedelimiter=none)"""splits line of text and optionally performs type conversion ""fields line split(delimiterif typesfields ty(valfor ty,val in zip(types,fieldsreturn fields lib fl ff |
18,031 | testingdebuggingprofilingand tuning if you wanted to write unit tests for testing various aspects of the split(functionyou would create separate module testsplitter pylike thistestsplitter py import splitter import unittest unit tests class testsplitfunction(unittest testcase)def setup(self)perform set up actions (if anypass def teardown(self)perform clean-up actions (if anypass def testsimplestring(self) splitter split('goog 'self assertequal( ,['goog',' ',' ']def testtypeconvert(self) splitter split('goog ',[strintfloat]self assertequal( ,['goog' ]def testdelimiter(self) splitter split('goog, , ',delimiter=','self assertequal( ,['goog',' ',' ']run the unittests if _name_ =' _main_ 'unittest main(to run testssimply run python on the file testsplitter py here' an examplepython testsplitter py ran tests in ok basic use of unittest involves defining class that inherits from unittest testcase within this classindividual tests are defined by methods starting with the name 'test'--for example'testsimplestring''testtypeconvert'and so on (it is important to emphasize that the names are entirely up to you as long as they start with 'testwithin each testvarious assertions are used to check for different conditions an instancetof unittest testcase has the following methods that are used when writing tests and for controlling the testing processt setup(called to perform set-up steps prior to running any of the testing methods teardown(called to perform clean-up actions after running the tests lib fl ff |
18,032 | assert_(expr [msg] failunless(expr [msg]signals test failure if expr evaluates as false msg is message string giving an explanation for the failure (if anyt assertequal(xy [,msg] failunlessequal(xy [msg]signals test failure if and are not equal to each other msg is message explaining the failure (if anyt assertnotequal(xy [msg] failifequal(xy[msg]signals test failure if and are equal to each other msg is message explaining the failure (if anyt assertalmostequal(xy [places [msg]] failunlessalmostequal(xy[places [msg]]signals test failure if numbers and are not within places decimal places of each other this is checked by computing the difference of and and rounding the result to the given number of places if the result is zerox and are almost equal msg is message explaining the failure (if anyt assertnotalmostequal(xy[places [msg]] failifalmostequal(xy [places [msg]]signals test failure if and are not at least places decimal places apart msg is message explaining the failure (if anyt assertraises(exccallablet failunlessraises(exccallablesignals test failure if the callable object callable does not raise the exception exc remaining arguments are passed as arguments to callable multiple exceptions can be checked by using tuple of exceptions as exc failif(expr [msg]signals test failure if expr evaluates as true msg is message explaining the failure (if anyt fail([msg]signals test failure msg is message explaining the failure (if anyt failureexception this attribute is set to the last exception value caught in test this may be useful if you not only want to check that an exception was raisedbut that the exception raises an appropriate value--for exampleif you wanted to check the error message generated as part of raising an exception lib fl ff |
18,033 | testingdebuggingprofilingand tuning it should be noted that the unittest module contains large number of advanced customization options for grouping testscreating test suitesand controlling the environment in which tests run these features are not directly related to the process of writing tests for your code (you tend to write testing classes as shown independently of how tests actually get executedconsult the documentation at library/unittest html for more information on how to organize tests for larger programs the python debugger and the pdb module python includes simple command-based debugger which is found in the pdb module the pdb module supports post-mortem debugginginspection of stack framesbreakpointssingle-stepping of source linesand code evaluation there are several functions for invoking the debugger from program or from the interactive python shell run(statement [globals [locals]]executes the string statement under debugger control the debugger prompt will appear immediately before any code executes typing 'continuewill force it to run globals and locals define the global and local namespacesrespectivelyin which the code runs runeval(expression [globals [locals]]evaluates the expression string under debugger control the debugger prompt will appear before any code executesso you will need to type 'continueto force it to execute as with run(on successthe value of the expression is returned runcall(function [argument]calls function within the debugger function is callable object additional arguments are supplied as the arguments to function the debugger prompt will appear before any code executes the return value of the function is returned upon completion set_trace(starts the debugger at the point at which this function is called this can be used to hard-code debugger breakpoint into specific code location post_mortem(tracebackstarts post-mortem debugging of traceback object traceback is typically obtained using function such as sys exc_info(pm(enters post-mortem debugging using the traceback of the last exception of all of the functions for launching the debuggerthe set_trace(function may be the easiest to use in practice if you are working on complicated application but you have detected problem in one part of ityou can insert set_trace(call into the code and simply run the application when encounteredthis will suspend the program and go directly to the debugger where you can inspect the execution environment execution resumes after you leave the debugger lib fl ff |
18,034 | debugger commands when the debugger startsit presents (pdbprompt such as the followingimport pdb import buggymodule pdb run('buggymodule start()'( )?((pdb(pdbis the debugger prompt at which the following commands are recognized note that some commands have short and long form in this caseparentheses are used to indicate both forms for exampleh(elpmeans that either or help is acceptable [!]statement executes the (one-linestatement in the context of the current stack frame the exclamation point may be omittedbut it must be used to avoid ambiguity if the first word of the statement resembles debugger command to set global variableyou can prefix the assignment command with "globalcommand on the same line(pdbglobal list_optionslist_options ['- '(pdba(rgsprints the argument list of the current function alias [name [command]creates an alias called name that executes command within the command stringthe substrings '% ','% 'and so forth are replaced by parameters when the alias is typed '%*is replaced by all parameters if no command is giventhe current alias list is shown aliases can be nested and can contain anything that can be legally typed at the pdb prompt here' an exampleprint instance variables (usage "pi classinst"alias pi for in % _dict_ keys()print "% ", ,"=",% _dict_ [kprint instance variables in self alias ps pi self (reak[loc [condition]sets breakpoint at location loc loc either specifies specific filename and line number or is the name of function within module the following syntax is usedsetting description filename: function module function line number in the current file line number in another file function name in the current module function name in module if loc is omittedall the current breakpoints are printed condition is an expression that must evaluate to true before the breakpoint is honored all breakpoints are assigned lib fl ff |
18,035 | testingdebuggingprofilingand tuning numbers that are printed as output upon the completion of this command these numbers are used in several other debugger commands that follow cl(ear[bpnumber [bpnumber ]clears list of breakpoint numbers if breakpoints are specifiedall breaks are cleared commands [bpnumbersets series of debugger commands to execute automatically when the breakpoint bpnumber is encountered when listing the commands to executesimply type them on the subsequent lines and use end to mark the end of the command sequence if you include the continue commandthe execution of the program will resume automatically when the breakpoint is encountered if bpnumber is omittedthe last breakpoint set is used condition bpnumber [conditionplaces condition on breakpoint condition is an expression that must evaluate to true before the breakpoint is recognized omitting the condition clears any previous condition (ont(inue)continues execution until the next breakpoint is encountered disable [bpnumber [bpnumber ]disables the set of specified breakpoints unlike with clearthey can be reenabled later (ownmoves the current frame one level down in the stack trace enable [bpnumber [bpnumber ]enables specified set of breakpoints (elp[commandshows the list of available commands specifying command returns help for that command ignore bpnumber [countignores breakpoint for count executions (umplineno sets the next line to execute this can only be used to move between statements in the same execution frame moreoveryou can' jump into certain statementssuch as statements in the middle of loop (ist[first [last]lists source code without argumentsthis command lists lines around the current line ( lines before and lines afterwith one argumentit lists lines around that line with two argumentsit lists lines in given range if last is less than firstit' interpreted as count lib fl ff |
18,036 | (extexecutes until the next line of the current function skips the code contained in function calls expression evaluates the expression in the current context and prints its value pp expression the same as the commandbut the result is formatted using the pretty-printing module (pprintq(uitquits from the debugger (eturnruns until the current function returns run [argsrestarts the program and uses the command-line arguments in args as the new setting of sys argv all breakpoints and other debugger settings are preserved (tepexecutes single source line and stops inside called functions tbreak [loc [condition]sets temporary breakpoint that' removed after its first hit (pmoves the current frame one level up in the stack trace unalias name deletes the specified alias until resumes execution until control leaves the current execution frame or until line number greater than the current line number is reached for exampleif the debugger was stopped at the last line in loop bodytyping until will execute all of the statements in the loop until the loop is finished (hereprints stack trace debugging from the command line an alternative method for running the debugger is to invoke it on the command line here' an examplepython - pdb someprogram py lib fl ff |
18,037 | testingdebuggingprofilingand tuning in this casethe debugger is launched automatically at the beginning of program startup where you are free to set breakpoints and make other configuration changes to make the program runsimply use the continue command for exampleif you wanted to debug the split(function from within program that used ityou might do thispython - pdb someprogram py /users/beazley/code/someprogram py( )(-import splitter (pdbb splitter split breakpoint at /users/beazley/code/splitter py: (pdbc /users/beazley/code/splitter py( )split(-fields line split(delimiter(pdbconfiguring the debugger if pdbrc file exists in the user' home directory or in the current directoryit' read in and executed as if it had been typed at the debugger prompt this can be useful for specifying debugging commands that you want to execute each time the debugger is started (as opposed to having to interactively type the commands each timeprogram profiling the profile and cprofile modules are used to collect profiling information both modules work in the same waybut cprofile is implemented as extensionis significantly fasterand is more modern either module is used to collect both coverage information (that iswhat functions get executedas well as performance statistics the easiest way to profile program is to execute it from the command line as followspython - cprofile someprogram py alternativelythe following function in the profile module can be usedrun(command [filename]executes the contents of command using the exec statement under the profiler filename is the name of file in which raw profiling data is saved if it' omitteda report is printed to standard output the result of running the profiler is report such as the following function calls ( primitive callsin cpu seconds ordered bystandard name ncalls tottime percall cumtime percall filename:lineno(function : (? / book py: (process book py: (? exceptions py: ( _init_ profile: (execfile('book py') profile: (profilerdifferent parts of the report generated by run(are interpreted as followsf lib fl ff |
18,038 | section description number of nonrecursive function calls total number of calls (including self-recursiontime spent in this function (not counting subfunctionstottime/ncalls total time spent in the function percall cumtime/(primitive callsfilename:lineno(functionlocation and name of each function primitive calls ncalls tottime percall cumtime when there are two numbers in the first column (for example" / ")the latter is the number of primitive calls and the former is the actual number of calls simply inspecting the generated report of the profiler is often enough for most applications of this module--for exampleif you simply want to see how your program is spending its time howeverif you want to save the data and analyze it furtherthe pstats module can be used consult more details about saving and analyzing the profile data tuning and optimization this section covers some general rules of thumb that can be used to make python programs run faster and use less memory the techniques described here are by no means exhaustive but should give programmers some ideas when looking at their own code making timing measurements if you simply want to time long-running python programthe easiest way to do it is often just to run it until the control of something like the unix time command alternativelyif you have block of long-running statements you want to timeyou can insert calls to time clock(to get current reading of the elapsed cpu time or calls to time time(to read the current wall-clock time for examplestart_cpu time clock(start_realtime time(statements statements end_cpu time clock(end_real time time(print("% real seconds(end_real start_real)print("% cpu seconds(end_cpu start_cpu)keep in the mind that this technique really works only if the code to be timed runs for reasonable period of time if you have fine-grained statement you want to benchmarkyou can use the timeit(code [setup]function in the timeit module for examplefrom timeit import timeit timeit('math sqrt( )','import math' timeit('sqrt( )','from math import sqrt' lib fl ff |
18,039 | testingdebuggingprofilingand tuning in this examplethe first argument to timeit(is the code you want to benchmark the second argument is statement that gets executed once in order to set up the execution environment the timeit(function runs the supplied statement one million times and reports the execution time the number of repetitions can be changed by supplying number=count keyword argument to timeit(the timeit module also has function repeat(that can be used to make measurements this function works the same way as timeit(except that it repeats the timing measurement three times and returns list of the results for examplefrom timeit import repeat repeat('math sqrt( )','import math'[ when making performance measurementit is common to refer to the associated speedupwhich usually refers to the original execution time divided by the new execution time for examplein the previous timing measurementsusing sqrt( instead of math sqrt( represents speedup of or about sometimes this gets reported as percentage by saying the speedup is about percent making memory measurements the sys module has function getsizeof(that can be used to investigate the memory footprint (in bytesof individual python objects for exampleimport sys sys getsizeof( sys getsizeof("hello world" sys getsizeof([ , , , ] sum(sys getsizeof(xfor in [ , , , ] for containers such as liststuplesand dictionariesthe size that gets reported is just for the container object itselfnot the cumulative size of all objects contained inside of it for instancein the previous examplethe reported size of the list [ , , , is actually smaller than the space required for four integers (which are bytes eachthis is because the contents of the list are not included in the total you can use sum(as shown here to calculate the total size of the list contents be aware that the getsizeof(function is only going to give you rough idea of overall memory use for various objects internallythe interpreter aggressively shares objects via reference counting so the actual memory consumed by an object might be far less than you first imagine alsogiven that extensions to python can allocate memory outside of the interpreterit may be difficult to precisely get measurement of overall memory use thusa secondary technique for measuring the actual memory footprint is to inspect your running program from an operating system process viewer or task manager franklya better way to get handle on memory use may be to sit down and be analytical about it if you know your program is going to allocate various kinds of data structures and you know what kinds of data will be stored in those structures (that isintsfloatsstringsand so on)you can use the results of the getsizeof(function to lib fl ff |
18,040 | obtain figures for calculating an upper bound on your program' memory footprint--or at the very leastyou can get enough information to carry out "back of the envelopeestimate disassembly the dis module can be used to disassemble python functionsmethodsand classes into low-level interpreter instructions the module defines function dis(that can be used like thisfrom dis import dis dis(split load_fast load_attr load_fast call_function store_fast (line (split (delimiter (fields load_global jump_if_false pop_top (types (to build_list dup_top store_fast load_global load_global load_fast call_function get_iter for_iter unpack_sequence store_fast store_fast load_fast load_fast load_fast call_function list_append jump_absolute delete_fast store_fast jump_forward pop_top >>> > load_fast return_value ( [ ] (zip (types (fields (to (ty (val ( [ ] (ty (val ( [ ] (fields (to (fieldsexpert programmers can use this information in two ways firsta disassembly will show you exactly what operations are involved in executing function with careful studyyou might spot opportunities for making speedups secondif you are programming with threadseach line printed in the disassembly represents single interpreter operation--each of which has atomic execution thusif you are trying to track down tricky race conditionthis information might be useful lib fl ff |
18,041 | testingdebuggingprofilingand tuning tuning strategies the following sections outline few optimization strategies thatin the opinion of the authorhave proven to be useful with python code understand your program before you optimize anythingknow that speedup obtained by optimizing part of program is directly related to that part' total contribution to the execution time for exampleif you optimize function by making it run times as fast but that function only contributes to percent of the program' total execution timeyou're only going to get an overall speedup of about %- depending on the effort involved in making the optimizationthis may or may not be worth it it is always good idea to first use the profiling module on code you intend to optimize you really only want to focus on functions and methods where your program spends most of its timenot obscure operations that are called only occasionally understand algorithms poorly implemented ( log nalgorithm will outperform the most finely tuned ( algorithm don' optimize inefficient algorithms--look for better algorithm first use the built-in types python' built-in tuplelistsetand dictionary types are implemented entirely in and are the most finely tuned data structures in the interpreter you should actively use these types to store and manipulate data in your program and resist the urge to build your own custom data structures that mimic their functionality (that isbinary search treeslinked listsand so onhaving said thatyou should still look more closely at types in the standard library some library modules provide new types that outperform the built-ins at certain tasks for instancethe collection deque type provides similar functionality to list but has been highly optimized for the insertion of new items at both ends listin contrastis only efficient when appending items at the end if you insert items at the frontall of the other elements need to be shifted in order to make room the time required to do this grows as the list gets larger and larger just to give you an idea of the differencehere is timing measurement of inserting one million items at the front of list and dequefrom timeit import timeit timeit(' appendleft( )''import collectionss collections deque()'number= timeit(' insert( , )'' []'number= don' add layers any time you add an extra layer of abstraction or convenience to an object or functionyou will slow down your program howeverthere is also trade-off between usability and performance for instancethe whole point of adding an extra layer is often to simplify codingwhich is also good thing lib fl ff |
18,042 | to illustrate with simple exampleconsider program that makes use of the dict(function to create dictionaries with string keys like thiss dict(name='goog',shares= ,price= {'name':'goog''shares': 'price': programmer might create dictionaries in this way to save typing (you don' have to put quotes around the key nameshoweverthis alternative way of creating dictionary also runs much more slowly because it adds an extra function call timeit(" {'name':'goog','shares': ,'price': }" timeit(" dict(name='goog',shares= ,price= )" if your program creates millions of dictionaries as it runsthen you should know that the first approach is faster with few exceptionsany feature that adds an enhancement or changes the way in which an existing python object works will run more slowly know how classes and instances build upon dictionaries user-defined classes and instances are built using dictionaries because of thisoperations that look upsetor delete instance data are almost always going to run more slowly than directly performing these operations on dictionary if all you are doing is building simple data structure for storing dataa dictionary may be more efficient choice than defining class just to illustrate the differencehere is simple class that represents holding of stockclass stock(object)def _init_ (self,name,shares,price)self name name self shares shares self price price if you compare the performance of using this class against dictionarythe results are interesting firstlet' compare the performance of simply creating instancesfrom timeit import timeit timeit(" stock('goog', , )","from stock import stock" timeit(" {'name'goog''shares 'price }" herethe speedup of creating new objects is about nextlet' look at the performance of performing simple calculationtimeit(" shares* price""from stock import stocks stock('goog', , )" timeit(" ['shares']* ['price']"" {'name'goog''shares 'price }" herethe speedup is about the lesson here is that just because you can define new object using classit' not the only way to work with data tuples and dictionaries are often good enough using them will make your program run more quickly and use less memory lib fl ff |
18,043 | testingdebuggingprofilingand tuning use _slots_ if your program creates large number of instances of user-defined classesyou might consider using the _slots_ attribute in class definition for exampleclass stock(object) _slots_ ['name','shares','price'def __init__(self,name,shares,price)self name name self shares shares self price price _slots_ is sometimes viewed as safety feature because it restricts the set of attribute names howeverit is really more of performance optimization classes that use _slots_ don' use dictionary for storing instance data (insteada more efficient internal data structure is usedsonot only will instances use far less memorybut access to instance data is also more efficient in some casessimply adding _slots_ will make program run noticeably faster without making any other changes there is one caution with using _slots_ _however adding this feature to class may cause other code to break mysteriously for exampleit is generally well-known that instances store their data in dictionary that can be accessed as the _dict_ attribute when slots are definedthis attribute doesn' exist so any code that relies on _dict_ will fail avoid the operator whenever you use the to look up an attribute on an objectit always involves name lookup for examplewhen you say namethere is lookup for the variable name "xin the environment and then lookup for the attribute "nameon for user-defined objectsattribute lookup may involve looking in the instance dictionarythe class dictionaryand the dictionaries of base-classes for calculations involving heavy use of methods or module lookupsit is almost always better to eliminate the attribute lookup by putting the operation you want to perform into local variable first for exampleif you were performing lot of square root operationsit is faster to use 'from math import sqrtand 'sqrt( )rather than typing 'math sqrt( )in the first part of this sectionwe saw that this approach resulted in speedup of about obviously you should not try to eliminate attribute lookups everywhere in your program because it will make your code very difficult to read howeverfor performance-critical sectionsthis is useful technique use exceptions to handle uncommon cases to avoid errorsyou might be inclined to add extra checks to program for exampledef parse_header(line)fields line split(":"if len(fields! raise runtimeerror("malformed header"headervalue fields return header lower()value strip( lib fl ff |
18,044 | howeveran alternative way to handle errors is to simply let the program generate an exception and to catch it for exampledef parse_header(line)fields line split(":"tryheadervalue fields return header lower()value strip(except valueerrorraise runtimeerror("malformed header"if you benchmark both versions on properly formatted linethe second version of code runs about percent faster setting up try block for code that normally doesn' raise an exceptions runs more quickly than executing an if statement avoid exceptions for common cases don' write code that uses exception handling for the common case for examplesuppose you had program that performed lot of dictionary lookupsbut most of these lookups were for keys that didn' exist nowconsider two approaches to performing lookupapproach perform lookup and catch an exception tryvalue items[keyexcept keyerrorvalue none approach check if the key exists and perform lookup if key in itemsvalue items[keyelsevalue none in simple performance measurement where the key is not foundthe second approach runs more than times fasterin case you were wonderingthis latter approach also runs almost twice as fast as using items get(keybecause the in operator is faster to execute than method call embrace functional programming and iteration list comprehensionsgenerator expressionsgeneratorscoroutinesand closures are much more efficient than most python programmers realize for data processing especiallylist comprehensions and generator expressions run significantly more quickly than code that manually iterates over data and carries out similar operations these operations also run much more quickly than legacy python code that uses functions such as map(and filter(generators can be used to write code that not only runs fastbut which makes efficient use of memory use decorators and metaclasses decorators and metaclasses are features that are used to modify functions and classes howeverbecause they operate at the time of function or class definitionthey can be used in ways that lead to improved performance--especially if program has many optional features that might be turned on or off "functions and functional programming,has an example of using decorator to enable logging of functionsbut in way that does not impact performance when logging is disabled lib fl ff |
18,045 | lib fl ff |
18,046 | the python library built-in functions python runtime services mathematics data structuresalgorithmsand utilities string and text handling python database access file and directory handling operating system services threads and concurrency network programming and sockets internet application programming web programming internet data handling and encoding miscellaneous library modules lib fl ff |
18,047 | lib fl ff |
18,048 | built-in functions and exceptions his describes python' built-in functions and exceptions much of this material is covered less formally in earlier of this book this merely consolidates all this information into one section and expands upon some of the more subtle features of certain functions alsopython includes number of built-in functions that are considered to be obsolete and which have been removed from python those functions are not documented here--instead the focus is on modern functionality built-in functions and types certain typesfunctionsand variables are always available to the interpreter and can be used in any source module although you don' need to perform any extra imports to access these functionsthey are contained in module _builtin_ in python and in module builtins in python within other modules that you importthe variable _builtins_ is also bound to this module abs(xreturns the absolute value of all(sreturns true if all of the values in the iterable evaluate as true any(sreturns true if any of the values in the iterable evaluate as true ascii(xcreates printable representation of the object just like the repr()but only uses ascii characters in the result non-ascii characters are turned into appropriate escape sequences this can be used to view unicode strings in terminal or shell that doesn' support unicode python only lib fl ff |
18,049 | built-in functions and exceptions basestring this is an abstract data type that is the superclass of all strings in python (str and unicodeit is only used for type testing of strings for exampleisinstance( ,basestringreturns true if is either kind of string python only bin(xreturns string containing the binary representation of the integer bool([ ]type representing boolean values true and false if used to convert xit returns true if evaluates to true using the usual truth-testing semantics (that isnonzero numbernon-empty listand so onotherwisefalse is returned false is also the default value returned if bool(is called without any arguments the bool class inherits from int so the boolean values true and false can be used as integers with values and in mathematical calculations bytearray([ ] type representing mutable array of bytes when creating an instancex may be an iterable sequence of integers in the range to an -bit string or bytes literalor an integer that specifies the size of the byte array (in which case every entry will be initialized to bytearray object looks like an array of integers if you perform lookup such as [ ]you will get an integer value representing the byte value at index assignments such as [iv also require to be an integer byte value howevera bytearray also provides all of the operations normally associated with strings (that isslicingfind()split()replace()and so onwhen using these string operationsyou should be careful to preface all string literals with in order to indicate that you're working with bytes for exampleif you wanted to split byte array into fields using comma character separatoryou would use split( ','not split(','the result of these operations is always new bytearray objectsnot strings to turn bytearray into stringuse the decode(encodingmethod an encoding of 'latin- will directly turn bytearray of -bit characters into string without any modification of the underlying character values bytearray( ,encodingan alternative calling convention for creating bytearray instance from characters in string where encoding specifies the character encoding to use in the conversion bytes([ ] type representing an immutable array of bytes in python this is an alias for str(which creates standard -bit string of characters in python bytes is completely separate type that is an immutable version of the bytearray type described earlier in that casethe argument has the same interpretation and can be used in the same manner one portability caution is that even though bytes is defined in python the resulting object does not behave consistently with python for exampleif is an instance created by bytes()then [ireturns character string in python but returns an integer in python lib fl ff |
18,050 | bytes(sencodingan alternative calling convention for creating bytes instance from characters in string where encoding specifies the character encoding to use python only chr(xconverts an integer valuexinto one-character string in python must be in the range < < and in python must represent valid unicode code point if is out of rangea valueerror exception is raised classmethod(functhis function creates class method for the function func it is typically only used inside class definitions where it is implicitly invoked by the @classmethod decorator unlike normal methoda class method receives the class as the first argumentnot an instance for exampleif you had an objectfthat is an instance of class fooinvoking class method on will pass the class foo as the first argument to the methodnot the instance cmp(xycompares and and returns negative number if yor if = any two objects can be comparedalthough the result may be meaningless if the two objects have no meaningful comparison method defined (for examplecomparing number with file objectin certain circumstancessuch comparisons may also raise an exception compile(stringfilenamekind [flags [dont_inherit]]compiles string into code object for use with exec(or eval(string is string containing valid python code if this code spans multiple linesthe lines must be terminated by single newline ('\ 'and not platform-specific variants (for example'\ \non windowsfilename is string containing the name of the file in which the string was defined kind is 'execfor sequence of statements'evalfor single expressionor 'singlefor single executable statement the flags parameter determines which optional features (associated with the _future_ moduleare enabled features are specified using the bitwise or of flags defined in the _future_ module for exampleif you wanted to enable new division semanticsyou would set flags to _future_ division compiler_flag if flags is omitted or set to the code is compiled with whatever features are currently in effect if flags is suppliedthe features specified are added to those features already in effect if dont_inherit is setonly those features specified in flags are enabled--features currently enabled are ignored complex([real [imag]]type representing complex number with real and imaginary componentsreal and imagwhich can be supplied as any numeric type if imag is omittedthe imaginary component is set to zero if real is passed as stringthe string is parsed and converted to complex number in this caseimag should be omitted if no arguments are given is returned delattr(objectattrdeletes an attribute of an object attr is string same as del object attr lib fl ff |
18,051 | built-in functions and exceptions dict([ ]or dict(key value key value type representing dictionary if no argument is givenan empty dictionary is returned if is mapping object (such as dictionary) new dictionary having the same keys and same values as is returned for exampleif is dictionarydict(msimply makes shallow copy of it if is not mappingit must support iteration in which sequence of (key,valuepairs is produced these pairs are used to populate the dictionary dict(can also be called with keyword arguments for exampledict(foo= bar= creates the dictionary 'foo 'bar dir([object]returns sorted list of attribute names if object is moduleit contains the list of symbols defined in that module if object is type or class objectit returns list of attribute names the names are typically obtained from the object' _dict_ attribute if definedbut other sources may be used if no argument is giventhe names in the current local symbol table are returned it should be noted that this function is primarily used for informational purposes (for exampleused interactively at the command lineit should not be used for formal program analysis because the information obtained may be incomplete alsouser-defined classes can define special method _dir_ (that alters the result of this function divmod(abreturns the quotient and remainder of long division as tuple for integersthe value ( /ba bis returned for floats(math floor( ) bis returned this function may not be called with complex numbers enumerate(iter[initial valuegiven an iterable objectiterreturns new iterator (of type enumeratethat produces tuples containing count and the value produced from iter for exampleif iter produces abcthen enumerate(iterproduces ( , )( , )( ,ceval(expr [globals [locals]]evaluates an expression expr is string or code object created by compile(globals and locals are mapping objects that define the global and local namespacesrespectivelyfor the operation if omittedthe expression is evaluated in the namespace of the caller it is most common for globals and locals to be specified as dictionariesbut advanced applications can supply custom mapping objects exec(code [global [locals]]executes python statements code is stringa fileor code object created by compile(globals and locals define the global and local namespacesrespectivelyfor the operation if omittedthe code is executed in the namespace of the caller if no global or local dictionaries are giventhe behavior of this function is little muddled between python versions in python exec is actually implemented as special language statementwhereas python implements it as standard library function subtle side effect of this implementation difference is that in python code evaluated by exec can freely mutate local variables in the caller' namespace in python you can execute code that makes such changesbut they don' seem to have any lasting effect beyond the exec(call itself this is because python uses locals(to obtain the local namespace if one isn' supplied as you will note in the documentation for locals()the returned dictionary is only safe to inspectnot modify lib fl ff |
18,052 | filter(functioniterablein python this creates list consisting of the objects from iterable for which function evaluates to true in python the result is an iterator that produces this result if function is nonethe identity function is used and all the elements of iterable that are false are removed iterable can be any object that supports iteration as general ruleit is significantly faster to use generator expression or list comprehension to filter data (refer to float([ ]type representing floating-point number if is numberit is converted to float if is stringit is parsed into float if no argument is supplied is returned format(value [format_spec]converts value to formatted string according to the format specification string in format_spec this operation invokes value _format_ ()which is free to interpret the format specification as it sees fit for simple types of datathe format specifier typically includes an alignment character of ''or '^' number (which indicates the field width)and character code of ' '' 'or 'sfor integerfloating pointor string valuesrespectively for examplea format specification of 'dformats an integera specification of ' dright aligns an integer in an -character field and '< dleft aligns an integer in an -character field more details on format(and format specifiers can be found in "types and objects,and "operators and expressions frozenset([items]type representing an immutable set object populated with values taken from items that must be an iterable the values must also be immutable if no argument is givenan empty set is returned getattr(objectname [,default]returns the value of named attribute of an object name is string containing the attribute name default is an optional value to return if no such attribute exists otherwiseattributeerror is raised same as object name globals(returns the dictionary of the current module that represents the global namespace when called inside another function or methodit returns the global namespace of the module in which the function or method was defined hasattr(objectnamereturns true if name is the name of an attribute of object false is returned otherwise name is string hash(objectreturns an integer hash value for an object (if possiblethe hash value is primarily used in the implementation of dictionariessetsand other mapping objects the hash value is the same for any two objects that compare as equals mutable objects don' define hash valuealthough user-defined classes can define method _hash_ (to support this operation lib fl ff |
18,053 | built-in functions and exceptions help([object]calls the built-in help system during interactive sessions object may be string representing the name of moduleclassfunctionmethodkeywordor documentation topic if it is any other kind of objecta help screen related to that object will be produced if no argument is suppliedan interactive help tool will start and provide more information hex(xcreates hexadecimal string from an integer id(objectreturns the unique integer identity of object you should not interpret the return value in any way (that isas memory locationinput([prompt]in python this prints promptreads line of inputand processes it through eval((that isit' the same as eval(raw_input(prompt)in python prompt is printed to standard output and single line of input is read without any kind of evaluation or modification int( [,base]type representing an integer if is numberit is converted to an integer by truncating toward if it is stringit is parsed into an integer value base optionally specifies base when converting from string in python long integer is created if the value exceeds the -bit range of the int type isinstance(objectclassobjreturns true if object is an instance of classobjis subclass of classobjor belongs to an abstract base class classobj the classobj parameter can also be tuple of possible types or classes for exampleisinstance( (list,tuple)returns true if is tuple or list issubclass(class class returns true if class is subclass of (derived fromclass or if class is registered with an abstract base class class class can also be tuple of possible classesin which case each class will be checked note that issubclass(aais true iter(object [,sentinel]returns an iterator for producing items in object if the sentinel parameter is omittedthe object must either provide the method _iter_ ()which creates an iteratoror implement _getitem_ ()which accepts integer arguments starting at if sentinel is specifiedobject is interpreted differently insteadobject should be callable object that takes no parameters the returned iterator object will call this function repeatedly until the returned value is equal to sentinelat which point iteration will stop typeerror will be generated if object does not support iteration len(sreturns the number of items contained in should be listtuplestringsetor dictionary typeerror is generated if is an iterable such as generator lib fl ff |
18,054 | list([items]type representing list items may be any iterable objectthe values of which are used to populate the list if items is already lista copy is made if no argument is givenan empty list is returned locals(returns dictionary corresponding to the local namespace of the caller this dictionary should only be used to inspect the execution environment--it is not safe to modify the contents of this dictionary long([ [base]]type representing long integers in python if is numberit is converted to an integer by truncating toward if is stringit is parsed into long value if no argument is giventhis function returns for portabilityyou should avoid direct use of long using int(xwill create long as necessary for type checkinguse isinstance(xnumbers integralto check if is any integer type map(functionitemsin python this applies function to every item of items and returns list of results in python an iterator producing the same results is created if multiple input sequences are suppliedfunction is assumed to take that many argumentswith each argument taken from different sequence the behavior when processing multiple input sequences differs between python and python in python the result is the same length as the longest input sequence with none used as padding value when the shorter input sequences are exhausted in python the result is only as long as the shortest sequence the functionality provided by map(is almost always better expressed using generator expression or list comprehension (both of which provide better performancefor examplemap(functionscan usually be replaced by [function(xfor in smax( [args]for single argumentsthis function returns the maximum value of the items in swhich may be any iterable object for multiple argumentsit returns the largest of the arguments min( [args]for single argumentsthis function returns the minimum value of the items in swhich may be any iterable object for multiple argumentsit returns the smallest of the arguments next( [default]returns the next item from the iterator if the iterator has no more itemsa stopiteration exception is raised unless value is supplied to the default argument in that casedefault is returned instead for portabilityyou should always use this function instead of calling next(directly on an iterator in python the name of the underlying iterator method changed to _next_ (if you write your code to use the next(functionyou won' have to worry about this difference lib fl ff |
18,055 | built-in functions and exceptions object(the base class for all objects in python you can call it to create an instancebut the result isn' especially interesting oct(xconverts an integerxto an octal string open(filename [mode [bufsize]]in python opens the file filename and returns new file object (refer to "input and output"mode is string that indicates how the file should be opened'rfor reading'wfor writingand 'afor appending second character 'tor 'bis used to indicate text-mode (the defaultor binary mode for example'ror 'rtopens file in text modewhereas 'rbopens file in binary mode an optional '+can be added to the mode to open the file for updating (which allows both reading and writinga mode of ' +truncates the file to zero length if it already exists mode of ' +or ' +opens the file for both reading and writing but leaves the original contents intact when the file is opened if mode of 'uor 'ruis specifiedthe file is opened in universal newline mode in this modeall variants of newline ('\ ''\ ''\ \ 'are converted to the standard '\ncharacter if the mode is omitteda mode of 'rtis assumed the bufsize argument specifies the buffering behaviorwhere is unbuffered is line bufferedand any other positive number indicates an approximate buffer size in bytes negative number indicates that the system default buffering should be used (this is the default behavioropen(filename [mode [bufsize [encoding [errors [newline [closefd]]]]]]in python this opens the file filename and returns file object the first three arguments have the same meaning as for the python version of open(described earlier encoding is an encoding name such as 'utf- errors is the error handling policy and is one of 'strict''ignore''replace''backslashreplace'or 'xmlcharrefreplacenewline controls the behavior of universal newline mode and is set to none'''\ ''\ 'or '\ \nclosefd is boolean flag that specifies whether the underlying file descriptor is closed when the close(method executes unlike python different kinds of objects are returned depending on the selected / mode for exampleif you open file in binary modeyou get an object where / operations such as read(and write(operate on byte arrays instead of strings file / is one area where there are significant differences between python and consult appendix "python ,for more details ord(creturns the integer ordinal value of single characterc for ordinary charactersa value in the range [ , is returned for single unicode charactersa value in the range [ , is usually returned in python may also be unicode surrogate pairin which case it is converted into the appropriate unicode code point pow(xy [ ]returns * if is suppliedthis function returns ( *yz if all three arguments are giventhey must be integers and must be nonnegative lib fl ff |
18,056 | print(value[sep=separatorend=endingfile=outfile]python function for printing series of values as inputyou can supply any number of valuesall of which are printed on the same line the sep keyword argument is used to specify different separator character ( space by defaultthe end keyword argument specifies different line ending ('\nby defaultthe file keyword argument redirects the output to file object this function can be used in python if you add the statement from _future_ import print_function to your code property([fget [,fset [,fdel [,doc]]]]creates property attribute for classes fget is function that returns the attribute valuefset sets the attribute valueand fdel deletes an attribute doc provides documentation string these parameters may be supplied using keyword arguments--for exampleproperty(fget=getxdoc="some text"range([start,stop [step]in python this creates fully populated list of integers from start to stop step indicates stride and is set to if omitted if start is omitted (when range(is called with one argument)it defaults to negative step creates list of numbers in descending order in python range(creates special range object that computes its values on demand (like xrange(in previous python versionsraw_input([prompt]python function that reads line of input from standard input (sys stdinand returns it as string if prompt is suppliedit' first printed to standard output (sys stdouttrailing newlines are strippedand an eoferror exception is raised if an eof is read if the readline module is loadedthis function will use it to provide advanced line-editing and command-completion features use input(to read input in python repr(objectreturns string representation of object in most casesthe returned string is an expression that can be passed to eval(to re-create the object be aware that in python the result of this function may be unicode string that can' be displayed in the terminal or shell window (resulting in an exceptionuse the ascii(function to create an ascii representation of object reversed(screates reverse iterator for sequence this function only works if implements the sequence methods _len_ (and _getitem_ (in additions must index items starting at it does not work with generators or iterators round( [ ]rounds the result of rounding the floating-point number to the closest multiple of to the power minus if is omittedit defaults to if two multiples are equally closepython rounds away from (for example is rounded to and - is rounded to - python rounds toward if the previous digit is even and away from otherwise (for example is rounded to and is rounded to lib fl ff |
18,057 | built-in functions and exceptions set([items]creates set populated with items taken from the iterable object items the items must be immutable if items contains other setsthose sets must be of type frozenset if items is omittedan empty set is returned setattr(objectnamevaluesets an attribute of an object name is string same as object name value slice([start,stop [step]returns slice object representing integers in the specified range slice objects are also generated by the extended slice syntax [ : :krefer to the section "sequence and mapping methodsin for details sorted(iterable [key=keyfunc [reverse=reverseflag]]creates sorted list from items in iterable the keyword argument key is singleargument function that transforms values before they are passed to the compare function the keyword argument reverse is boolean flag that specifies whether or not the resulting list is sorted in reverse order the key and reverse arguments must be specified using keywords--for examplesorted( ,key=get_namestaticmethod(funccreates static method for use in classes this function is implicitly invoked by the @staticmethod decorator str([object]type representing string in python string contains -bit characterswhereas in python strings are unicode if object is supplieda string representation of its value is created by calling its _str_ (method this is the same string that you see when you print the object if no argument is givenan empty string is created sum(items [,initial]computes the sum of sequence of items taken from the iterable object items initial provides the starting value and defaults to this function only works with numbers super(type [object]returns an object that represents the superclasses of type the primary purpose of this object is to invoke methods in base classes here' an exampleclass ( )def foo(self)super( ,selffoo(if object is an objectthen isinstance(objecttypemust be true if object is typethen it must be subclass of type refer to "classes and objectoriented programming,for more details in python you can use super(in method with no arguments in this casetype is set to the class in which the method is defined and object is set to the first argument of the method although this cleans up the syntaxit' not backwards-compatible with python so it should be avoided if you're concerned about portability lib fl ff |
18,058 | tuple([items]type representing tuple if supplieditems is an iterable object that is used to populate the tuple howeverif items is already tupleit' simply returned unmodified if no argument is givenan empty tuple is returned type(objectthe base class of all types in python when called as functionreturns the type of object this type is the same as the object' class for common types such as integersfloatsand liststhe type will refer to one of the other built-in classes such as intfloatlistand so forth for user-defined objectsthe type is the associated class for objects related to python' internalsyou will typically get reference to one of the classes defined in the types module type(name,bases,dictcreates new type object (which is the same as defining new classname is the name of the typebases is tuple of base classesand dict is dictionary containing definitions corresponding to class body this function is most commonly used when working with metaclasses this is described further in unichr(xconverts the integer or long integer xwhere < < to single unicode character python only in python just use chr(xunicode(string [,encoding [,errors]]in python this converts string to unicode string encoding specifies the data encoding of string if omittedthe default encoding as returned by sys getdefaultencoding(is used errors specifies how encoding errors are handled and is one of 'strict''ignore''replace''backslashreplace'or 'xmlcharrefreplacerefer to and for details not available in python vars([object]returns the symbol table of object (usually found in its _dict_ attributeif no argument is givena dictionary corresponding to the local namespace is returned the dictionary returned by this function should be assumed to be read-only it' not safe to modify its contents xrange([start,stop [step] type representing range of integer values from start to stop that is not included step provides an optional stride the values are not actually stored but are computed on demand when accessed in python xrange(is the preferred function to use when you want to write loops over ranges of integer values in python xrange(has been renamed to range(and xrange(is unavailable startstopand step are limited to the set of values supported by machine integers (typically bitszip([ [ []]]in python returns list of tuples where the nth tuple is ( [ ] [ ]the resulting list is truncated to the length of the shortest argument sequence if no arguments are givenan empty list is returned in python the behavior is similarbut the lib fl ff |
18,059 | built-in functions and exceptions result is an iterator that produces sequence of tuples in python be aware that using zip(with long input sequences is something that can unintentionally consume large amounts of memory consider using itertools izip(instead built-in exceptions built-in exceptions are contained in the exceptions modulewhich is always loaded prior to the execution of any program exceptions are defined as classes exception base classes the following exceptions serve as base classes for all the other exceptionsbaseexception the root class for all exceptions all built-in exceptions are derived from this class exception the base class for all program-related exceptions that includes all built-in exceptions except for systemexitgeneratorexitand keyboardinterrupt user-defined exceptions should be defined by inheriting from exception arithmeticerror the base class for arithmetic exceptionsincluding overflowerrorzerodivisionerrorand floatingpointerror lookuperror the base class for indexing and key errorsincluding indexerror and keyerror environmenterror the base class for errors that occur outside pythonincluding ioerror and oserror the preceding exceptions are never raised explicitly howeverthey can be used to catch certain classes of errors for instancethe following code would catch any sort of numerical errortrysome operation except arithmeticerror as emath error exception instances when an exception is raisedan instance of an exception class is created this instance is placed in the optional variable supplied to the except statement here' an exampleexcept ioerror as ehandle error 'ehas an instance of ioerror instances of an exception have few standard attributes that can be useful to inspect and/or manipulate in certain applications lib fl ff |
18,060 | args the tuple of arguments supplied when raising the exception in most casesthis is one-item tuple with string describing the error for environmenterror exceptionsthe value is -tuple or -tuple containing an integer error numbera string error messageand an optional filename the contents of this tuple might be useful if you need to re-create the exception in different contextfor exampleto raise an exception in different python interpreter process message string representing the error message that gets printed when the exception is displayed (python onlye _cause_ previous exception when using explicit chained exceptions (python onlysee appendix _context_ previous exception for implicitly chained exceptions (python onlysee appendix _traceback_ traceback object associated with the exception (python onlysee appendix predefined exception classes the following exceptions are raised by programsassertionerror failed assert statement attributeerror failed attribute reference or assignment eoferror end of file generated by the built-in functions input(and raw_input(it should be noted that most other / operations such as the read(and readline(methods of files return an empty string to signal eof instead of raising an exception floatingpointerror failed floating-point operation it should be noted that floating-point exceptionhandling is tricky problem and only that this exception only gets raised if python has been configured and built in way that enables it it is more common for floating-point errors to silently produce results such as float('nan'or float('inf' subclass of arithmeticerror generatorexit raised inside generator function to signal termination this happens when generator is destroyed prematurely (before all generator values are consumedor the close(method of generator is called if generator ignores this exceptionthe generator is terminated and the exception is silently ignored lib fl ff |
18,061 | built-in functions and exceptions ioerror failed / operation the value is an ioerror instance with the attributes errnostrerrorand filename errno is an integer error numberstrerror is string error messageand filename is an optional filename subclass of environmenterror importerror raised when an import statement can' find module or when from can' find name in module indentationerror indentation error subclass of syntaxerror indexerror sequence subscript out of range subclass of lookuperror keyerror key not found in mapping subclass of lookuperror keyboardinterrupt raised when the user hits the interrupt key (usually ctrl+cmemoryerror recoverable out-of-memory error nameerror name not found in local or global namespaces notimplementederror unimplemented feature can be raised by base classes that require derived classes to implement certain methods subclass of runtimeerror oserror operating system error primarily raised by functions in the os module the value is the same as for ioerror subclass of environmenterror overflowerror result of an integer value being too large to be represented this exception usually only arises if large integer values are passed to objects that internally rely upon fixedprecision machine integers in their implementation for examplethis error can arise with range or xrange objects if you specify starting or ending values that exceed bits in size subclass of arithmeticerror referenceerror result of accessing weak reference after the underlying object has been destroyed see the weakref module runtimeerror generic error not covered by any of the other categories lib fl ff |
18,062 | stopiteration raised to signal the end of iteration this normally happens in the next(method of an object or in generator function syntaxerror parser syntax error instances have the attributes filenamelinenooffsetand textwhich can be used to gather more information systemerror internal error in the interpreter the value is string indicating the problem systemexit raised by the sys exit(function the value is an integer indicating the return code if it' necessary to exit immediatelyos _exit(can be used taberror inconsistent tab usage generated when python is run with the -tt option subclass of syntaxerror typeerror occurs when an operation or function is applied to an object of an inappropriate type unboundlocalerror unbound local variable referenced this error occurs if variable is referenced before it' defined in function subclass of nameerror unicodeerror unicode encoding or decoding error subclass of valueerror unicodeencodeerror unicode encoding error subclass of unicodeerror unicodedecodeerror unicode decoding error subclass of unicodeerror unicodetranslateerror unicode error occurred during translation subclass of unicodeerror valueerror generated when the argument to function or an operation is the right type but an inappropriate value windowserror generated by failed system calls on windows subclass of oserror zerodivisionerror dividing by zero subclass of arithmeticerror lib fl ff |
18,063 | built-in functions and exceptions built-in warnings python has warnings module that is typically used to notify programmers about deprecated features warnings are issued by including code such as the followingimport warnings warnings warn("the mondo flag is no longer supported"deprecationwarningalthough warnings are issued by library modulethe names of the various warnings are built-in warnings are somewhat similar to exceptions there is hierarchy of builtin warnings that all inherit from exception warning the base class of all warnings subclass of exception userwarning generic user-defined warning subclass of warning deprecationwarning warning for deprecated features subclass of warning syntaxwarning warning for deprecated python syntax subclass of warning runtimewarning warning for potential runtime problems subclass of warning futurewarning warning that the behavior of feature will change in the future subclass of warning warnings are different than exceptions in that the issuing of warning with the warn(function may or may not cause program to stop for examplea warning may just print something to the output or it may raise an exception the actual behavior can be configured with the warnings module or with the - option to the interpreter if you are using someone else' code that generates warningbut you would like to proceed anywaysyou can catch warnings that have been turned into exceptions using try and except for exampletryimport md except deprecationwarningpass it should be emphasized that code such as this is rare although it will catch warning that has been turned into an exceptionit doesn' suppress warning messages (you have to use the warnings module to control thatplusignoring warnings is good way to write code that doesn' work correctly when new versions of python are released lib fl ff |
18,064 | future_builtins the future_builtins moduleonly available in python provides implementations of the built-in functions whose behavior is changed in python the following functions are definedascii(objectproduces the same output as repr(refer to the description in the "built-in functionssection of this filter(functioniterablecreates an iterator instead of list the same as itertools ifilter(hex(objectcreates hexadecimal stringbut uses the _index_ (special method to get an integer value instead of calling _hex_ (map(functioniterablecreates an iterator instead of list the same as itertools imap(oct(objectcreates an octal stringbut uses the _index_ (special method to get an integer value instead of calling _oct_ (zip(iterableiterablecreates an iterator instead of list the same as itertools izip(be aware that the functions listed in this module are not complete list of changes to the built-in module for instancepython also renames raw_input(to input(and xrange(to range( lib fl ff |
18,065 | lib fl ff |
18,066 | python runtime services his describes modules that are related to the python interpreter runtime topics include garbage collectionbasic management of objects (copyingmarshallingand so on)weak referencesand interpreter environment atexit the atexit module is used to register functions to execute when the python interpreter exits single function is providedregister(func [,args [,kwargs]]adds function func to list of functions that will execute when the interpreter exits args is tuple of arguments to pass to the function kwargs is dictionary of keyword arguments the function is invoked as func(*args,**kwargsupon exitfunctions are invoked in reverse order of registration (the most recently added exit function is invoked firstif an error occursan exception message will be printed to standard error but will otherwise be ignored copy the copy module provides functions for making shallow and deep copies of compound objectsincluding liststuplesdictionariesand instances of user-defined objects copy(xmakes shallow copy of by creating new compound object and duplicating the members of by reference for built-in typesit is somewhat uncommon to use this function insteadyou use calls such as list( )dict( )set( )and so forth to create shallow copy of (it should be noted that using the type name directly like this is also significantly faster than using copy()deepcopy( [visit]makes deep copy of by creating new compound object and recursively duplicating all the members of visit is an optional dictionary that' used to keep track of visited objects in order to detect and avoid cycles in recursively defined data structures this argument is typically only supplied if deepcopy(is being called recursively as described later in this lib fl ff |
18,067 | although it is not usually necessarya class can implement customized copy methods by implementing the methods _copy_ (selfand _deepcopy_ (selfvisit)which implement the shallow and deep copy operations respectively the _deepcopy_ (method must accept dictionaryvisitwhich is used to keep track of previously encountered objects during the copy process it' not necessary for _deepcopy_ (to do anything with visit other than pass it to other deepcopy(operations carried out in the implementation (if anyif class implements the methods _getstate_ (and _setstate_ (that are used by the pickle modulethey will be used by the copy module to create copies notes this module can be used with simple types such as integers and stringsbut there' little need to do so the copy functions don' work with modulesclass objectsfunctionsmethodstracebacksstack framesfilessocketsand other similar types when an object can' be copiedthe copy error exception is raised gc the gc module provides an interface for controlling the garbage collector used to collect cycles in objects such as liststuplesdictionariesand instances as various types of container objects are createdthey're placed on list that' internal to the interpreter whenever container objects are deallocatedthey're removed from this list if the number of allocations exceeds the number of deallocations by user-definable threshold valuethe garbage collector is invoked the garbage collector works by scanning this list and identifying collections of objects that are no longer being used but haven' been deallocated due to circular dependencies in additionthe garbage collector uses threelevel generational scheme in which objects that survive the initial garbage-collection step are placed onto lists of objects that are checked less frequently this provides better performance for programs that have large number of long-lived objects collect([generation]runs full garbage collection this function checks all generations and returns the number of unreachable objects found generation is an optional integer in the range that specifies the generation to collect disable(disables garbage collection enable(enables garbage collection garbage variable containing read-only list of user-defined instances that are no longer in usebut which cannot be garbage collected because they are involved in reference cycle and they define _del_ (method such objects cannot be garbage-collected because in order to break the reference cyclethe interpreter must arbitrarily destroy lib fl ff |
18,068 | one of the objects first howeverthere is no way to know if the _del_ (method of the remaining objects in the cycle needs to perform critical operations on the object that was just destroyed get_count(returns tuple (count count count containing the number of objects currently in each generation get_debug(returns the debugging flags currently set get_objects(returns list of all objects being tracked by the garbage collector does not include the returned list get_referrers(obj obj returns list of all objects that directly refer to the objects obj obj and so on the returned list may include objects that have not yet been garbage-collected as well as partially constructed objects get_referents(obj obj returns list of objects that the objects obj obj and so on refer to for exampleif obj is containerthis would return list of the objects in the container get_threshold(returns the current collection threshold as tuple isenabled(returns true if garbage collection is enabled set_debug(flagssets the garbage-collection debugging flagswhich can be used to debug the behavior of the garbage collector flags is the bitwise or of the constants debug_statsdebug_collectabledebug_uncollectabledebug_instancesdebug_objectsdebug_savealland debug_leak the debug_leak flag is probably the most useful because it will have the collector print information useful for debugging programs with memory leaks set_threshold(threshold [threshold [threshold ]]sets the collection frequency of garbage collection objects are classified into three generationswhere generation contains the youngest objects and generation contains the oldest objects objects that survive garbage-collection step are moved to the nextoldest generation once an object reaches generation it stays in that generation threshold is the difference between the number of allocations and deallocations that must be reached before garbage collection occurs in generation threshold is the number of collections of generation that must occur before generation is scanned threshold is the number of collections that must occur in generation before generation is collected the default threshold is currently set to ( , , setting threshold to disables garbage collection lib fl ff |
18,069 | notes circular references involving objects with _del_ (method are not garbage-collected and are placed on the list gc garbage (uncollectable objectsthese objects are not collected due to difficulties related to object finalization the functions get_referrers(and get_referents(only apply to objects that support garbage collection in additionthese functions are only intended for debugging they should not be used for other purposes inspect the inspect module is used to gather information about live python objects such as attributesdocumentation stringssource codestack framesand so on cleandoc(doccleans up documentation string doc by changing all tabs into whitespace and removing indentation that might have been inserted to make the docstring line up with other statements inside function or method currentframe(returns the frame object corresponding to the caller' stack frame formatargspec(args [varags [varkw [defaults]]]produces nicely formatted string representing the values returned by getargspec(formatargvalues(args [varargs [varkw [locals]]]produces nicely formatted string representing the values returned by getargvalues(getargspec(funcgiven functionfuncreturns named tuple argspec(argsvarargsvarkwdefaultsargs is list of argument namesand varargs is the name of the argument (if anyvarkw is the name of the *argument (if any)and defaults is tuple of default argument values or none if there are no default argument values if there are default argument valuesthe defaults tuple represents the values of the last arguments in argswhere is the len(defaultsgetargvalues(framereturns the values of arguments supplied to function with execution frame frame returns tuple arginfo(argsvarargsvarkwlocalsargs is list of argument namesvarargs is the name of the argument (if any)and varkw is the name of the *argument (if anylocals is the local dictionary of the frame getclasstree(classes [unique]given list of related classesclassesthis function organizes the classes into hierarchy based on inheritance the hierarchy is represented as collection of nested listswhere each entry in the list is list of classes that inherit from the class that immediately precedes the list each entry in the list is -tuple (clsbases)where cls is the lib fl ff |
18,070 | class object and bases is tuple of base classes if unique is trueeach class only appears once in the returned list otherwisea class may appear multiple times if multiple inheritance is being used getcomments(objectreturns string consisting of comments that immediately precede the definition of object in python source code if object is modulecomments defined at the top of the module are returned returns none if no comments are found getdoc(objectreturns the documentation string for object the documentation string is first processed using the cleandoc(function before being returned getfile(objectreturns the name of the file in which object was defined may return typeerror if this information is not applicable or available (for examplefor built-in functionsgetframeinfo(frame [context]returns named tuple traceback(filenamelinenofunctioncode_contextindexcontaining information about the frame object frame filename and line specify source code location the context parameter specifies the number of lines of context from the source code to retrieve the contextlist field in the returned tuple contains list of source lines corresponding to this context the index field is numerical index within this list for the line corresponding to frame getinnerframes(traceback [context]returns list of frame records for the frame of traceback and all inner frames each frame-record is -tuple consisting of (framefilenamelinefuncnamecontextlistindexfilenamelinecontextcontextlistand index have the same meaning as with getframeinfo(getmembers(object [predicate]returns all of the members of object typicallythe members are obtained by looking in the _dict_ attribute of an objectbut this function may return attributes of object stored elsewhere (for exampledocstrings in _doc_ _objectsnames in _name_ _and so onthe members are returned list of (namevaluepairs predicate is an optional function that accepts member object as an argument and returns true or false only members for which predicate returns true are returned functions such as isfunction(and isclass(can be used as predicate functions getmodule(objectreturns the module in which object was defined (if possiblegetmoduleinfo(pathreturns information about how python would interpret the file path if path is not python modulenone is returned otherwisea named tuple moduleinfo(namesuffixmodemodule_typeis returned where name is the name of the modulef lib fl ff |
18,071 | python runtime services suffix is the filename suffixmode is the file mode that would be used to open the moduleand module_type is an integer code specifying the module type module type codes are defined in the imp module as followsmodule type description imp py_source python source file python compiled object file pycdynamically loadable extension package directory built-in module frozen module imp py_compiled imp c_extension imp pkg_directory imp c_builtin imp py_frozen getmodulename(pathreturns the name of the module that would be used for the file path if path does not look like python modulenone is returned getmro(clsreturns tuple of classes that represent the method-resolution ordering used to resolve methods in class cls refer to "classes and object-oriented programming,for further details getouterframes(frame [context]returns list of frame records for frame and all outer frames this list represents the calling sequence where the first entry contains information for frame each frame record is -tuple (framefilenamelinefuncnamecontextlistindexwhere the fields have the same meaning as for getinnerframes()the context argument has the same meaning as for getframeinfo(getsourcefile(objectreturns the name of the python source file in which object was defined getsourcelines(objectreturns tuple (sourcelinesfirstlinecorresponding to the definition of object sourcelines is list of source code linesand firstline is the line number of the first source code line raises ioerror if source code can' be found getsource(objectreturns source code of object as single string raises ioerror if the source code can' be found isabstract(objectreturns true if object is an abstract base class isbuiltin(objectreturns true if object is built-in function isclass(objectreturns true if object is class lib fl ff |
18,072 | iscode(objectreturns true if object is code object isdatadescriptor(objectreturns true if object is data descriptor object this is the case if object defines both _get_ (and _set_ (method isframe(objectreturns true if object is frame object isfunction(objectreturns true if object is function object isgenerator(objectreturns true if object is generator object isgeneratorfunction(objectreturns true if object is generator function this is different than isgenerator(in that it tests if object is function that creates generator when called it is not used to check if object is an actively running generator ismethod(objectreturns true if object is method ismethoddescriptor(objectreturns true if object is method descriptor object this is the case if object is not methodclassor function and it defines _get_ (method but does not define _set_ (ismodule(objectreturns true if object is module object isroutine(objectreturns true if object is user-defined or built-in function or method istraceback(objectreturns true if object is traceback object stack([context]returns list of frame records corresponding to the stack of the caller each frame record is -tuple (framefilenamelinefuncnamecontextlistindex)which contains the same information as returned by getinnerframes(context specifies the number of lines of source context to return in each frame record trace([context]returns list of frame records for the stack between the current frame and the frame in which the current exception was raised the first frame record is the callerand the last frame record is the frame where the exception occurred context specifies the number of lines of source context to return in each frame record lib fl ff |
18,073 | marshal the marshal module is used to serialize python objects in an "undocumentedpython-specific data format marshal is similar to the pickle and shelve modulesbut it is less powerful and intended for use only with simple objects it shouldn' be used to implement persistent objects in general (use pickle insteadhoweverfor simple built-in typesthe marshal module is very fast approach for saving and loading data dump(valuefile [version]writes the object value to the open file object file if value is an unsupported typea valueerror exception is raised version is an integer that specifies the data format to use the default output format is found in marshal version and is currently set to version is an older format used by earlier versions of python dumps(value [,version]returns the string written by the dump(function if value is an unsupported typea valueerror exception is raised version is the same as described previously load(filereads and returns the next value from the open file object file if no valid value is readan eoferrorvalueerroror typeerror exception will be raised the format of the input data is automatically detected loads(stringreads and returns the next value from the string string notes data is stored in binary architecture-independent format only noneintegerslong integersfloatscomplex numbersstringsunicode stringstupleslistsdictionariesand code objects are supported liststuplesand dictionaries can only contain supported objects class instances and recursive references in liststuplesand dictionaries are not supported integers may be promoted to long integers if the built-in integer type doesn' have enough precision--for exampleif the marshalled data contains -bit integerbut the data is being read on -bit machine marshal is not intended to be secure against erroneous or maliciously constructed data and should not be used to unmarshal data from untrusted sources marshal is significantly faster than picklebut it isn' as flexible pickle the pickle module is used to serialize python objects into stream of bytes suitable for storing in filetransferring across networkor placing in database this process is variously called picklingserializingmarshallingor flattening the resulting byte stream can also be converted back into series of python objects using an unpickling process lib fl ff |
18,074 | the following functions are used to turn an object into byte-stream dump(objectfile [protocol ]dumps pickled representation of object to the file object file protocol specifies the output format of the data protocol (the defaultis text-based format that is backwards-compatible with earlier versions of python protocol is binary protocol that is also compatible with most earlier python versions protocol is newer protocol that provides more efficient pickling of classes and instances protocol is used by python and is not backwards-compatible if protocol is negativethe most modern protocol will be selected the variable pickle highest_protocol contains the highest protocol available if object doesn' support picklinga pickle picklingerror exception is raised dumps(object [protocol]same as dump()but returns string containing the pickled data the following example shows how you use these functions to save objects to filef open('myfile''wb'pickle dump(xfpickle dump(yfdump more objects close(the following functions are used to restore pickled object load(fileloads and returns pickled representation of an object from the file object file it is not necessary to specify the input protocol as it is automatically detected pickle unpicklingerror exception is raised if the file contains corrupted data that can' be decoded if an end-of-file is detectedan eoferror exception is raised loads(stringsame as load()but reads the pickled representation of an object from string the following example shows how you use these functions to load dataf open('myfile''rb' pickle load(fy pickle load(fload more objects close(when loadingit is not necessary to specify the protocol or any information about the type of object being loaded that information is saved as part of the pickle data format itself if you are pickling more than one python objectyou can simply make repeated calls to dump(and load(as shown in the previous examples when making multiple callsyou simply have to make sure the sequence of load(calls matches the sequence of dump(calls that were used to write the file when working with complicated data structures involving cycles or shared referencesusing dump(and load(can be problematic because they don' maintain any internal state about objects that have already been pickled or restored this can result in output files that are excessively large and that don' properly restore the relationship lib fl ff |
18,075 | between objects when loaded an alternative approach is to use pickler and unpickler objects pickler(file [protocol ]creates pickling object that writes data to the file object file with the specified pickle protocol an instance of pickler has method dump(xthat dumps an object to file once has been dumpedits identity is remembered if subsequent dump(operation is used to write the same objecta reference to the previously dumped object is saved instead of writing new copy the method clear_memo(clears the internal dictionary used to track previously dumped objects you would use this if you wanted to write fresh copy of previously dumped object (that isif its value changed since the last dump(operationunpickler(filecreates an unpickling object that reads data from the file object file an instance of unpickler has method load(that loads and returns new object from file an unpickler keeps track of objects it has returned because the input source might contain an object reference created by the pickler object in this caseu load(returns reference to the previously loaded object the pickle module works with most kinds of normal python objects this includesn none numbers and strings tupleslistsand dictionaries containing only pickleable objects instances of user-defined classes defined at the top level of module when instances of user-defined class are pickledthe instance data is the only part that gets pickled the corresponding class definition is not saved--insteadthe pickled data merely contains the name of the associated class and module when instances are unpickledthe module in which the class is defined is automatically imported in order to access the class definition when re-creating instances it should also be noted that when restoring an instancethe _init_ (method of class is not invoked insteadthe instance is re-created through other means and the instance data restored one restriction on instances is that the corresponding class definition must appear at the top level of module (that isno nested classesin additionif the instance' class definition was originally defined in _main_ _that class definition must be manually reloaded prior to unpickling saved object (because there' no way for the interpreter to know how to automatically load the necessary class definitions back into _main_ when unpicklingit is not normally necessary to do anything to make user-defined class work with pickle howevera class can define customized methods for saving and restoring its state by implementing the special methods _getstate_ (and _setstate_ (the _getstate_ (method must return pickleable object (such as string or tuplerepresenting the state of the object the _setstate_ (method accepts the pickled object and restores its state if these methods are undefinedthe default behavior is to pickle an instance' underlying _dict_ attribute it should be noted that if these methods are definedthey will also be used by the copy module to implement the shallow and deep copy operations lib fl ff |
18,076 | notes in python module called cpickle contains implementation of functions in the pickle module it is significantly faster than picklebut is restricted in that it doesn' allow subclassing of the pickler and unpickler objects python has support module that also contains implementationbut it is used more transparently (pickle takes advantage of it automatically as appropriaten the data format used by pickle is python-specific and shouldn' be assumed to be compatible with any external standards such as xml whenever possiblethe pickle module should be used instead of the marshal module because pickle is more flexiblethe data encoding is documentedand additional error-checking is performed due to security concernsprograms should not unpickle data received from untrusted sources use of the pickle module with types defined in extension modules is much more involved than what is described here implementers of extension types should consult the online documentation for details concerning the low-level protocol required to make these objects work with pickle--in particulardetails on how to implement the _reduce_ (and _reduce_ex_ (special methods that pickle uses to create the serialized byte sequences sys the sys module contains variables and functions that pertain to the operation of the interpreter and its environment variables the following variables are defined api_version an integer representing the api version of the python interpreter used when working with extension modules argv list of command-line options passed to program argv[ is the name of the program builtin_module_names tuple containing names of modules built into the python executable byteorder native byte-ordering of the machine--'littlefor little-endian or 'bigfor bigendian lib fl ff |
18,077 | python runtime services copyright string containing copyright message _displayhook_ original value of the displayhook(function dont_write_bytecode boolean flag that determines whether or not python writes bytecode pyc or pyo fileswhen importing modules the initial value is true unless the - option to the interpreter is given the setting can be changed as needed in your own program dllhandle integer handle for the python dll (windows_ _excepthook_ original value of the excepthook(function exec_prefix directory where platform-dependent python files are installed executable string containing the name of the interpreter executable flags an object representing the settings of different command-line options supplied to the python interpreter itself the following table lists the attributes of flags along with the corresponding command-line option that turns the flag on these attributes are readonly attribute command-line option flags debug flags py k_warning flags division_warning flags division_new flags inspect flags interactive flags optimize flags dont_write_bytecode flags no_site flags ignore_environment flags tabcheck flags verbose flags unicode - - - -qnew - - - or -oo - - - - or -tt - - lib fl ff |
18,078 | float_info an object that holds information about internal representation of floating-point numbers the values of these attributes are taken from the float header file attribute description difference between and the next largest float float_info dig number of decimal digits that can be represented without any changes after rounding float_info mant_dig number of digits that can be represented using the numeric base specified in float_info radix float_info max maximum floating-point number float_info max_exp maximum exponent in the numeric base specified in float_info radix float_info max_ _exp maximum exponent in base float_info min minimum positive floating-point value float_info min_exp minimum exponent in the numeric base specified in float_info radix float_info min_ _exp minimum exponent in base float_info radix numeric base used for exponents float_info rounds rounding behavior (- undetermined towards zero nearest towards positive infinity towards negative infinityfloat_info epsilon hexversion integer whose hexadecimal representation encodes the version information contained in sys version_info the value of this integer is always guaranteed to increase with newer versions of the interpreter last_typelast_valuelast_traceback these variables are set when an unhandled exception is encountered and the interpreter prints an error message last_type is the last exception typelast_value is the last exception valueand last_traceback is stack trace note that the use of these variables is not thread-safe sys exc_info(should be used instead maxint largest integer supported by the integer type (python onlymaxsize largest integer value supported by the size_t datatype on the system this value determines the largest possible length for stringslistsdictsand other built-in types maxunicode integer that indicates the largest unicode code point that can be represented the default value is for the -bit ucs- encoding larger value will be found if python has been configured to use ucs- modules dictionary that maps module names to module objects lib fl ff |
18,079 | python runtime services path list of strings specifying the search path for modules the first entry is always set to the directory in which the script used to start python is located (if availablerefer to "iterators and generators platform platform identifier stringsuch as 'linux- prefix directory where platform-independent python files are installed ps ps strings containing the text for the primary and secondary prompts of the interpreter initiallyps is set to and ps is set to the str(method of whatever object is assigned to these values is evaluated to generate the prompt text py kwarning flag set to true in python when the interpreter is run with the - option stdinstdoutstderr file objects corresponding to standard inputstandard outputand standard error stdin is used for the raw_input(and input(functions stdout is used for print and the prompts of raw_input(and input(stderr is used for the interpreter' prompts and error messages these variables can be assigned to any object that supports write(method operating on single string argument _stdin_ __ _stdout_ __ _stderr_ file objects containing the values of stdinstdoutand stderr at the start of the interpreter tracebacklimit maximum number of levels of traceback information printed when an unhandled exception occurs the default value is value of suppresses all traceback information and causes only the exception type and value to be printed version version string version_info version information represented as tuple (majorminormicroreleaselevelserialall values are integers except releaselevelwhich is the string 'alpha''beta''candidate'or 'finalwarnoptions list of warning options supplied to the interpreter with the - command-line option winver the version number used to form registry keys on windows lib fl ff |
18,080 | functions the following functions are available_clear_type_cache(clears the internal type cache to optimize method lookupsa small -entry cache of recently used methods is maintained inside the interpreter this cache speeds up repeated method lookups--especially in code that has deep inheritance hierarchies normallyyou don' need to clear this cachebut you might do so if you are trying to track down really tricky memory reference counting issue for exampleif method in the cache was holding reference to an object that you were expecting to be destroyed _current_frames(returns dictionary mapping thread identifiers to the topmost stack frame of the executing thread at the time of call this information can be useful in writing tools related to thread debugging (that istracking down deadlockkeep in mind that the values returned by this function only represent snapshot of the interpreter at the time of call threads may be executing elsewhere by the time you look at the returned data displayhook([value]this function is called to print the result of an expression when the interpreter is running in interactive mode by defaultthe value of repr(valueis printed to standard output and value is saved in the variable _builtin_ displayhook can be redefined to provide different behavior if desired excepthook(type,value,tracebackthis function is called when an uncaught exception occurs type is the exception classvalue is the value supplied by the raise statementand traceback is traceback object the default behavior is to print the exception and traceback to standard error howeverthis function can be redefined to provide alternative handling of uncaught exceptions (which may be useful in specialized applications such as debuggers or cgi scriptsexc_clear(clears all information related to the last exception that occurred it only clears information specific to the calling thread exc_info(returns tuple (typevaluetracebackcontaining information about the exception that' currently being handled type is the exception typevalue is the exception parameter passed to raiseand traceback is traceback object containing the call stack at the point where the exception occurred returns none if no exception is currently being handled exit([ ]exits python by raising the systemexit exception is an integer exit code indicating status code value of is considered normal (the default)nonzero values are considered abnormal if noninteger value is given to nit' printed to sys stderr and an exit code of is used lib fl ff |
18,081 | python runtime services getcheckinterval(returns the value of the check intervalwhich specifies how often the interpreter checks for signalsthread switchesand other periodic events getdefaultencoding(gets the default string encoding in unicode conversions returns value such as 'asciior 'utf- the default encoding is set by the site module getdlopenflags(returns the flags parameter that is supplied to the function dlopen(when loading extension modules on unix see dl module getfilesystemencoding(returns the character encoding used to map unicode filenames to filenames used by the underlying operating system returns 'mbcson windows or 'utf- on macintosh os on unix systemsthe encoding depends on locale settings and will return the value of the locale codeset parameter may return nonein which case the system default encoding is used _getframe([depth]returns frame object from the call stack if depth is omitted or zerothe topmost frame is returned otherwisethe frame for that many calls below the current frame is returned for example_getframe( returns the caller' frame raises valueerror if depth is invalid getprofile(returns the profile function set by the setprofile(function getrecursionlimit(returns the recursion limit for functions getrefcount(objectreturns the reference count of object getsizeof(object [default]returns the size of object in bytes this calculation is made by calling the _sizeof_ (special method of object if undefineda typeerror will be generated unless default value has been specified with the default argument because objects are free to define _sizeof_ (however they wishthere is no guarantee that the result of this function is true measure of memory use howeverfor built-in types such as lists or stringit is correct gettrace(returns the trace function set by the settrace(function getwindowsversion(returns tuple (major,minor,build,platform,textthat describes the version of windows being used major is the major version number for examplea value of indicates windows nt and value of indicates windows and windows xp lib fl ff |
18,082 | variants minor is the minor version number for example indicates windows whereas indicates windows xp build is the windows build number platform identifies the platform and is an integer with one of the following common values (win on windows ) (windows , or me) (windows nt xp)or (windows cetext is string containing additional information such as "service pack setcheckinterval(nsets the number of python virtual machine instructions that must be executed by the interpreter before it checks for periodic events such as signals and thread context switches the default value is setdefaultencoding(encsets the default encoding enc is string such as 'asciior 'utf- this function is only defined inside the site module it can be called from user-definable sitecustomize modules setdlopenflags(flagssets the flags passed to the dlopen(functionwhich is used to load extension modules on unix this will affect the way in which symbols are resolved between libraries and other extension modules flags is the bitwise or of values that can be found in the dl module (see "network programming")--for examplesys setdlopenflags(dl rtld_now dl rtld_globalsetprofile(pfuncsets the system profile function that can be used to implement source code profiler setrecursionlimit(nchanges the recursion limit for functions the default value is note that the operating system may impose hard limit on the stack sizeso setting this too high may cause the python interpreter process to crash with segmentation fault or access violation settrace(tfuncsets the system trace functionwhich can be used to implement debugger refer to for information about the python debugger traceback the traceback module is used to gather and print stack traces of program after an exception has occurred the functions in this module operate on traceback objects such as the third item returned by the sys exc_info(function the main use of this module is in code that needs to report errors in non-standard way--for exampleif you were running python programs deeply embedded within network server and you wanted to redirect tracebacks to log file print_tb(traceback [limit [file]]prints up to limit stack trace entries from traceback to the file file if limit is omittedall the entries are printed if file is omittedthe output is sent to sys stderr lib fl ff |
18,083 | python runtime services print_exception(typevaluetraceback [limit [file]]prints exception information and stack trace to file type is the exception typeand value is the exception value limit and file are the same as in print_tb(print_exc([limit [file]]same as print_exception(applied to the information returned by the sys exc_info(function format_exc([limit [file]]returns string containing the same information printed by print_exc(print_last([limit [file]]same as print_exception (sys last_typesys last_valuesys last_tracebacklimitfileprint_stack([frame [limit [file]]]prints stack trace from the point at which it' invoked frame specifies an optional stack frame from which to start limit and file have the same meaning as for print_tb(extract_tb(traceback [limit]extracts the stack trace information used by print_tb(the return value is list of tuples of the form (filenamelinefuncnametextcontaining the same information that normally appears in stack trace limit is the number of entries to return extract_stack([frame [limit]]extracts the same stack trace information used by print_stack()but obtained from the stack frame frame if frame is omittedthe current stack frame of the caller is used and limit is the number of entries to return format_list(listformats stack trace information for printing list is list of tuples as returned by extract_tb(or extract_stack(format_exception_only(typevalueformats exception information for printing format_exception(typevaluetraceback [limit]formats an exception and stack trace for printing format_tb(traceback [limit]same as format_list(extract_tb(tracebacklimit)format_stack([frame [limit]]same as format_list(extract_stack(framelimit)tb_lineno(tracebackreturns the line number set in traceback object lib fl ff |
18,084 | types the types module defines names for the built-in types that correspond to functionsmodulesgeneratorsstack framesand other program elements the contents of this module are often used in conjunction with the built-in isinstance(function and other type-related operations variable description builtinfunctiontype codetype frametype functiontype generatortype getsetdescriptortype lambdatype memberdescriptortype methodtype moduletype tracebacktype type of built-in functions type of code objects type of execution frame object type of user-defined functions and lambdas type of generator-iterator objects type of getset descriptor objects alternative name for functiontype type of member descriptor objects type of user-defined class methods type of modules type of traceback objects most of the preceding type objects serve as constructors that can be used to create an object of that type the following descriptions provide the parameters used to create functionsmodulescode objectsand methods contains detailed information about the attributes of the objects created and the arguments that need to be supplied to the functions described next functiontype(codeglobals [name [defarags [closure]]]creates new function object codetype(argcountnlocalsstacksizeflagscodestringconstantsnamesvarnamesfilenamenamefirstlinenolnotab [freevars [cellvars ]]creates new code object methodtype(functioninstanceclasscreates new bound instance method moduletype(name [doc]creates new module object notes the types module should not be used to refer the type of built-in objects such as integerslistsor dictionaries in python types contains other names such as inttype and dicttype howeverthese names are just aliases for the built-in type names of int and dict in modern codeyou should just use the built-in type names because the types module only contains the names listed previously in python lib fl ff |
18,085 | python runtime services warnings the warnings module provides functions to issue and filter warning messages unlike exceptionswarnings are intended to alert the user to potential problemsbut without generating an exception or causing execution to stop one of the primary uses of the warnings module is to inform users about deprecated language features that may not be supported in future versions of python for exampleimport regex _main_ : deprecationwarningthe regex module is deprecatedmodule use the re like exceptionswarnings are organized into class hierarchy that describes general categories of warnings the following lists the currently supported categorieswarning object description warning userwarning deprecationwarning syntaxwarning runtimewarning futurewarning base class of all warning types user-defined warning warning for use of deprecated feature potential syntax problem potential runtime problem warning that the semantics of particular feature will change in future release each of these classes is available in the _builtin_ module as well as the exceptions module in additionthey are also instances of exception this makes it possible to easily convert warnings into errors warnings are issued using the warn(function for examplewarnings warn("feature is deprecated "warnings warn("feature might be broken "runtimewarningif desiredwarnings can be filtered the filtering process can be used to alter the output behavior of warning messagesto ignore warningsor to turn warnings into exceptions the filterwarnings(function is used to add filter for specific type of warning for examplewarnings filterwarnings(action="ignore"message=*regex *"category=deprecationwarningimport regex warning message disappears limited forms of filtering can also be specified using the - option to the interpreter for examplepython -wignore:theregex:deprecationwarning the following functions are defined in the warnings modulef lib fl ff |
18,086 | warn(message[category[stacklevel]]issues warning message is string containing the warning messagecategory is the warning class (such as deprecationwarning)and stacklevel is an integer that specifies the stack frame from which the warning message should originate by defaultcategory is userwarning and stacklevel is warn_explicit(messagecategoryfilenamelineno[module[registry]]this is low-level version of the warn(function message and category have the same meaning as for warn(filenamelinenoand module explicitly specify the location of the warning registry is an object representing all the currently active filters if registry is omittedthe warning message is not suppressed showwarning(messagecategoryfilenamelineno[file]writes warning to file if file is omittedthe warning is printed to sys stderr formatwarning(messagecategoryfilenamelinenocreates the formatted string that is printed when warning is issued filterwarnings(action[message[category[module[lineno[append]]]]]adds an entry to the list of warning filters action is one of 'error''ignore''always''default''once'or 'modulethe following list provides an explanation of eachaction description 'error'ignore'always'default'module'onceconvert the warning into an exception ignore the warning always print warning message print the warning once for each location where the warning occurs print the warning once for each module in which the warning occurs print the warning once regardless of where it occurs message is regular expression string that is used to match against the warning message category is warning class such as deprecationerror module is regular expression string that is matched against the module name lineno is specific line number or to match against all lines append specifies that the filter should be appended to the list of all filters (checked lastby defaultnew filters are added to the beginning of the filter list if any argument is omittedit defaults to value that matches all warnings resetwarnings(resets all the warning filters this discards all previous calls to filterwarnings(as well as options specified with - notes the list of currently active filters is found in the warnings filters variable when warnings are converted to exceptionsthe warning category becomes the exception type for instancean error on deprecationwarning will raise deprecationwarning exception lib fl ff |
18,087 | the - option can be used to specify warning filter on the command line the general format of this option is -waction:message:category:module:lineno where each part has the same meaning as for the filterwarning(function howeverin this casethe message and module fields specify substrings (instead of regular expressionsfor the first part of the warning message and module name to be filteredrespectively weakref the weakref module is used to provide support for weak references normallya reference to an object causes its reference count to increase--effectively keeping the object alive until the reference goes away weak referenceon the other handprovides way of referring to an object without increasing its reference count this can be useful in certain kinds of applications that must manage objects in unusual ways for examplein an object-oriented programwhere you might implement relationship such as the observer patterna weak reference can be used to avoid the creation of reference cycles an example of this is shown in the "object memory managementsection of weak reference is created using the weakref ref(function as followsclass apass (ar weakref ref(acreate weak reference to print ar once weak reference is createdthe original object can be obtained from the weak reference by simply calling it as function with no arguments if the underlying object still existsit will be returned otherwisenone is returned to indicate that the original object no longer exists for exampleprint ar(print original object del delete the original object print ar( is goneso this now returns none none the following functions are defined by the weakref moduleref(object[callback]creates weak reference to object callback is an optional function that will be called when object is about to be destroyed if suppliedthis function should accept single argumentwhich is the corresponding weak reference object more than one weak reference may refer to the same object in this casethe callback functions will be called in order from the most recently applied reference to the oldest reference object can be obtained from weak reference by calling the returned weak reference object as function with no arguments if the original object no longer existsnone lib fl ff |
18,088 | will be returned ref(actually defines typereferencetypethat can be used for type-checking and subclasses proxy(object[callback]creates proxy using weak reference to object the returned proxy object is really wrapper around the original object that provides access to its attributes and methods as long as the original object existsmanipulation of the proxy object will transparently mimic the behavior of the underlying object on the other handif the original object has been destroyedoperations on the proxy will raise weakref referenceerror to indicate that the object no longer exists callback is callback function with the same meaning as for the ref(function the type of proxy object is either proxytype or callableproxytypedepending on whether or not the original object is callable getweakrefcount(objectreturns the number of weak references and proxies that refer to object getweakrefs(objectreturns list of all weak reference and proxy objects that refer to object weakkeydictionary([dict]creates dictionary in which the keys are referenced weakly when there are no more strong references to keythe corresponding entry in the dictionary is automatically removed if suppliedthe items in dict are initially added to the returned weakkeydictionary object because only certain types of objects can be weakly referencedthere are numerous restrictions on acceptable key values in particularbuilt-in strings cannot be used as weak keys howeverinstances of user-defined classes that define _hash_ (method can be used as keys an instance of weakkeydictionary has two methodsiterkeyrefs(and keyrefs()that return the weak key references weakvaluedictionary([dict]creates dictionary in which the values are referenced weakly when there are no more strong references to valuecorresponding entries in the dictionary will be discarded if suppliedthe entries in dict are added to the returned weakvaluedictionary an instance of weakvaluedictionary has two methodsitervaluerefs(and valuerefs()that return the weak value references proxytypes this is tuple (proxytypecallableproxytypethat can be used for testing if an object is one of the two kinds of proxy objects created by the proxy(function--for exampleisinstance(objectproxytypesf lib fl ff |
18,089 | example one application of weak references is to create caches of recently computed results for instanceif function takes long time to compute resultit might make sense to cache these results and to reuse them as long as they are still in use someplace in the application for example_resultcache def foocache( )if resultcache has_key( ) _resultcache[ ](get weak ref and dereference it if is not nonereturn foo(x_resultcache[xweakref ref(rreturn notes only class instancesfunctionsmethodssetsfrozen setsfilesgeneratorstype objectsand certain object types defined in library modules (for examplesocketsarraysand regular expression patternssupport weak references built-in functions and most built-in types such as listsdictionariesstringsand numbers cannot be used if iteration is ever used on weakkeydictionary or weakvaluedictionarygreat care should be taken to ensure that the dictionary does not change size because this may produce bizarre side effects such as items mysteriously disappearing from the dictionary for no apparent reason if an exception occurs during the execution of callback registered with ref(or proxy()the exception is printed to standard error and ignored weak references are hashable as long as the original object is hashable moreoverthe weak reference will maintain its hash value after the original object has been deletedprovided that the original hash value is computed while the object still exists weak references can be tested for equality but not for ordering if the objects are still alivereferences are equal if the underlying objects have the same value otherwisereferences are equal if they are the same reference lib fl ff |
18,090 | mathematics his describes modules for performing various kinds of mathematical operations in additionthe decimal modulewhich provides generalized support for decimal floating-point numbersis described decimal the python float data type is represented using double-precision binary floatingpoint encoding (usually as defined by the ieee standarda subtle consequence of this encoding is that decimal values such as can' be represented exactly insteadthe closest value is this inexactness carries over to calculations involving floating-point numbers and can sometimes lead to unexpected results (for example * = evaluates as falsethe decimal module provides an implementation of the ibm general decimal arithmetic standardwhich allows for the exact representation of decimals it also gives precise control over mathematical precisionsignificant digitsand rounding behavior these features can be useful if interacting with external systems that precisely define properties of decimal numbers for exampleif writing python programs that must interact with business applications the decimal module defines two basic data typesa decimal type that represents decimal number and context type that represents various parameters concerning computation such as precision and round-off error-handling here are few simple examples that illustrate the basics of how the module worksimport decimal decimal decimal(' ' decimal decimal(' 'create some decimal numbers perform some math calculations using the default context decimal decimal(' ' decimal decimal(' 'change the precision and perform calculations decimal getcontext(prec decimal decimal(' ' decimal decimal(' 'change the precision for just single block of statements with decimal localcontext(decimal context(prec= )) decimal decimal(' ' decimal decimal(' ' lib fl ff |
18,091 | mathematics decimal objects decimal numbers are represented by the following classdecimal([value [context]]value is the value of the number specified as either an integera string containing decimal value such as ' 'or tuple (signdigitsexponentif tuple is suppliedsign is for positive for negativedigits is tuple of digits specified as integersand exponent is an integer exponent the special strings 'infinity''-infinity''nan'and 'snanmay be used to specify positive and negative infinity as well as not number (nan'snanis variant of nan that results in an exception if it is ever subsequently used in calculation an ordinary float object may not be used as the initial value because that value may not be exact (which defeats the purpose of using decimal in the first placethe context parameter is context objectwhich is described later if suppliedcontext determines what happens if the initial value is not valid number--raising an exception or returning decimal with the value nan the following examples show how to create various decimal numbersa decimal decimal( creates decimal(" " decimal decimal(" "creates decimal(" " decimal decimal(( ,( , , , ),- )creates decimal("- " decimal decimal("infinity" decimal decimal("nan"decimal objects are immutable and have all the usual numeric properties of the built-in int and float types they can also be used as dictionary keysplaced in setssortedand so forth for the most partyou manipulate decimal objects using the standard python math operators howeverthe methods in the following list can be used to carry out several common mathematical operations all operations take an optional context parameter that controls the behavior of precisionroundingand other aspects of the calculation if omittedthe current context is used method description exp([context] fma(yz [context] ln([context] log ([context] sqrt([context]natural exponent ** * with no rounding of * component natural logarithm (base eof base- logarithm of square root of context objects various properties of decimal numberssuch as rounding and precisionare controlled through the use of context objectf lib fl ff |
18,092 | context(prec=nonerounding=nonetraps=noneflags=noneemin=noneemax=nonecapitals= this creates new decimal context the parameters should be specified using keyword arguments with the names shown prec is an integer that sets the number of digits of precision for arithmetic operationsrounding determines the rounding behaviorand traps is list of signals that produce python exception when certain events occur during computation (such as division by zeroflags is list of signals that indicate the initial state of the context (such as overflownormallyflags is not specified emin and emax are integers representing the minimum and maximum range for exponentsrespectively capitals is boolean flag that indicates whether to use 'eor 'efor exponents the default is (' 'normallynew context objects aren' created directly insteadthe function getcontext(or localcontext(is used to return the currently active context object that object is then modified as needed examples of this appear later in this section howeverin order to better understand those examplesit is necessary to explain these context parameters in further detail rounding behavior is determined by setting the rounding parameter to one of the following valuesconstant description round_ceiling rounds toward positive infinity for example rounds up to and - rounds up to - rounds toward zero for example rounds down to and - rounds up to - rounds toward negative infinity for example rounds down to and - rounds down to - rounds away from zero if the fractional part is greater than halfotherwiserounds toward zero for example rounds up to rounds down to - rounds up to - and - rounds down to - the same as round_half_down except that if the fractional part is exactly halfthe result is rounded down if the preceding digit is even and rounded up if the preceding digit is odd for example is rounded down to and is rounded up to the same as round_half_down except that if the fractional part is exactly halfit is rounded away from zero for example rounds up to and - rounds down to - rounds away from zero for example rounds up to and rounds down to - rounds away from zero if the last digit after toward zero would have been or otherwiserounds toward zero for example rounds to and rounds to round_down round_floor round_half_down round_half_even round_half_up round_up round_ up the traps and flags parameters of context(are lists of signals signal represents type of arithmetic exception that may occur during computation unless listed in trapssignals are ignored otherwisean exception is raised the following signals are definedf lib fl ff |
18,093 | mathematics signal description clamped divisionbyzero inexact invalidoperation exponent adjusted to fit the allowed range division of non-infinite number by rounding error occurred invalid operation performed exponent exceeds emax after rounding also generates inexact and rounded rounding occurred may occur even if no information was lost (for example" rounded to " "exponent is less than emin prior to rounding numerical underflow result rounded to also generates inexact and subnormal overflow rounded subnormal underflow these signal names correspond to python exceptions that can be used for error checking here' an exampletryx / except decimal divisionbyzeroprint "division by zerolike exceptionsthe signals are organized into hierarchyarithmeticerror (built-in exceptiondecimalexception clamped divisionbyzero inexact overflow underflow invalidoperation rounded overflow underflow subnormal underflow the overflow and underflow signals appear more than once in the table because those signals also result in the parent signal (for examplean underflow also signals subnormalthe decimal divisionbyzero signal also derives from the built-in divisionbyzero exception in many casesarithmetic signals are silently ignored for instancea computation may produce round-off error but generate no exception in this casethe signal names can be used to check set of sticky flags that indicate computation state here' an examplectxt decimal getcontext(get current context if ctxt flags[rounded]print "result was rounded! lib fl ff |
18,094 | when flags get setthey stay set until they are cleared using the clear_flags(method thusone could perform an entire sequence of calculations and only check for errors at the end the settings on an existing context object can be changed through the following attributes and methodsc capitals flag set to or that determines whether to use or as the exponent character emax integer specifying maximum exponent emin integer specifying minimum exponent prec integer specifying digits of precision flags dictionary containing current flag values corresponding to signals for examplec flags[roundedreturns the current flag value for the rounded signal rounding rounding rule in effect an example is round_half_even traps dictionary containing true/false settings for the signals that result in python exceptions for examplec traps[divisionbyzerois usually truewhereas traps[roundedis false clear_flags(resets all sticky flags (clears flagsc copy(returns copy of context create_decimal(valuecreates new decimal object using as the context this may be useful in generating numbers whose precision and rounding behavior override that of the default context functions and constants the following functions and constants are defined by the decimal module getcontext(returns the current decimal context each thread has its own decimal context so this returns the context of the calling thread lib fl ff |
18,095 | mathematics localcontext([ ]creates context manager that sets the current decimal context to copy of for statements defined inside the body of with statement if is omitteda copy of the current context is created here is an example of using this function that temporarily sets the precision to five decimal places for series of statementswith localcontext(as cc prec statements setcontext(csets the decimal context of the calling thread to basiccontext premade context with nine digits of precision rounding is round_half_upemin is - emax is and all traps are enabled except for inexactroundedand subnormal defaultcontext the default context used when creating new contexts (the values stored here are used as default values for the new contextdefines digits of precisionround_half_even roundingand traps for overflowinvalidoperationand divisionbyzero extendedcontext premade context with nine digits of precision rounding is round_half_evenemin is - emax is and all traps are disabled never raises exceptions insteadresults may be set to nan or infinity inf the same as decimal("infinity"neginf the same as decimal("-infinity"nan the same as decimal("nan"examples here are some more examples showing basic usage of decimal numbersa decimal(" " decimal(" " decimal(" " decimal(" "divmod( , (decimal(" ")decimal(" ")max( ,bdecimal(" " [decimal(" ")decimal(" ")decimal(" ")sum(cdecimal(" " lib fl ff |
18,096 | [ * for in [decimal(" ")decimal(" ")decimal(" ")float( str( ' here' an example of changing parameters in the contextgetcontext(prec decimal(" " decimal(" " decimal(" "getcontext(flags[rounded getcontext(flags[rounded decimal(" "traceback (most recent call last)file ""line in decimal divisionbyzerox getcontext(traps[divisionbyzerofalse decimal(" "decimal("infinity"notes the decimal and context objects have large number of methods related to low-level details concerning the representation and behavior of decimal operations these have not been documented here because they are not essential for the basic use of this module howeveryou should consult the online documentation at the decimal context is unique to each thread changes to the context only affect that thread and not others special numberdecimal("snan")may be used as signaled-nan this number is never generated by any of the built-in functions howeverif it appears in computationan error is always signaled you can use this to indicate invalid computations that must result in an error and must not be silently ignored for examplea function could return snan as result the value of may be positive or negative (that isdecimal( and decimal ("- ")the distinct zeros still compare as equals this module is probably unsuitable for high-performance scientific computing due to the significant amount of overhead involved in calculations alsothere is often little practical benefit in using decimal floating point over binary floating point in such applications full mathematical discussion of floating-point representation and error analysis is beyond the scope of this book readers should consult book on numerical analysis for further details the article "what every computer scientist should lib fl ff |
18,097 | mathematics know about floating-point arithmeticby david goldbergin computing surveysassociation for computing machinerymarch is also worthy read (this article is easy to find on the internet if you simply search for the titlen the ibm general decimal arithmetic specification contains more information and can be easily located online through search engines fractions the fractions module defines class fraction that represents rational number instances can be created in three different ways using the class constructorfraction([numerator [,denominator]]creates new rational number numerator and denominator have integral values and default to and respectively fraction(fractionif fraction is an instance of numbers rationalcreates new rational number with the same value as fraction fraction(sif is string containing fraction such as " / or "- / " fraction with the same value is created if is decimal number such as " " fraction with that value is created ( fraction( , )the following class methods can create fraction instances from other types of objectsfraction from_float(fcreates fraction representing the exact value of the floating-point number fraction from_decimal(dcreates fraction representing the exact value of the decimal number here are some examples of using these functionsf fractions fraction( , fractions fraction(" " fraction( fractions fraction from_float( fraction( an instance of fraction supports all of the usual mathematical operations the numerator and denominator are stored in the numerator and denominator attributesrespectively in additionthe following method is definedf limit_denominator([max_denominator]returns the fraction that has the closest value to max_denominator specifies the largest denominator to use and defaults to lib fl ff |
18,098 | here are some examples of using fraction instances (using the values created in the earlier example) fraction( fraction( limit_denominator( fraction( the fractions module also defines single functiongcd(abcomputes the greatest common divisor of integers and the result has the same sign as if is nonzerootherwiseit' the same sign as math the math module defines the following standard mathematical functions these functions operate on integers and floats but don' work with complex numbers ( separate module cmath can be used to perform similar operations on complex numbersthe return value of all functions is float all trigonometric functions assume the use of radians function description acos(xacosh(xasin(xasinh(xatan(xatan (yxatanh(xceil(xcopysign( ,ycos(xcosh(xdegrees(xradians(xexp(xfabs(xfactorial(xreturns the arc cosine of returns the hyperbolic arc cosine of returns the arc sine of returns the hyperbolic arc sine of returns the arc tangent of returns atan( xreturns the hyperbolic arc tangent of returns the ceiling of returns with the same sign as returns the cosine of returns the hyperbolic cosine of converts from radians to degrees converts from degrees to radians returns * returns the absolute value of returns factorial returns the floor of returns as computed by the fmod(function returns the positive mantissa and exponent of as tuple returns the full precision sum of floating-point values in the iterable sequence see the following note for description returns the euclidean distancesqrt( yfloor(xfmod(xyfrexp(xfsum(shypot(xycontinues lib fl ff |
18,099 | function description isinf(xisnan(xldexp(xilog( [base]return true if is infinity returns true if is nan returns ( *ireturns the logarithm of to the given base if base is omittedthis function computes the natural logarithm returns the base logarithm of returns the natural logarithm of + returns the fractional and integer parts of as tuple both have the same sign as returns * returns the sine of returns the hyperbolic sine of returns the square root of returns the tangent of returns the hyperbolic tangent of truncates to the nearest integer towards log (xlog (xmodf(xpow(xysin(xsinh(xsqrt(xtan(xtanh(xtrunc(xthe following constants are definedconstant description pi mathematical constant pi mathematical constant notes the floating-point values +inf-infand nan can be created by passing strings into the float(function--for examplefloat("inf")float("-inf")or float("nan" the math fsum(function is more accurate than the built-in sum(function because it uses different algorithm that tries to avoid floating-point errors introduced by cancellation effects for exampleconsider the sequence [ - if you use sum( )you will get result of (because the value of is lost when added to the large value howeverusing math sum(sproduces the correct result of the algorithm used by math sum(is described in "adaptive precision floating-point arithmetic and fast robust geometric predicatesby jonathan richard shewchukcarnegie mellon university school of computer science technical report cmu-cs- numbers the numbers module defines series of abstract base classes that serve to organize various kinds of numbers the numeric classes are organized into hierarchy in which each level progressively adds more capabilities lib fl ff |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.