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 cr... |
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 interpret... |
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 woul... |
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 nam... |
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 d... |
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 '\nc... |
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(re... |
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 ... |
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... |
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... |
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 clea... |
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... |
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... |
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 r... |
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 ... |
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 'asciiencod... |
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 en... |
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 ... |
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 ... |
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 behavi... |
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... |
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-indepe... |
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... |
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 mo... |
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 directo... |
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... |
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 ca... |
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 ar... |
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 writin... |
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 d... |
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 a... |
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... |
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... |
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 indicat... |
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 o... |
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 (eturn... |
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 pr... |
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... |
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 num... |
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 defin... |
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 t... |
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 nameshowe... |
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... |
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 form... |
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 ... |
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 numbe... |
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 represen... |
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 i... |
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 cop... |
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 o... |
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 supplied... |
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... |
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 o... |
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... |
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... |
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 obje... |
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 ex... |
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... |
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' f... |
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 valu... |
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 is... |
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(functioniter... |
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 interpre... |
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 ob... |
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 deb... |
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... |
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 c... |
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 pyc... |
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(objectre... |
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 insteadhowever... |
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 i... |
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... |
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 (p... |
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... |
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 ... |
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-indepe... |
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 ... |
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... |
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 ad... |
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 s... |
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 codet... |
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 ab... |
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_... |
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 expressionsfo... |
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 ob... |
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 result... |
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 defi... |
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 digit... |
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 behavior... |
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 ... |
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 determine... |
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 ser... |
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[div... |
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... |
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 ... |
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 intege... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.