id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
18,400 | get_charset(returns the character set associated with the message payload (for instance'iso- - ' get_charsets([default]returns list of all character sets that appear in the message for multipart messagesthe list will represent the character set of each subpart the character set of each part is taken from 'content-typeheaders that appear in the message if no character set is specified or the content-type header is missingthe character set for that part is set to the value of default (which is none by defaultm get_content_charset([default]returns the character set from the first 'content-typeheader in the message if the header is not found or no character set is specifieddefault is returned get_content_maintype(returns the main content type (for example'textor 'multipart' get_content_subtype(returns the subcontent type (for example'plainor 'mixed' get_content_type(returns string containing the message content type (for example'multipart/mixedor 'text/plain' get_default_type(returns the default content type (for example'text/plainfor simple messagesm get_filename([default]returns the filename parameter from 'content-dispositionheaderif any returns default if the header is missing or does not have filename parameter get_param(param [default [header [unquote]]]email headers often have parameters attached to them such as the 'charsetand 'formatparts of the header 'content-typetext/plaincharset="utf- "format=flowedthis method returns the value of specific header parameter param is parameter namedefault is default value to return if the parameter is not foundheader is the name of the headerand unquote specifies whether or not to unquote the parameter if no value is given for headerparameters are taken from the 'content-typeheader the default value of unquote is true the return value is either string or -tuple (charsetlanguagevaluein the event the parameter was encoded according to rfc- conventions in this casecharset is string such as 'iso- - 'language is string containing language code such as 'en'and value is the parameter value get_params([default [header [unquote]]]returns all parameters for header as list default specifies the value to return if the header isn' found if header is omittedthe 'content-typeheader is used unquote is flag that specifies whether or not to unquote values (true by defaultthe contents lib fl ff |
18,401 | internet data handling and encoding of the returned list are tuples (namevaluewhere name is the parameter name and value is the value as returned by the get_param(method get_payload([ [decode]]returns the payload of message if the message is simple messagea byte string containing the message body is returned if the message is multipart messagea list containing all the subparts is returned for multipart messagesi specifies an optional index in this list if suppliedonly that message component will be returned if decode is truethe payload is decoded according to the setting of any 'content-transfer-encodingheader that might be present (for example'quoted-printable''base 'and so onto decode the payload of simple nonmultipart messageset to none and decode to true or specify decode using keyword argument it should be emphasized that the payload is returned as byte string containing the raw content if the payload represents text encoded in utf- or some other encodingyou will need to use the decode(method on the result to convert it get_unixfrom(returns the unix-style 'from lineif any is_multipart(returns true if is multipart message walk(creates generator that iterates over all the subparts of messageeach of which is also represented by message instance the iteration is depth-first traversal of the message typicallythis function could be used to process all the components of multipart message finallymessage instances have few attributes that are related to low-level parsing process preamble any text that appears in multipart message between the blank line that signals the end of the headers and the first occurrence of the multipart boundary string that marks the first subpart of the message epilogue any text in the message that appears after the last multipart boundary string and the end of the message defects list of all message defects found when parsing the message consult the online documentation for the email errors module for further details the following example illustrates how the message class is used while parsing an email message the following code reads an email messageprints short summary of useful headersprints the plain text portions of the messageand saves any attachments import email import sys open(sys argv[ ]," " email message_from_file(fopen message file parse message lib fl ff |
18,402 | print short summary of sender/recipient print("from %sm["from"]print("to %sm["to"]print("subject %sm["subject"]print(""if not is_multipart()simple message just print the payload payload get_payload(decode=truecharset get_content_charset('iso- - 'print(payload decode(charset)elsemultipart message walk over all subparts and print text/plain fragments save any attachments for in walk()filename get_filename(if filenameprint("saving attachment%sfilenamedata get_payload(decode=trueopen(filename,"wb"write(dataelseif get_content_type(='text/plain'payload get_payload(decode=truecharset get_content_charset('iso- - 'print(payload decode(charset)in this exampleit is important to emphasize that operations that extract the payload of message always return byte strings if the payload represents textyou also need to decode it according to some character set the get_content_charset(and payload decode(operations in the example are carrying out this conversion composing email to compose an email messageyou can either create an empty instance of message objectwhich is defined in the email message moduleor you can use message object that was created by parsing an email message (see the previous sectionmessage(creates new message that is initially empty an instance of message supports the following methods for populating message with contentheadersand other information add_header(namevalue**paramsadds new message header name is the name of the headervalue is the value of the headerand params is set of keyword arguments that supply additional optional parameters for exampleadd_header('foo','bar',spam='major'adds the header line 'foobarspam="major"to the message as_string([unixfrom]converts the entire message to string unixfrom is boolean flag if this is set to truea unix-style 'from line appears as the first line by defaultunixfrom is false lib fl ff |
18,403 | internet data handling and encoding attach(payloadadds an attachment to multipart message payload must be another message object (for exampleemail mime text mimetextinternallypayload is appended to list that keeps track of the different parts of the message if the message is not multipart messageuse set_payload(to set the body of message to simple string del_param(param [header [requote]]deletes the parameter param from header header for exampleif message has the header 'foobarspam="major"'del_param('spam','foo'would delete the 'spam="major"portion of the header if requote is true (the default)all remaining values are quoted when the header is rewritten if header is omittedthe operation is applied to the 'content-typeheader replace_header(namevaluereplaces the value of the first occurrence of the header name with value value raises keyerror if the header is not found set_boundary(boundarysets the boundary parameter of message to the string boundary this string gets added as the boundary parameter to the 'content-typeheader in the message raises headerparseerror if the message has no content-type header set_charset(charsetsets the default character set used by message charset may be string such as 'iso- - or 'euc-jpsetting character set normally adds parameter to the 'content-typeheader of message (for example'content-typetext/htmlcharset="iso- - "' set_default_type(ctypesets the default message content type to ctype ctype is string containing mime type such as 'text/plainor 'message/rfc this type is not stored in the 'content-typeheader of the message set_param(paramvalue [header [requote [charset [language]]]]sets the value of header parameter param is the parameter nameand value is the parameter value header specifies the name of the header and defaults to 'content-typerequote specifies whether or not to requote all the values in the header after adding the parameter by defaultthis is true charset and language specify optional character set and language information if these are suppliedthe parameter is encoded according to rfc- this produces parameter text such as param*="'iso- - 'en-us'some% valuem set_payload(payload [charset]sets the entire message payload to payload for simple messagespayload can be byte string containing the message body for multipart messagespayload is list of message objects charset optionally specifies the character set that was used to encode the text (see set_charsetf lib fl ff |
18,404 | set_type(type [header [requote]]sets the type used in the 'content-typeheader type is string specifying the typesuch as 'text/plainor 'multipart/mixedheader specifies an alternative header other than the default 'content-typeheader requote quotes the value of any parameters already attached to the header by defaultthis is true set_unixfrom(unixfromsets the text of the unix-style 'from line unixfrom is string containing the complete text including the 'fromtext this text is only output if the unixfrom parameter of as_string(is set to true rather than creating raw message objects and building them up from scratch each timethere are collection of prebuilt message objects corresponding to different types of content these message objects are especially useful for creating multipart mime messages for instanceyou would create new message and attach different parts using the attach(method of message each of these objects is defined in different submodulewhich is noted in each description mimeapplication(data [subtype [encoder [**params]]]defined in email mime application creates message containing application data data is byte string containing the raw data subtype specifies the data subtype and is 'octet-streamby default encoder is an optional encoding function from the email encoders subpackage by defaultdata is encoded as base params represents optional keyword arguments and values that will be added to the 'content-typeheader of the message mimeaudio(data [subtype [encoder [**params]]]defined in email mime audio creates message containing audio data data is byte string containing the raw binary audio data subtype specifies the type of the data and is string such as 'mpegor 'wavif no subtype is providedthe audio type will be guessed by looking at the data using the sndhdr module encoder and params have the same meaning as for mimeapplication mimeimage(data [subtype [encoder [**params]]]defined in email mime image creates message containing image data data is byte string containing the raw image data subtype specifies the image type and is string such as 'jpgor 'pngif no subtype is providedthe type will be guessed using function in the imghdr module encoder and params have the same meaning as for mimeapplication mimemessage(msg [subtype]defined in email mime message creates new non-multipart mime message msg is message object containing the initial payload of the message subtype is the type of the message and defaults to 'rfc mimemultipart([subtype [boundary [subparts [**params]]]]defined in email mime multipart creates new mime multipart message subtype specifies the optional subtype to be added to the 'content-typemultipart/subtypeheader by defaultsubtype is 'mixedboundary is string that specifies the boundary separator used to make each message subpart if set to none lib fl ff |
18,405 | or omitteda suitable boundary is determined automatically subparts is sequence of message objects that make up the contents of the message params represents optional keyword arguments and values that are added to the 'content-typeheader of the message once multipart message has been createdadditional subparts can be added using the message attach(method mimetext(data [subtype [charset]]defined in email mime text creates message containing textual data data is string containing the message payload subtype specifies the text type and is string such as 'plain(the defaultor 'htmlcharset is the character setwhich defaults to 'us-asciithe message may be encoded depending on the contents of the message the following example shows how to compose and send an email message using the classes in this sectionimport smtplib from email mime text import mimetext from email mime multipart import mimemultipart from email mime audio import mimeaudio sender "jon@nogodiggydie netreceiver"dave@dabeaz comsubject "faders up!body " never should have moved out of texas - \naudio "texasfuneral mp mimemultipart( ["to"receiver ["from"sender ["subject"subject attach(mimetext(body)apart mimeaudio(open(audio,"rb"read(),"mpeg"apart add_header("content-disposition","attachment",filename=audiom attach(apartsend the email message smtplib smtp( connect( sendmail(sender[receiver], as_string() close(notes number of advanced customization and configuration options have not been discussed readers should consult the online documentation for advanced uses of this module the email package has gone through at least four different versionswhere the underlying programming interface has been changed ( submodules renamedclasses moved to different locationsetc this section has documented version of the interface that is used in both python and python if you are working with legacy codethe basic concepts still applybut you may have to adjust the locations of classes and submodules lib fl ff |
18,406 | hashlib the hashlib module implements variety of secure hash and message digest algorithms such as md and sha to compute hash valueyou start by calling one of the following functionsthe name of which is the same as represented algorithmfunction description md (sha (sha (sha (md hash ( bitssha hash ( bitssha hash ( bitssha hash ( bitssha hash ( bitssha hash ( bitssha (sha (an instance of the digest object returned by any of these functions has the following interfacemethod or attribute description update(dataupdates the hash with new data data must be byte string repeated calls are the same as single call with concatenated data returns the value of the digest as raw byte string returns text string with the value of the digest encoded as series of hex digits returns copy of the digest the copy preserves the internal state of the original digest size of the resulting hash in bytes internal block size of the hash algorithm in bytes digest( hexdigest( copy( digest_size block_size an alternative construction interface is also provided by the modulenew(hashnamecreates new digest object hashname is string such as 'md or 'sha specifying the name of the hashing algorithm to use the name of the hash can minimally be any of the previous hashing algorithms or hashing algorithm exposed by the openssl library (which depends on the installationhmac the hmac module provides support for hmac (keyed-hashing for message authentication)which is described in rfc- hmac is mechanism used for message authentication that is built upon cryptographic hashing functions such as md and sha- new(key [msg [digest]]creates new hmac object herekey is byte string containing the starting key for the hashmsg contains initial data to processand digest is the digest constructor that should be used for cryptographic hashing by defaultdigest is hashlib md lib fl ff |
18,407 | internet data handling and encoding normallythe initial key value is determined at random using cryptographically strong random number generator an hmac objecthhas the following methodsh update(msgadds the string msg to the hmac object digest(returns the digest of all data processed so far and returns byte string containing the digest value the length of the string depends on the underlying hashing function for md it is charactersfor sha- it is characters hexdigest(returns the digest as string of hexadecimal digits copy(makes copy of the hmac object example the primary use of the hmac module is in applications that need to authenticate the sender of message to do thisthe key parameter to new(is byte string representing secret key known by both the sender and receiver of message when sending messagethe sender will create new hmac object with the given keyupdate the object with message data to be sentand then send the message data along with the resulting hmac digest value to the receiver the receiver can verify the message by computing its own hmac digest value (using the same key and message dataand comparing the result to the digest value received here is an exampleimport hmac secret_key "peekaboodata "hello worldbyte string only known to me typically you would want to use string of random bytes computed using os urandom(or similar the message to send send the message somewhere out represents socket or some other / channel on which we are sending data hmac new(secret_keyh update(dataout send(datasend the data out send( digest()send the digest receive the message in represents socket or some other / channel out which we are receiving data hmac new(secret_keydata in receive(get the message data update(datadigest in receive(get the digest sent by the sender if digest ! digest()raise authenticationerror('message not authenticated' lib fl ff |
18,408 | htmlparser in python this module is called html parser the htmlparser module defines class htmlparser that can be used to parse html and xhtml documents to use this moduleyou define your own class that inherits from htmlparser and redefines methods as appropriate htmlparser(this is base class that is used to create html parsers it is initialized without any arguments an instance of htmlparser has the following methodsh close(closes the parser and forces the processing of any remaining unparsed data this method is called after all html data has been fed to the parser feed(datasupplies new data to the parser this data will be immediately parsed howeverif the data is incomplete (for exampleit ends with an incomplete html element)the incomplete portion will be buffered and parsed the next time feed(is called with more data getpos(returns the current line number and character offset into that line as tuple (lineoffseth get_starttag_text(returns the text corresponding to the most recently opened start tag handle_charref(namethis handler method is called whenever character reference such as '&#ref;is encountered name is string containing the name of the reference for examplewhen parsing '&# ;'name will be set to ' handle_comment(datathis handler method is called whenever comment is encountered data is string containing the text of the comment for examplewhen parsing the comment ''data will contain the text 'commenth handle_data(datathis handler is called to process data that appears between tags data is string containing text handle_decl(declthis handler is called to process declarations such as 'decl is string containing the text of the declaration not including the leading '<!and trailing '> lib fl ff |
18,409 | internet data handling and encoding handle_endtag(tagthis handler is called whenever end tags are encountered tag is the name of the tag converted to lowercase for exampleif the end tag is ''tag is the string 'bodyh handle_entityref(namethis handler is called to handle entity references such as '&name;name is string containing the name of the reference for exampleif parsing '<'name will be set to 'lth handle_pi(datathis handler is called to handle processing instructions such as '<?processing instruction>data is string containing the text of the processing instruction not including the leading 'when called on xhtml-style instructions of the form ''the last '?will be included in data handle_startendtag(tagattrsthis handler processes xhtml-style empty tags such as '<tag name="value/>tag is string containing the name of the tag attrs contains attribute information and is list of tuples of the form (namevaluewhere name is the attribute name converted to lowercase and value is the attribute value when extracting valuesquotes and character entities are replaced for exampleif parsing '< href="[('href','implementation of this method simply calls handle_starttag(and handle_endtag( handle_starttag(tagattrsthis handler processes start tags such as 'tag and attrs have the same meaning as described for handle_startendtag( reset(resets the parserdiscarding any unprocessed data the following exception is providedhtmlparsererror exception raised as result of parsing errors the exception has three attributes the msg attribute contains message describing the errorthe lineno attribute is the line number where the parsing error occurredand the offset attribute is the character offset into the line example the following example fetches an html document using the urllib package and prints all links that have been specified with 'declarationsprintlinks py tryfrom htmlparser import htmlparser from urllib import urlopen except importerrorfrom html parser import htmlparser lib fl ff |
18,410 | from urllib request import urlopen import sys class printlinks(htmlparser)def handle_starttag(self,tag,attrs)if tag =' 'for name,value in attrsif name ='href'print(valuep printlinks( urlopen(sys argv[ ]data read(charset info(getparam('charset'#charset info(get_content_charset( feed(data decode(charset) close(python python in the exampleit must be noted that any html fetched using urllib is returned as byte string to properly parse itit must be decoded into text according to the document character set encoding the example shows how to obtain this in python and python note the parsing capabilities of htmlparser tend to be rather limited in factwith very complicated and/or malformed htmlthe parser can break users also find this module to be lower-level than is useful if you are writing programs that must scrape data from html pagesconsider the beautiful soup package (pypi/beautifulsoupjson the json module is used to serialize and unserialize objects represented using javascript object notation (jsonmore information about json is available at incidentallyit' almost the same as python syntax for representing lists and dictionaries for examplea json array is written as [value value ]and json object is written as {name:valuename:valuethe following list shows how json values and python values are mapped the python types listed in parentheses are accepted when encoding but are not returned when decoding (insteadthe first listed type is returnedjson type python type object array string number true false null dict list (tupleunicode (strbytesintfloat true false none lib fl ff |
18,411 | internet data handling and encoding for string datayou should assume the use of unicode if byte strings are encountered during encodingthey will be decoded into unicode string using 'utf- by default (although this can be controlledjson strings are always returned as unicode when decoding the following functions are used to encode/decode json documentsdump(objf**optsserializes obj to file-like object opts represents collection of keyword arguments that can be specified to control the serialization processkeyword argument description skipkeys boolean flag that controls what to do when dictionary keys (not the valuesare not basic type such as string or number if truethe keys are skipped if false (the default) typeerror is raised boolean flag that determines whether or not unicode strings can be written to the file by defaultthis is false only set this to true if is file that correctly handles unicodesuch as file created by the codecs module or opened with specific encoding set boolean flag that determines whether circular references are checked for containers by defaultthis is true if set to false and circular reference is encounteredan overflowerror exception is raised boolean flag that determines whether out-of-range floating-point values are serialized ( naninf-infby default this is true subclass of jsonencoder to use you would specify this if you created your own custom encoder by inheriting from jsonencoder if there are any additional keyword arguments given to dump()they are passed as arguments to the constructor of this class non-negative integer that sets the amount indentation to use when printing array and object members setting this results in kind of pretty-printing by defaultit is nonewhich causes the result to be in the most compact representation tuple of the form (item_separatordict_separatorwhere item_separator is string containing the separator used between array items and dict_separator is string containing the separator used between dictionary keys and values by defaultthe value is (''''encoding to use for unicode strings--'utf- by default function used to serialize objects that are not any of the basic supported types it should either return value that can be serialized ( stringor raise typeerror by defaulta typeerror is raised for unsupported types ensure_ascii check_circular allow_nan cls indent separators encoding default dumps(obj**optsthe same as dump(except that string containing the result is returned lib fl ff |
18,412 | load( **optsdeserializes json object on the file-like object and returns it opts represents set of keyword arguments that can be specified to control the decoding process and are described next be aware that this function calls read(to consume the entire contents of because of thisit should not be used on any kind of streaming file such as socket where json data might be received as part of larger or ongoing data stream keyword argument description encoding encoding used to interpret any of the string values that are decoded by defaultthis is 'utf- boolean flag that determines whether or not literal (unescapednewlines are allowed to appear in json strings by defaultthis is truewhich means that an exception is generated for such strings subclass of jsondecoder to use for decoding only specified if you've created custom decoder by inheriting from jsondecoder any extra keyword arguments to load(are supplied to the class constructor function that' called with the result of every json object that is decoded by defaultthis is the built-in dict(function function that' called to decode json floating-point values by defaultthis is the built-in float(function function that' called to decode json integer values by defaultthis is the built-in int(function function that' called to decode json constants such as 'nan''true''false'etc strict cls object_hook parse_float parse_int parse_constant loads( **optsthe same as load(except that an object is deserialized from the string although these functions share the same names as functions from the pickle and marshal modules and they serialize datathey are not used in the same way specificallyyou should not use dump(to write more than one json-encoded object to the same file similarlyload(cannot be used to read more than one json-encoded object from the same file (if the input file has more than one object in ityou'll get an errorjson-encoded objects should be treated in the same manner as html or xml for exampleyou usually don' take two completely separate xml documents and just concatenate them together in the same file if you want to customize the encoding or decoding processinherit from these base classesjsondecoder(**optsa class that decodes json data opts represents set of keyword arguments that are identical to those used by the load(function an instance of jsondecoder has the following two methodsd decode(sreturns the python representation of the json object in is string lib fl ff |
18,413 | internet data handling and encoding raw_decode(sreturns tuple (pyobjindexwhere pyobj is the python representation of json object in and index is the position in where the json object ended this can be used if you are trying to parse an object out of an input stream where there is extra data at the end jsonencoder(**optsa class that encodes python object into json opts represents set of keyword arguments that are identical to those used by the dump(function an instance of jsonencoder has the following methodse default(objmethod called when python object obj can' be encoded according to any of the normal encoding rules the method should return result which is one of the types that can be encoded (for examplea stringlistor dictionarye encode(objmethod that' called to create json representation of python object obj iterencode(objcreates an iterator that produces the strings making up the json representation of python object obj as they are computed the process of creating json string is highly recursive in nature for instanceit involves iterating over the keys of dictionary and traversing down into other dictionaries and lists found along the way if you use this methodyou can process the output in piecemeal manner as opposed to having everything collected into huge in-memory string if you define subclasses that inherit from jsondecoder or jsonencoderyou need to exercise caution if your class also defines _init_ (to deal with all of the keyword argumentshere is how you should define itclass myjsondecoder(jsondecoder)def _init_ (self**kwargs)get my own arguments foo kwargs pop('foo',nonebar kwargs pop('bar',noneinitialize the parent with everything left over jsondecoder _init_ (self,**kwargsmimetypes the mimetypes module is used to guess the mime type associated with filebased on its filename extension it also converts mime types to their standard filename extensions mime types consist of type/subtype pair--for example 'text/html''image/png'or 'audio/mpegguess_type(filename [strict]guesses the mime type of file based on its filename or url returns tuple (typeencodingin which type is string of the form "type/subtypeand encoding is the program used to encode the data for transfer (for examplecompress or gzipreturns (nonenoneif the type cannot be guessed if strict is true (the lib fl ff |
18,414 | default)then only official mime types registered with iana are recognized (see guess_extension(type [strict]guesses the standard file extension for file based on its mime type returns string with the filename extension including the leading dot returns none for unknown types if strict is true (the default)then only official mime types are recognized guess_all_extensions(type [strict]the same as guess_extension(but returns list of all possible filename extensions init([files]initializes the module files is sequence of filenames that are read to extract type information these files contain lines that map mime type to list of acceptable file suffixes such as the followingimage/jpegtext/htmljpe jpeg jpg htm html read_mime_types(filenameloads type mapping from given filename returns dictionary mapping filename extensions to mime type strings returns none if filename doesn' exist or cannot be read add_type(typeext [strict]adds new mime type to the mapping type is mime type such as 'text/plain'ext is filename extension such as txt'and strict is boolean indicating whether the type is an officially registered mime type by defaultstrict is true quopri the quopri module performs quoted-printable transport encoding and decoding of byte strings this format is used primarily to encode -bit text files that are mostly readable as ascii but which may contain small number of non-printing or special characters (for examplecontrol characters or non-ascii characters in the range - the following rules describe how the quoted-printable encoding worksn any printable non-whitespace ascii characterwith the exception of '='is represented as is the '=character is used as an escape character when followed by two hexadecimal digitsit represents character with that value (for example'= 'the equals sign is represented by '= dif '=appears at the end of lineit denotes soft line break this only occurs if long line of input text must be split into multiple output lines spaces and tabs are left as is but may not appear at the end of line lib fl ff |
18,415 | internet data handling and encoding it is fairly common to see this format used when documents make use of special characters in the extended ascii character set for exampleif document contained the text "copyright ( "this might be represented by the python byte string 'copyright \xa the quoted-printed version of the string is 'copyright = where the special character '\xa has been replaced by the escape sequence '= decode(inputoutput [header]decodes bytes into quopri format input and output are file objects opened in binary mode if header is truethen the underscore (_will be interpreted as space otherwiseit is left alone this is used when decoding mime headers that have been encoded by defaultheader is false decodestring( [header]decodes string may be unicode or byte stringbut the result is always byte string header has the same meaning as with decode(encode(inputoutputquotetabs [header]encodes bytes into quopri format input and output are file objects opened in binary mode quotetabsif set to trueforces tab characters to be quoted in addition to the normal quoting rules otherwisetabs are left as is by defaultquotetabs is false header has the same meaning as for decode(encodestring( [quotetabs [header]]encodes byte string the result is also byte string quotetabs and header have the same meaning as with encode(notes the quoted-printable data encoding predates unicode and is only applicable to -bit data even though it is most commonly applied to textit really only applies to ascii and extended ascii characters represented as single bytes when you use this modulemake sure all files are in binary mode and that you are working with byte strings xml package python includes variety of modules for processing xml data the topic of xml processing is largeand covering every detail is beyond the scope of this book this section assumes the reader is already familiar with some basic xml concepts book such as inside xml by steve holzner (new ridersor xml in nutshell by elliotte harold and scott means ( 'reilly and associateswill be useful in explaining basic xml concepts several books discuss xml processing with python including python xml by christopher jones ( 'reilly and associatesand xml processing with python by sean mcgrath (prentice hallpython provides two kinds of xml support firstthere is basic support for two industry-standard approaches to xml parsing--sax and dom sax (simple api for xmlis based on event handling where an xml document is read sequentially and as xml elements are encounteredhandler functions get triggered to perform processing dom (document object modelbuilds tree structure representing an entire xml lib fl ff |
18,416 | document once the tree has been builtdom provides an interface for traversing the tree and extracting data neither the sax nor dom apis originate with python insteadpython simply copies the standard programming interface that was developed for java and javascript although you can certainly process xml using the sax and dom interfacesthe most convenient programming interface in the standard library is the elementtree interface this is python-specific approach to xml parsing that takes full advantage of python language features and which most users find to be significantly easier and faster than sax or dom the rest of this section covers all three xml parsing approachesbut the elementtree approach is given the most detail readers are advised that the coverage here is really only focused on basic parsing of xml data python also includes xml modules related to implementing new kinds of parsersbuilding xml documents from scratchand so forth in additiona variety of third-party extensions extend python' capabilities with additional xml features such as support for xslt and xpath links to further information can be found at wiki python org/moin/pythonxml xml example document the following example illustrates typical xml documentin this case description of recipe famous guacamole southwest favoritelarge avocadoschopped tomatochopped white onionchopped fresh squeezed lemon juice jalapeno pepperdiced fresh cilantrominced garlicminced salt ice-cold beer combine all ingredients and hand whisk to desired consistency serve and enjoy with ice-cold beers the document consists of elements that start and end with tags such as elements are typically nested and organized into hierarchy-for examplethe elements that appear under within each documenta single element is the document root in the examplethis is the element elements optionally have attributes as shown for the item elements <item num=" ">large avocadoschopped working with xml documents typically involves all of these basic features for exampleyou may want to extract text and attributes from specific element types to lib fl ff |
18,417 | internet data handling and encoding locate elementsyou have to navigate through the document hierarchy starting at the root element xml dom minidom the xml dom minicom module provides basic support for parsing an xml document and storing it in memory as tree structure according to the conventions of dom there are two parsing functionsparse(file [parser]parses the contents of file and returns node representing the top of the document tree ile is filename or an already-open file object parser is an optional sax -compatible parser object that will be used to construct the tree if omitteda default parser will be used parsestring(string [parser]the same as parse()except that the input data is supplied in string instead of file nodes the document tree returned by the parsing functions consists of collection of nodes linked together each node has the following attributes which can be used to extract information and navigate through the tree structurenode attribute description attributes childnodes firstchild lastchild localname mapping object that holds attribute values (if anya list of all child nodes of the first child of node the last child of node local tag name of an element if colon appears in the tag (for example'')then this only contains the part after the colon namespace associated with nif any the node that appears after in the tree and has the same parent is none if is the last sibling the name of the node the meaning depends on the node type integer describing the node type it is set to one of the following values which are class variables of the node classattribute_nodecdata_section_nodecomment_nodedocument_fragment_nodedocument_nodedocument_type_nodeelement_nodeentity_nodeentity_reference_nodenotation_nodeprocessing_instruction_nodeor text_node the value of the node the meaning depends on the node type reference to the parent node part of tag name that appears before colon for examplethe element 'would have prefix of 'foothe node that appears before in the tree and has the same parent namespaceuri nextsibling nodename nodetype nodevalue parentnode prefix previoussibling lib fl ff |
18,418 | in addition to these attributesall nodes have the following methods typicallythese are used to manipulate the tree structure appendchild(childadds new child nodechildto the new child is added at the end of any other children clonenode(deepmakes copy of the node if deep is trueall child nodes are also cloned hasattributes(returns true if the node has any attributes haschildnodes(returns true if the node has any children insertbefore(newchildichildinserts new childnewchildbefore another childichild ichild must already be child of issamenode(otherreturns true if the node other refers to the same dom node as normalize(joins adjacent text nodes into single text node removechild(childremoves child child from replacechild(newchild,oldchildreplaces the child oldchild with newchild oldchild must already be child of although there are many different types of nodes that might appear in treeit is most common to work with documentelementand text nodes each is briefly described next document nodes document node appears at the top of the entire document tree and represents the entire document as whole it has the following methods and attributesd documentelement contains the root element of the entire document getelementsbytagname(tagnamesearches all child nodes and returns list of elements with given tag name tagname getelementsbytagnamens(namespaceurilocalnamesearches all child nodes and returns list of elements with given namespace uri and local name the returned list is an object of type nodelist lib fl ff |
18,419 | internet data handling and encoding element nodes an element node represents single xml element such as to get the text from an elementyou need to look for text nodes as children the following attributes and methods are defined to get other informatione tagname the tag name of the element for exampleif the element is defined by ''the tag name is 'fooe getelementsbytagname(tagnamereturns list of all children with given tag name getelementsbytagnamens(namespaceurilocalnamereturns list of all children with given tag name in namespace namespaceuri and localname are strings that specify the namespace and tag name if namespace has been declared using declaration such as '<foo xmlns:foo="'localname is set to 'barthe returned object is of type nodelist hasattribute(namereturns true if an element has an attribute with name name hasattributens(namespaceurilocalnamereturns true if an element has an attribute named by namespaceuri and localname the arguments have the same meaning as described for getelementsbytagnamens( getattribute(namereturns the value of attribute name the return value is string if the attribute doesn' existan empty string is returned getattributens(namespaceurilocalnamereturns the value of the attributed named by namespaceuri and localname the return value is string an empty string is returned if the attribute does not exist the arguments are the same as described for getelementsbytagnamens(text nodes text nodes are used to represent text data text data is stored in the data attribute of text object the text associated with given document element is always stored in text nodes that are children of the element utility functions the following utility methods are defined on nodes these are not part of the dom standardbut are provided by python for general convenience and for debugging toprettyxml([indent [newl]]creates nicely formatted string containing the xml represented by node and its children indent specifies an indentation string and defaults to tab ('\ 'newl specifies the newline character and defaults to '\nf lib fl ff |
18,420 | toxml([encoding]creates string containing the xml represented by node and its children encoding specifies the encoding (for example'utf- 'if no encoding is givennone is specified in the output text writexml(writer [indent [addindent [newl]]]writes xml to writer writer can be any object that provides write(method that is compatible with the file interface indent specifies the indentation of it is string that is prepended to the start of node in the output addindent is string that specifies the incremental indentation to apply to child nodes of newl specifies the newline character dom example the following example shows how to use the xml dom minidom module to parse and extract information from an xml filefrom xml dom import minidom doc minidom parse("recipe xml"ingredients items doc getelementsbytagname("ingredients")[ ingredients getelementsbytagname("item"for item in itemsnum item getattribute("num"units item getattribute("units"text item firstchild data strip(quantity "% % (num,unitsprint("%- % (quantity,text)note the xml dom minidom module has many more features for changing the parse tree and working with different kinds of xml node types more information can be found in the online documentation xml etree elementtree the xml etree elementtree module defines flexible container object elementtree for storing and manipulating hierarchical data although this object is commonly used in conjunction with xml processingit is actually quite general-purpose--serving role that' cross between list and dictionary elementtree objects the following class is used to define new elementtree object and represents the top level of hierarchy elementtree([element [file]]creates new elementtree object element is an instance representing the root node of the tree this instance supports the element interface described next file is either filename or file-like object from which xml data will be read to populate the tree lib fl ff |
18,421 | internet data handling and encoding an instance tree of elementtree has the following methodstree _setroot(elementsets the root element to element tree find(pathfinds and returns the first top-level element in the tree whose type matches the given path path is string that describes the element type and its location relative to other elements the following list describes the path syntaxpath description matches only top-level elements with the given tag--for exampledoes not match elements defined at lower levels element of type tag embedded inside another element such as is not matched 'parent/tagmatches an element with tag 'tagif it' child of an element with tag 'parentas many path name components can be specified as desired '*selects all child elements for example'*/tagwould match all grandchild elements with tag name of 'tagstarts the search with the current node '//selects all subelements on all levels beneath an element for example//tagmatches all elements with tag 'tagat all sublevels 'tagif you are working with document involving xml namespacesthe tag strings in path should have the form '{uri}tagwhere uri is string such as 'tree findall(pathfinds all top-level elements in the tree that match the given path and returns them in document order as list or an iterator tree findtext(path [default]returns the element text for the first top-level element in the tree matching the given path default is string to return if no matching element can be found tree getiterator([tag]creates an iterator that produces all elements in the treein section orderwhose tag matches tag if tag is omittedthen every element in the tree is returned in order tree getroot(returns the root element for the tree tree parse(source [parser]parses external xml data and replaces the root element with the result source is either filename or file-like object representing xml data parser is an optional instance of treebuilderwhich is described later lib fl ff |
18,422 | tree write(file [encoding]writes the entire contents of the tree to file file is either filename or file-like object opened for writing encoding is the output encoding to use and defaults to the interpreter default encoding if not specified ('utf- or 'asciiin most casescreating elements the types of elements held in an elementtree are represented by instances of varying types that are either created internally by parsing file or with the following construction functionscomment([text]creates new comment element text is string or byte string containing the element text this element is mapped to xml comments when parsing or writing output element(tag [attrib [**extra]]creates new element tag is the name of the element name for exampleif you were creating an element 'tag would be 'fooattrib is dictionary of element attributes specified as strings or byte strings any extra keyword arguments supplied in extra are also used to set element attributes fromstring(textcreates an element from fragment of xml text in text--the same as xml(described next processinginstruction(target [text]creates new element corresponding to processing instruction target and text are both strings or byte strings when mapped to xmlthis element corresponds to 'subelement(parenttag [attrib [**extra]]the same as element()but it automatically adds the new element as child of the element in parent xml(textcreates an element by parsing fragment of xml code in text for exampleif you set text to 'this will create standard element with tag of 'fooxmlid(textthe same as xml(textexcept that 'idattributes are collected and used to build dictionary mapping id values to elements returns tuple (elemidmapwhere elem is the new element and idmap is the id mapping dictionary for examplexmlid('hello'returns ({' '' '} lib fl ff |
18,423 | internet data handling and encoding the element interface although the elements stored in an elementtree may have varying typesthey all support common interface if elem is any elementthen the following python operators are definedoperator description elem[nelem[nnewelem returns the nth child element of elem changes the nth child element of elem to different element newelem deletes the nth child element of elem number of child elements of elem del elem[nlen(elemall elements have the following basic data attributesattribute description elem tag string identifying the element type for examplehas tag of 'foodata associated with the element usually string containing text between the start and ending tags of an xml element additional data stored with the attribute for xmlthis is usually string containing whitespace found after the element' end tag but before the next tag starts dictionary containing the element attributes elem text elem tail elem attrib elements support the following methodssome of which emulate methods on dictionarieselem append(subelementappends the element subelement to the list of children elem clear(clears all of the data in an element including attributestextand children elem find(pathfinds the first subelement whose type matches path elem findall(pathfinds all subelements whose type matches path returns list or an iterable with the matching elements in document order elem findtext(path [default]finds the text for the first element whose type patches path default is string giving the value to return if there is no match elem get(key [default]gets the value of attribute key default is default value to return if the attribute doesn' exist if xml namespaces are involvedthen key will be string of the form '{uri}key}where uri is string such as ' lib fl ff |
18,424 | elem getchildren(returns all subelements in document order elem getiterator([tag]returns an iterator that produces all subelements whose type matches tag elem insert(indexsubelementinserts subelement at position index in the list of children elem items(returns all element attributes as list of (namevaluepairs elem keys(returns list of all of the attribute names elem remove(subelementremoves element subelement from the list of children elem set(keyvaluesets attribute key to value value tree building an elementtree object is easy to create from other tree-like structures the following object is used for this purpose treebuilder([element_factory] class that builds an elementtree structure using series of start()end()and data(calls as would be triggered while parsing file or traversing another tree structure element_factory is an operation function that is called to create new element instances an instance of treebuilder has these methodst close(closes the tree builder and returns the top-level elementtree object that has been created data(dataadds text data to the current element being processed end(tagcloses the current element being processed and returns the final element object start(tagattrscreates new element tag is the element nameand attrs is dictionary with the attribute values lib fl ff |
18,425 | internet data handling and encoding utility functions the following utility functions are defineddump(elemdumps the element structure of elem to sys stdout for debugging the output is usually xml iselement(elemchecks if elem is valid element object iterparse(source [events]incrementally parses xml from source source is filename or file-like object referring to xml data events is list of event types to produce possible event types are 'start''end''start-ns'and 'end-nsif omittedonly 'endevents are produced the value returned by this function is an iterator that produces tuples (eventelemwhere event is string such as 'startor 'endand elem is the element being processed for 'starteventsthe element is newly created and initially empty except for attributes for 'endeventsthe element is fully populated and includes all subelements parse(sourcefully parses an xml source into an elementtree object source is filename or filelike object with xml data tostring(elemcreates an xml string representing elem and all of its subelements xml examples here is an example of using elementtree to parse the sample recipe file and print an ingredient list it is similar to the example shown for dom from xml etree elementtree import elementtree doc elementtree(file="recipe xml"ingredients doc find('ingredients'for item in ingredients findall('item')num item get('num'units item get('units',''text item text strip(quantity "% % (numunitsprint("%- % (quantitytext)the path syntax of elementtree makes it easier to simplify certain tasks and to take shortcuts as necessary for examplehere is different version of the previous code that uses the path syntax to simply extract all elements from xml etree elementtree import elementtree doc elementtree(file="recipe xml"for item in doc findall(//item")num item get('num'units item get('units',''text item text strip(quantity "% % (numunitsprint("%- % (quantitytext) lib fl ff |
18,426 | consider an xml file 'recipens xmlthat makes use of namespacesfamous guacamole southwest favoritelarge avocadoschopped combine all ingredients and hand whisk to desired consistency serve and enjoy with ice-cold beers to work with the namespacesit is usually easiest to use dictionary that maps the namespace prefix to the associated namespace uri you then use string formatting operators to fill in the uri as shown herefrom xml etree elementtree import elementtree doc elementtree(file="recipens xml"ns ' 'ingredients doc find('{%( ) }ingredientsnsfor item in ingredients findall('{%( ) }itemns)num item get('num'units item get('units',''text item text strip(quantity "% % (numunitsprint("%- % (quantitytext)for small xml filesit is fine to use the elementtree module to quickly load them into memory so that you can work with them howeversuppose you are working with huge xml file with structure such as thisa texas funeral jon wayne metaphysical graffiti the dead milkmen continues for more albums reading large xml file into memory tends to consume vast amounts of memory for examplereading mb xml file may result in an in-memory data structure of more than mb if you're trying to extract information from such filesthe easiest way to lib fl ff |
18,427 | do it is to use the elementtree iterparse(function here is an example of iteratively processing nodes in the previous filefrom xml etree elementtree import iterparse iparse iterparse("music xml"['start','end']find the top-level music element for eventelem in iparseif event ='startand elem tag ='music'musicnode elem break get all albums albums (elem for eventelem in iparse if event ='endand elem tag ='album'for album in albumsdo some kind of processing musicnode remove(albumthrow away the album when done the key to using iterparse(effectively is to get rid of data that you're no longer using the last statement musicnode remove(albumis throwing away each element after we are done processing it (by removing it from its parentif you monitor the memory footprint of the previous programyou will find that it stays low even if the input file is massive notes the elementtree module is by far the easiest and most flexible way of handling simple xml documents in python howeverit does not provide lot of bells and whistles for examplethere is no support for validationnor does it provide any apparent way to handle complex aspects of xml documents such as dtds for these thingsyou'll need to install third-party packages one such packagelxml etree (at the popular libxml and libxslt libraries and provides full support for xpathxsltand other features the elementtree module itself is third-party package maintained by fredrik lundh at versions that are more modern than what is included in the standard library and which offer additional features xml sax the xml sax module provides support for parsing xml documents using the sax api parse(filehandler [error_handler]parses an xml documentfile file is either the name of file or an open file object handler is content handler object error_handler is an optional sax errorhandler object that is described further in the online documentation parsestring(stringhandler [error_handler]the same as parse(but parses xml data contained in string instead lib fl ff |
18,428 | handler objects to perform any processingyou have to supply content handler object to the parse(or parsestring(functions to define handleryou define class that inherits from contenthandler an instance of contenthandler has the following methodsall of which can be overridden in your handler class as neededc characters(contentcalled by the parser to supply raw character data content is string containing the characters enddocument(called by the parser when the end of the document is reached endelement(namecalled when the end of element name is reached for exampleif 'is parsedthis method is called with name set to 'fooc endelementns(nameqnamecalled when the end of an element involving an xml namespace is reached name is tuple of strings (urilocalnameand qname is the fully qualified name usually qname is none unless the sax namespace-prefixes feature has been enabled for exampleif the element is defined as '<foo:bar xmlns:foo="then the name tuple is ( ' endprefixmapping(prefixcalled when the end of an xml namespace is reached prefix is the name of the namespace ignorablewhitespace(whitespacecalled when ignorable whitespace is encountered in document whitespace is string containing the whitespace processinginstruction(targetdatacalled when an xml processing instruction enclosed in is encountered target is the type of instructionand data is the instruction data for exampleif the instruction is 'target is set to 'xml-stylesheetand data is the remainder of the instruction text 'href="mystyle csstype="text/css" setdocumentlocator(locatorcalled by the parser to supply locator object that can be used for tracking line numberscolumnsand other information the primary purpose of this method is simply to store the locator someplace so that you can use it later--for instanceif you needed to print an error message the locator object supplied in locator provides four methods--getcolumnnumber()getlinenumber()getpublicid()and getsystemid()--that can be used to get location information skippedentity(namecalled whenever the parser skips an entity name is the name of the entity that was skipped lib fl ff |
18,429 | internet data handling and encoding startdocument(called at the start of document startelement(nameattrscalled whenever new xml element is encountered name is the name of the elementand attrs is an object containing attribute information for exampleif the xml element is ''name is set to 'fooand attrs contains information about the bar and spam attributes the attrs object provides number of methods for obtaining attribute informationmethod description attrs getlength(attrs getnames(attrs gettype(nameattrs getvalue(namereturns the number of attributes returns list of attribute names gets the type of attribute name gets the value of attribute name startelementns(nameqnameattrscalled when new xml element is encountered and xml namespaces are being used name is tuple (urilocalnameand qname is fully qualified element name (normally set to none unless the sax namespace-prefixes feature has been enabledattrs is an object containing attribute information for exampleif the xml element is '<foo:bar xmlns:foo="name is ( 'when accessing attributes in the startelement(method shown earlier in additionthe following additional methods are added to deal with namespacesmethod description attrs getvaluebyqname(qnameattrs getnamebyqname(qnamereturns value for qualified name returns (namespacelocalnametuple for name returns qualified name for name specified as tuple (namespacelocalnamereturns qualified names of all attributes attrs getqnamebyname(nameattrs getqnames( startprefixmapping(prefixuricalled at the start of an xml namespace declaration for exampleif an element is defined as '<foo:bar xmlns:foo="'fooand uri is set to 'example the following example illustrates sax-based parserby printing out the ingredient list from the recipe file shown earlier this should be compared with the example in the xml dom minidom section lib fl ff |
18,430 | from xml sax import contenthandlerparse class recipehandler(contenthandler)def startdocument(self)self initem false def startelement(self,name,attrs)if name ='item'self num attrs get('num',' 'self units attrs get('units','none'self text [self initem true def endelement(self,name)if name ='item'text "join(self textif self units ='none'self units "unitstr "% % (self numself unitsprint("%- % (unitstr,text strip())self initem false def characters(self,data)if self initemself text append(dataparse("recipe xml",recipehandler()notes the xml sax module has many more features for working with different kinds of xml data and creating custom parsers for examplethere are handler objects that can be defined to parse dtd data and other parts of the document more information can be found in the online documentation xml sax saxutils the xml sax saxutils module defines some utility functions and objects that are often used with sax parsersbut are often generally useful elsewhere escape(data [entities]given stringdatathis function replaces certain characters with escape sequences for example'<gets replaced by '<entities is an optional dictionary that maps characters to the escape sequences for examplesetting entities to '\xf 'ñwould replace occurences of with 'ñunescape(data [entities]unescapes special escape sequences that appear in data for instance'<is replaced by '<entities is an optional dictionary mapping entities to unescaped character values entities is the inverse of the dictionary used with escape()--for example'ñ '\xf quoteattr(data [entities]escapes the string databut performs additional processing that allows the result value to be used as an xml attribute value the return value can be printed directly as an attribute value--for exampleprint "quoteattr(somevalueentities is dictionary compatible for use with the escape(function lib fl ff |
18,431 | internet data handling and encoding xmlgenerator([out [encoding]] contenthandler object that merely echoes parsed xml data back to the output stream as an xml document this re-creates the original xml document out is the output document and defaults to sys stdout encoding is the character encoding to use and defaults to 'iso- - this can be useful if you're trying to debug your parsing code and use handler that is known to work lib fl ff |
18,432 | miscellaneous library modules he modules listed in this section are not covered in detail in this book but are still considered to be part of the standard library these modules have mostly been omitted from previous because they are either extremely low-level and of limited userestricted to very specific platformsobsoleteor so complicated that coverage would require complete book on the topic although these modules are have been omitted from this bookonline documentation is available for each module at docs python org/library/modname an index of all modules is also available at the modules listed here represent common subset of functionality between python and python if you are using module that is not listed herechances are it has been officially deprecated some modules have changed names in python the new name is shown in parenthesesif applicable python services the following modules provide additional services related to the python language and execution of the python interpreter many of these modules are related to parsing and compilation of python source code module description bdb code codeop compileall copy_reg (copyregdis distutils fpectl imp access to the debugger framework interpreter base classes compiles python code byte-compiles python files in directory register built-in types for use with the pickle module disassembler distribution of python modules floating-point exception control provides access to the implementation of the import statement tests whether string is python keyword retrieves lines from source files finds modules used by script keyword linecache modulefinder lib fl ff |
18,433 | miscellaneous library modules module description parser pickletools pkgutil pprint accesses parse trees of python source code tools for pickle developers package extension utility prettyprinter for objects extracts information for class browsers compiles python source to bytecode files alternate implementation of the repr(function constants used to represent internal nodes of parse trees detection of ambiguous indentation regression testing package terminal nodes of the parse tree scanner for python source code user configuration file parsing import modules from zip archives pyclbr py_compile repr (reprlibsymbol tabnanny test token tokenize user zipimport string processing the following modules are some oldernow obsoletemodules used for string processing module description difflib fpformat stringprep textwrap compute deltas between strings floating-point number formatting internet string preparation text wrapping operating system modules these modules provide additional operating system services in some casesthe functionality of module listed here is already incorporated into the functionality of other modules covered in "operating system services module description crypt curses grp pty pipes nis platform pwd readline rlcompleter access to the unix crypt function curses library interface access to the group database pseudo terminal handling interface to shell pipelines interface to sun' nis access to platform-specific information access to the password database access to gnu readline library completion function for gnu readline lib fl ff |
18,434 | module description resource sched spwd stat syslog resource usage information event scheduler access to the shadow password database support for interpreting results of os stat(interface to unix syslog daemon unix tty control terminal control functions termios tty network the following modules provide support for lesser-used network protocolsmodule description imaplib nntplib poplib smtpd telnetlib imap protocol nntp protocol pop protocol smtp server telnet protocol internet data handling the following modules provide additional support for internet data processing not covered in "internet data handling and encoding module description binhex formatter mailcap mailbox netrc plistlib uu xdrlib binhex file format support generic output formatting mailcap file handling reading various mailbox formats netrc file processing macintosh plist file processing uuencode file support encode and decode sun xdr data internationalization the following modules are used for writing internationalized applicationsmodule description gettext locale multilingual text handling services internationalization functions provided by the system lib fl ff |
18,435 | miscellaneous library modules multimedia services the following modules provide support for handling various kinds of multimedia filesmodule description audioop aifc sunau wave chunk colorsys imghdr sndhdr ossaudiodev manipulates raw audio data reads and writes aiff and aifc files reads and writes sun au files reads and writes wav files reads iff chunked data conversions between color systems determines the type of an image determines the type of sound file access to oss-compatible audio devices miscellaneous the following modules round out the list and don' really neatly fall into any of the other categoriesmodule description cmd calendar shlex sched tkinter (tkinterwinsound line-oriented command interpreters calendar-generation functions simple lexical analysis module event scheduler python interface to tcl/tk playing sounds on windows lib fl ff |
18,436 | extending and embedding extending and embedding python appendixpython lib fl ff |
18,437 | lib fl ff |
18,438 | extending and embedding python ne of the most powerful features of python is its ability to interface with software written in there are two common strategies for integrating python with foreign code firstforeign functions can be packaged into python library module for use with the import statement such modules are known as extension modules because they extend the interpreter with additional functionality not written in python this isby farthe most common form of python- integration because it gives python applications access to high-performance programming libraries the other form of python- integration is embedding this is process by which python programs and the interpreter are accessed as library from this latter approach is sometimes used by programmers who want to embed the python interpreter into an existing application framework for some reason--usually as some kind of scripting engine this covers the absolute basics of the python- programming interface firstthe essential parts of the api used to build extension modules and embed the python interpreter are covered this section is not intended to be tutorialso readers new to this topic should consult the "embedding and extending the python interpreterdocument available at "python/ api reference manualavailable at ctypes library module is covered this is an extremely useful module that allows you to access functions in libraries without writing any additional code or using compiler it should be noted that for advanced extension and embedding applicationsmost programmers tend to turn to advanced code generators and programming libraries for examplethe swig project (extension modules by parsing the contents of header files references to this and other extension building tools can be found at integratingpythonwithotherlanguages extension modules this section outlines the basic process of creating handwritten extension module for python when you create an extension moduleyou are building an interface lib fl ff |
18,439 | extending and embedding python between python and existing functionality written in for librariesyou usually start from header file such as the following/file example *#include #include #include typedef struct point double xdouble ypoint/compute the gcd of two integers and *extern int gcd(int xint )/replace och with nch in and return the number of replacements *extern int replace(char *schar ochchar nch)/compute the distance between two points *extern double distance(point *apoint * )/ preprocessor constant *#define magic these function prototypes have some kind of implementation in separate file for example/example *#include "example /compute gcd of two positive integers and *int gcd(int xint yint gg ywhile ( xx xy greturn /replace character in string *int replace(char *schar oldchchar newchint nrep while ( strchr( ,oldch)*( ++newchnrep++return nrep/distance between two points *double distance(point *apoint *bdouble dx,dydx -> ->xdy -> ->yreturn sqrt(dx*dx dy*dy) lib fl ff |
18,440 | here is main(program that illustrates the use of these functions/main *#include "example hint main(/test the gcd(function *printf("% \ "gcd( , ))printf("% \ "gcd( , ))/test the replace(function *char ["skipping along unaware of the unspeakable peril "int nrepnrep replace( ,','-')printf("% \ "nrep)printf("% \ ", )/test the distance(function *point }point }printf("% \ "distance(& ,& ))here is the output of the previous programa out skipping-along-unaware-of-the-unspeakable-peril an extension module prototype extension modules are built by writing separate source file that contains set of wrapper functions which provide the glue between the python interpreter and the underlying code here is an example of basic extension module called _example/pyexample *#include "python #include "example hstatic char py_gcd_doc["computes the gcd of two integers"static pyobject py_gcd(pyobject *selfpyobject *argsint , ,rif (!pyarg_parsetuple(args,"ii:gcd",& ,& )return nullr gcd( , )return py_buildvalue(" ", )static char py_replace_doc["replaces all characters in string"static pyobject lib fl ff |
18,441 | extending and embedding python py_replace(pyobject *selfpyobject *argspyobject *kwargsstatic char *argnames[{" ","och","nch",null}char * ,*sdupchar ochnchint nreppyobject *resultif (!pyarg_parsetupleandkeywords(args,kwargs"scc:replace"argnames& &och&nch)return nullsdup (char *malloc(strlen( )+ )strcpy(sdup, )nrep replace(sdup,och,nch)result py_buildvalue("(is)",nrep,sdup)free(sdup)return resultstatic char py_distance_doc["computes the distance between two points"static pyobject py_distance(pyobject *selfpyobject *argspyerr_setstring(pyexc_notimplementederror,"distance(not implemented ")return nullstatic pymethoddef _examplemethods[{"gcd"py_gcdmeth_varargspy_gcd_doc}{"replace"py_replacemeth_varargs meth_keywordspy_replace_doc}{"distance",py_distance,meth_varargspy_distance_doc}{nullnull null}#if py_major_version /python module initialization *void init_example(voidpyobject *modmod py_initmodule("_example"_examplemethods)pymodule_addintmacro(mod,magic)#else /python module initialization *static struct pymoduledef _examplemodule pymoduledef_head_init"_example"/name of module *null/module documentationmay be null *- _examplemethods }pymodinit_func pyinit_ _example(voidpyobject *modmod pymodule_create(&_examplemodule)pymodule_addintmacro(modmagic)return mod#endif extension modules always need to include "python hfor each function to be accesseda wrapper function is written these wrapper functions accept either two arguments (self and argsboth of type pyobject *or three arguments (selfargsf lib fl ff |
18,442 | and kwargsall of type pyobject *the self parameter is used when the wrapper function is implementing built-in method to be applied to an instance of some object in this casethe instance is placed in the self parameter otherwiseself is set to null args is tuple containing the function arguments passed by the interpreter kwargs is dictionary containing keyword arguments arguments are converted from python to using the pyarg_parsetuple(or pyarg_parsetupleandkeywords(function similarlythe py_buildvalue(function is used to construct an acceptable return value these functions are described in later sections documentation strings for extension functions should be placed in separate string variables such as py_gcd_doc and py_replace_doc as shown these variables are referenced during module initialization (described shortlywrapper functions should neverunder penalty of certain flaming deathmutate data received by reference from the interpreter this is why the py_replace(wrapper is making copy of the received string before passing it to the function (which modifies it in placeif this step is omittedthe wrapper function may violate python' string immutability if you want to raise an exceptionyou use the pyexc_setstring(function as shown in the py_distance(wrapper null is returned to signal that an error has occurred the method table _examplemethods is used to associate python names with the wrapper functions these are the names used to call the function from the interpreter the meth_varargs flag indicates the calling conventions for wrapper in this caseonly positional arguments in the form of tuple are accepted it can also be set to meth_varargs meth_keywords to indicate wrapper function accepting keyword arguments the method table additionally sets the documentation strings for each wrapper function the final part of an extension module performs an initialization procedure that varies between python and python in python the module initialization function init_example is used to initialize the contents of the module in this casethe py_initmodule("_example",_examplemethodsfunction creates module_exampleand populates it with built-in function objects corresponding to the functions listed in the method table for python you have to create an pymoduledef object _examplemodule that describes the module you then write function pyinit_ _example(that initializes the module as shown the module initialization function is also the place where you install constants and other parts of moduleif necessary for examplethe pymodule_addintmacro(is adding the value of preprocessor to the module it is important to note that naming is critically important for module initialization if you are creating module called modnamethe module initialization function must be called initmodname(in python and pyinit_modname(in python if you don' do thisthe interpreter won' be able to correctly load your module naming extension modules it is standard practice to name extension modules with leading underscore such as '_examplethis convention is followed by the python standard library itself for lib fl ff |
18,443 | extending and embedding python instancethere are modules named _socket_thread_sreand _fileio corresponding to the programming components of the socketthreadingreand io modules generallyyou do not use these extension modules directly insteadyou create high-level python module such as the followingexample py from _example import add additional support code below the purpose of this python wrapper is to supply additional support code for your module or to provide higher-level interface in many casesit is easier to implement parts of an extension module in python instead of this design makes it easy to do this if you look at many standard library modulesyou will find that they have been implemented as mix of and python in this manner compiling and packaging extensions the preferred mechanism for compiling and packaging an extension module is to use distutils to do thisyou create setup py file that looks like thissetup py from distutils core import setupextension setup(name="example"version=" "py_modules ['example py']ext_modules extension("_example"["pyexample ","example "]in this fileyou need to include the high-level python file (example pyand the source files making up the extension module (pyexample cexample cto build the module for testingtype the followingpython setup py build_ext --inplace this will compile the extension code into shared library and leave it in the current working directory the name of this library will be _examplemodule so_examplemodule pydor some similar variant if the compilation was successfulusing your module is straightforward for examplepython python ( : dec : : [gcc (apple inc build )on darwin type "help""copyright""creditsor "licensefor more information import example example gcd( , example replace("hello world",','-'( 'hello-world'example distance(traceback (most recent call last)file ""line in notimplementederrordistance(not implemented lib fl ff |
18,444 | more complicated extension modules may need to supply additional build informationsuch as include directorieslibrariesand preprocessor macros they can also be included in setup pyas followssetup py from distutils core import setupextension setup(name="example"version=" "py_modules ['example py']ext_modules extension("_example"["pyexample ","example "]include_dirs ["/usr/include/ ","/opt/include"]define_macros [('debug', ')('mondo_flag', )]undef_macros ['have_foo','have_not']library_dirs["/usr/lib/ ""/opt/lib"]libraries " ""xt""blah]if you want to install an extension module for general useyou simply type python setup py install further details about this are found in "modulespackagesand distribution in some situationsyou may want to build an extension module manually this almost always requires advanced knowledge of various compiler and linker options the following is an example on linuxlinux gcc - -fpic - /usr/local/include/python example pyexample linux gcc -shared example pyexample - _examplemodule so type conversion from python to the following functions are used by extension modules to convert arguments passed from python to their prototypes are defined by including the python header file int pyarg_parsetuple(pyobject *argschar *format)parses tuple of positional arguments in args into series of variables format is format string containing zero or more of the specifier strings from tables which describe the expected contents of args all the remaining arguments contain the addresses of variables into which the results will be placed the order and types of these arguments must match the specifiers used in format zero is returned if the arguments could not be parsed int pyarg_parsetupleandkeywords(pyobject *argspyobject *kwargschar *formatchar **kwlist)parses both tuple of positional arguments and dictionary of keyword arguments contained in kwargs format has the same meaning as for pyarg_parsetuple(the only difference is that kwlist is null-terminated list of strings containing the names of all the arguments returns on success on error table lists the format codes that are placed in the format argument to convert numbers the argument type column lists the data type that should be passed to the pyarg_parse*(functions for numbersit is always pointer to location where the result should be stored lib fl ff |
18,445 | extending and embedding python table numeric conversions and associated data types for pyarg_parseformat python type argument type " " "hinteger integer integer integer integer integer integer integer integer integer integer float float complex signed char * unsigned char * short * " " " " " " " " " " "dunsigned short * int * unsigned int * long int * unsigned long * long long * unsigned long long * py_ssize_t * float * double * py_complex * when signed integer values are convertedan overflowerror exception is raised if the python integer is too large to fit into the requested data type howeverconversions that accept unsigned values ( ' '' '' 'and so ondo not check for overflow and will silently truncate the value if it exceeds the supported range for floating-point conversionsa python int or float may be supplied as input in this caseintegers will be promoted to float user-defined classes are accepted as numbers as long as they provide appropriate conversion methods such as _int_ (or _float_ (for examplea user-defined class that implements _int_ (will be accepted as input for any of the previously shown integer conversions (and _int_ (invoked automatically to do the conversiontable shows the conversions that apply to strings and bytes many of the string conversions return both pointer and length as result table string conversions and associated data types for pyarg_parseformat python type argument type " " " #" *" " #" *" " #" *" " #"esstring or byte string of length string stringbytesor buffer stringbytesor buffer string or none stringbytesor none stringbytesbufferor none bytes (null-terminatedbytes bytes or buffer string (unicodestring (unicodestring char * char ** char **rint *len py_buffer * char ** char **rint *len py_buffer * char ** char **rint *len py_buffer * py_unicode ** py_unicode **rint *len const char *encchar ** lib fl ff |
18,446 | table continued format python type argument type "es#string or bytes "etstring or null-terminated bytes "et#string or bytes " #" " #" *read-only buffer read-write buffer read-write buffer read-write buffer const char *encchar **rint *len const char *encchar **rint *len const char *encchar **rint *len char **rint *len char ** char **rint *len py_buffer * string handling presents special problem for extensions because the char datatype is used for many different purposes for instanceit might refer to texta single characteror buffer of raw binary data there is also the issue of what to do with embedded null characters ('\ 'that uses to signal the end of text strings in table the conversion codes of " "" "" ""es"and "etshould be used if you are passing text for these codespython assumes that the input text does not contain any embedded nulls--if soa typeerror exception is raised howeverthe resulting string in can be safely assumed to be null-terminated in python both -bit and unicode strings can be passedbut in python all conversions except for "etrequire the python str type and do not work with bytes when unicode strings are passed to cthey are always encoded using the default unicode encoding used by the interpreter (usually utf- the one exception is the "uconversion code that returns string using python' internal unicode representation this is an array of py_unicode values where unicode characters are typically represented by the wchar_t type in the "esand "etcodes allow you to specify an alternative encoding for the text for theseyou supply an encoding name such as 'utf- or 'iso- - 'and the text will be encoded into buffer and returned in that format the "etcode differs from "esin that if python byte-string is givenit is assumed to have already been encoded and is passed through unmodified one caution with "esand "etconversions is that they dynamically allocate memory for the result and require the user to explicitly release it using pymem_free(thuscode that uses these conversions should look similar to thispyobject *py_wrapper(pyobject *selfpyobject *argschar *bufferif (!pyarg_parsetuple(args,"es","utf- ",&buffer)return null/do something */cleanup and return the result *pymem_free(buffer)return resultf lib fl ff |
18,447 | extending and embedding python for handling text or binary datause the " #"" #"" #""es#"or "et#codes these conversions work exactly the same as before except that they additionally return length because of thisthe restriction on embedded null characters is lifted in additionthese conversions add support for byte strings and any other objects that support something known as the buffer interface the buffer interface is means by which python object can expose raw binary buffer representing its contents typicallyyou find it on stringsbytesand arrays ( the arrays created in the array module support itin this caseif an object provides readable buffer interfacea pointer to the buffer and its size is returned finallyif non-null pointer and length are given to the "es#and "et#conversionsit is assumed that these represent pre-allocated buffer into which the result of the encoding can be placed in this casethe interpreter does not allocate new memory for the result and you don' have to call pymem_free(the conversion codes of " *and " *are similar to " #and " #except that they populate py_buffer structure with information about the received data more information about this can be found in pep- but this structure minimally has attributes char *bufint lenand int itemsize that point to the bufferthe buffer length (in bytes)and the size of items held in the buffer in additionthe interpreter places lock on the buffer that prevents it from being changed by other threads as long as it is held by extension code this allows the extension to work with the buffer contents independentlypossibly in different thread than the interpreter it is up to the user to call pybuffer_release(on the buffer after all processing is complete the conversion codes of " #"" "" #"and " *are just like the "sfamily of codes except that they only accept objects implementing the buffer interface " #requires the buffer to be readable the "wcode requires the buffer to be both readable and writable python object supporting writable buffer is assumed to be mutable thusit is legal for extension to overwrite or modify the buffer contents the conversion codes of " "" #"and " *are just like the "sfamily of codes except that they only accept byte strings use these to write functions that must only take bytesnot unicode strings the "ycode only accepts byte strings that do not contain embedded null characters table lists conversion codes that are used to accept arbitrary python objects as input and to leave the result as type pyobject these are sometimes used for extensions that need to work with python objects that are more complicated than simple numbers or strings--for exampleif you needed extension function to accept an instance of python class or dictionary table python object conversions and associated data types for pyarg_parseformat python type type "oany any any string unicode pyobject ** " !" &" "upytypeobject *typepyobject ** int (*converter)(pyobject *void *)void * pyobject ** pyobject ** lib fl ff |
18,448 | the " "" "and "uspecifiers return raw python objects of type pyobject "sand "urestrict this object to be string or unicode stringrespectively the " !conversion requires two argumentsa pointer to python type object and pointer to pyobject into which pointer to the object is placed typeerror is raised if the type of the object doesn' match the type object for example/parse list argument *pyobject *listobjpyarg_parsetuple(args," !"&pylist_type&listobj)the following list shows the type names corresponding to some python container types that might be commonly used with this conversion name python type pylist_type pydict_type pyset_type pyfrozenset_type pytuple_type pyslice_type pybytearray_type list dict set frozen_set tuple slice bytearray the " &conversion takes two arguments (converteraddrand uses function to convert pyobject to data type converter is pointer to function with the prototype int converter(pyobject *objvoid *addr)where obj is the passed python object and addr is the address supplied as the second argument in pyarg_parsetuple(converter(should return on success on failure on errorthe converter should also raise an exception this kind of conversion can be used to map python objects such as lists or tuples into data structures for examplehere is possible implementation of the distance(wrapper from our earlier code/convert tuple into point structure *int convert_point(pyobject *objvoid *addrpoint * (point *addrreturn pyarg_parsetuple(obj,"ii"& -> & -> )pyobject *py_distance(pyobject *selfpyobject *argspoint double resultif (!pyarg_parsetuple(args," & &"convert_point& convert_point& )return nullresult distance(& ,& )return py_buildvalue(" ",result) lib fl ff |
18,449 | extending and embedding python finallyargument format strings can contain few additional modifiers related to tuple unpackingdocumentationerror messagesand default arguments the following is list of these modifiersformat string description "(items)unpack tuple of objects items consist of format conversions start of optional arguments end of arguments the remaining text is the function name end of arguments the remaining text is the error message "|":";the "(items)unpacks values from python tuple this can be useful way to map tuples into simple structures for examplehere is another possible implementation of the py_distance(wrapper functionpyobject *py_distance(pyobject *selfpyobject *argspoint double resultif (!pyarg_parsetuple(args,"(dd)(dd)"& & & & )return nullresult distance(& ,& )return py_buildvalue(" ",result)the modifier "|specifies that all remaining arguments are optional this can appear only once in format specifier and cannot be nested the modifier ":indicates the end of the arguments any text that follows is used as the function name in any error messages the modifier ";signals the end of the arguments any following text is used as the error message note that only one of and should be used here are some examplespyarg_parsetuple(args,"ii:gcd"& & )pyarg_parsetuple(args,"iigcd requires integers"& & )/parse with optional arguments *pyarg_parsetuple(args," | "&buffer&delimiter)type conversion from to python the following function is used to convert the values contained in variables to python objectpyobject *py_buildvalue(char *formatthis constructs python object from series of variables format is string describing the desired conversion the remaining arguments are the values of variables to be converted the format specifier is similar to that used with the pyarg_parsetuplefunctionsas shown in table lib fl ff |
18,450 | table format specifiers for py_buildvalue(format python type type description ""snone string void char " #string char *int "ybytes char " #bytes char *int " " #"ustring or none string or none unicode char char *int py_unicode " #"uunicode unicode py_unicode char " #unicode char *int " " " " " " " " " " " "cinteger integer integer integer integer integer integer integer integer integer integer string char unsigned char short unsigned short int unsigned int long unsigned long long long unsigned long long py_ssize_t char " " " "ofloat float complex any float double py_complex pyobject nothing null-terminated string if the string pointer is nullnone is returned string and length may contain null bytes if the string pointer is nullnone is returned same as "sexcept byte string is returned same as "sexcept byte string is returned same as "ssame as " #null-terminated unicode string if the string pointer is nullnone is returned unicode string and length converts null-terminated string into unicode string converts string into unicode -bit integer -bit unsigned integer short -bit integer unsigned short -bit integer integer unsigned integer long integer unsigned long integer long long unsigned long long python size type single character creates python string of length single-precision floating point double-precision floating point complex number any python object the object is unchanged except for its reference countwhich is incremented by if null pointer is givena null pointer is returned this is useful if an error has been signaled elsewhere and you want it to propagate lib fl ff |
18,451 | extending and embedding python table continued format python type type description " &any converterany "sstring any pyobject data processed through converter function same as "osame as "oexcept that the reference count is not incremented creates tuple of items items is string of format specifiers from this table vars is list of variables corresponding to the items in items creates list of items items is string of format specifiers vars is list of variables corresponding to the items in items creates dictionary of items "npyobject "(items)tuple vars "[items]list vars "{items}dictionary vars here are some examples of building different kinds of valuespy_buildvalue(""py_buildvalue(" ", py_buildvalue("ids", , ,"hello"py_buildvalue(" #","hello", py_buildvalue("()"py_buildvalue("( )", py_buildvalue("[ii]", , py_buildvalue("[ , ]", , py_buildvalue("{ : , : }"," ", ," ", none ( "hello""hell(( ,[ , [ , {' ': ' ': for unicode string conversions involving char *it is assumed that the data consists of series of bytes encoded using the default unicode encoding (usually utf- the data will be automatically decoded into unicode string when passed to python the only exceptions are the "yand " #conversions that return raw byte string adding values to module in the module initialization function of an extension moduleit is common to add constants and other support values the following functions can be used to do thisint pymodule_addobject(pyobject *moduleconst char *namepyobject *valueadds new value to module name is the name of the valueand value is python object containing the value you can build this value using py_buildvalue(int pymodule_addintconstant(pyobject *moduleconst char *namelong valueadds an integer value to module void pymodule_addstringconstant(pyobject *moduleconst char *nameconst char *valueadds string value to module value must be null-terminated string lib fl ff |
18,452 | void pymodule_addintmacro(pyobject *modulemacroadds macro value to module as an integer macro must be the name of preprocessor macro void pymodule_addstringmacro(pyobject *modulemacroadds macro value to module as string error handling extension modules indicate errors by returning null to the interpreter prior to returning nullan exception should be set using one of the following functionsvoid pyerr_nomemory(raises memoryerror exception void pyerr_setfromerrno(pyobject *excraises an exception exc is an exception object the value of the exception is taken from the errno variable in the library void pyerr_setfromerrnowithfilename(pyobject *excchar *filenamelike pyerr_setfromerrno()but includes the file name in the exception value as well void pyerr_setobject(pyobject *excpyobject *valraises an exception exc is an exception objectand val is an object containing the value of the exception void pyerr_setstring(pyobject *excchar *msgraises an exception exc is an exception objectand msg is message describing what went wrong the exc argument in these functions can be set to one of the followingc name python exception pyexc_arithmeticerror pyexc_assertionerror pyexc_attributeerror pyexc_environmenterror pyexc_eoferror pyexc_exception pyexc_floatingpointerror pyexc_importerror pyexc_indexerror pyexc_ioerror pyexc_keyerror pyexc_keyboardinterrupt pyexc_lookuperror pyexc_memoryerror pyexc_nameerror pyexc_notimplementederror arithmeticerror assertionerror attributeerror environmenterror eoferror exception floatingpointerror importerror indexerror ioerror keyerror keyboardinterrupt lookuperror memoryerror nameerror notimplementederror lib fl ff |
18,453 | extending and embedding python name python exception pyexc_oserror pyexc_overflowerror pyexc_referenceerror pyexc_runtimeerror pyexc_standarderror pyexc_stopiteration pyexc_syntaxerror pyexc_systemerror pyexc_systemexit pyexc_typeerror pyexc_unicodeerror pyexc_unicodeencodeerror pyexc_unicodedecodeerror pyexc_unicodetranslateerror pyexc_valueerror pyexc_windowserror pyexc_zerodivisionerror oserror overflowerror referenceerror runtimeerror standarderror stopiteration syntaxerror systemerror systemexit typeerror unicodeerror unicodeencodeerror unicodedecodeerror unicodetranslateerror valueerror windowserror zerodivisionerror the following functions are used to query or clear the exception status of the interpretervoid pyerr_clear(clears any previously raised exceptions pyobject *pyerr_occurred(checks to see whether or not an exception has been raised if sothe current exception value is returned otherwisenull is returned int pyerr_exceptionmatches(pyobject *excchecks to see if the current exception matches the exception exc returns if true otherwise this function follows the same exception matching rules as in python code thereforeexc could be superclass of the current exception or tuple of exception classes the following prototype shows how to implement try-except block in /carry out some operation involving python objects *if (pyerr_occurred()if (pyerr_exceptionmatches(pyexc_valueerror)/take some kind of recovery action *pyerr_clear()return result/ valid pyobject *else return null/propagate the exception to the interpreter * lib fl ff |
18,454 | reference counting unlike programs written in pythonc extensions may have to manipulate the reference count of python objects this is done using the following macrosall of which are applied to objects of type pyobject macro description py_incref(objincrements the reference count of objwhich must be non-null py_decref(objdecrements the reference count of objwhich must be non-null py_xincref(objincrements the reference count of objwhich may be null py_xdecref(objdecrements the reference count of objwhich may be null manipulating the reference count of python objects in is delicate topicand readers are strongly advised to consult the "extending and embedding the python interpreterdocument available at as general ruleit is not necessary to worry about reference counting in extension functions except in the following casesn if you save reference to python object for later use or in structureyou must increase the reference count similarlyto dispose of an object that was previously saveddecrease its reference count if you are manipulating python containers (listsdictsand so onfrom cyou may have to manually manipulate reference counts of the individual items for examplehigh-level operations that get or set items in container typically increase the reference count you will know that you have reference counting problem if your extension code crashes the interpreter (you forgot to increase the reference countor the interpreter leaks memory as your extension functions are used (you forgot to decrease reference countthreads global interpreter lock is used to prevent more than one thread from executing in the interpreter at once if function written in an extension module executes for long timeit will block the execution of other threads until it completes this is because the lock is held whenever an extension function is invoked if the extension module is thread-safethe following macros can be used to release and reacquire the global interpreter lockpy_begin_allow_threads releases the global interpreter lock and allows other threads to run in the interpreter the extension must not invoke any functions in the python api while the lock is released py_end_allow_threads reacquires the global interpreter lock the extension will block until the lock can be acquired successfully in this case lib fl ff |
18,455 | extending and embedding python the following example illustrates the use of these macrospyobject *py_wrapper(pyobject *selfpyobject *argspyarg_parsetuple(argspy_begin_allow_threads result run_long_calculation(args)py_end_allow_threads return py_buildvalue(fmt,result)embedding the python interpreter the python interpreter can also be embedded into applications with embeddingthe python interpreter operates as programming library where programs can initialize the interpreterhave the interpreter run scripts and code fragmentsload library modulesand manipulate functions and objects implemented in python an embedding template with embeddingyour program is in charge of the interpreter here is simple program that illustrates the most minimal embedding possible#include int main(int argcchar **argvpy_initialize()pyrun_simplestring("print('hello world')")py_finalize()return in this examplethe interpreter is initializeda short script is executed as stringand the interpreter is shut down before proceeding any furtherit is usually good idea to get the prior example working first compilation and linking to compile an embedded interpreter on unixyour code must include the "python hheader file and link against the interpreter library such as libpython the header file is typically found in /usr/local/include/python and the library is typically found in /usr/local/lib/python /config for windowsyou will need to locate these files in the python installation directory be aware that the interpreter may depend on other libraries you need to include when linking unfortunatelythis tends to be platform-specific and related to how python was configured on your machine--you may have to fiddle around for bit basic interpreter operation and setup the following functions are used to set up the interpreter and to run scriptsint pyrun_anyfile(file *fpchar *filenameif fp is an interactive device such as tty in unixthis function calls pyrun_interactiveloop(otherwisepyrun_simplefile(is called filename is lib fl ff |
18,456 | string that gives name for the input stream this name will appear when the interpreter reports errors if filename is nulla default string of "???is used as the file name int pyrun_simplefile(file *fpchar *filenamesimilar to pyrun_simplestring()except that the program is read from the file fp int pyrun_simplestring(char *commandexecutes command in the _main_ module of the interpreter returns on success- if an exception occurred int pyrun_interactiveone(file *fpchar *filenameexecutes single interactive command int pyrun_interativeloop(file *fpchar *filenameruns the interpreter in interactive mode void py_initialize(initializes the python interpreter this function should be called before using any other functions in the apiwith the exception of py_setprogramname()pyeval_initthreads()pyeval_releaselock()and pyeval_acquirelock(int py_isinitialized(returns if the interpreter has been initialized if not void py_finalize(cleans up the interpreter by destroying all the sub-interpreters and objects that were created since calling py_initialize(normallythis function frees all the memory allocated by the interpreter howevercircular references and extension modules may introduce memory leaks that cannot be recovered by this function void py_setprogramname(char *namesets the program name that' normally found in the argv[ argument of the sys module this function should only be called before py_initialize(char *py_getprefix(returns the prefix for installed platform-independent files this is the same value as found in sys prefix char *py_getexecprefix(returns the exec-prefix for installed platform-dependent files this is the same value as found in sys exec_prefix char *py_getprogramfullpath(returns the full path name of the python executable char *py_getpath(returns the default module search path the path is returned as string consisting of directory names separated by platform-dependent delimiters (on unixon dos/windowsf lib fl ff |
18,457 | extending and embedding python int pysys_setargv(int argcchar **argvsets command-line options used to populate the value of sys argv this should only be called before py_initialize(accessing python from although there are many ways that the interpreter can be accessed from cfour essential tasks are the most common with embeddingn importing python library modules (emulating the import statementn getting references to objects defined in modules calling python functionsclassesand methods accessing the attributes of objects (datamethodsand so onall of these operations can be carried out using these basic operations defined in the python apipyobject *pyimport_importmodule(const char *modnameimports module modname and returns reference to the associated module object pyobject *pyobject_getattrstring(pyobject *objconst char *namegets an attribute from an object this is the same as obj name int pyobject_setattrstring(pyobject *objconst char *namepyobject *valuesets an attribute on an object this is the same as obj name value pyobject *pyeval_callobject(pyobject *funcpyobject *argscalls func with arguments args func is python callable object (functionmethodclassand so onargs is tuple of arguments pyobject pyeval_callobjectwithkeywords(pyobject *funcpyobject *argspyobject *kwargscalls func with positional arguments args and keyword arguments kwargs func is callable objectargs is tupleand kwargs is dictionary the following example illustrates the use of these functions by calling and using various parts of the re module from this program prints out all of the lines read from stdin that contain python regular expression supplied by the user #include "python hint main(int argcchar **argvpyobject *repyobject *re_compilepyobject *patpyobject *pat_searchpyobject *argschar buffer[ ]if (argc ! fprintf(stderr,"usage% pattern\ ",argv[ ])exit( )py_initialize() lib fl ff |
18,458 | /import re *re pyimport_importmodule("re")/pat re compile(pat,flags*re_compile pyobject_getattrstring(re,"compile")args py_buildvalue("( )"argv[ ])pat pyeval_callobject(re_compileargs)py_decref(args)/pat_search pat search bound method*pat_search pyobject_getattrstring(pat,"search")/read lines and perform matches *while (fgets(buffer, ,stdin)pyobject *matchargs py_buildvalue("( )"buffer)/match pat search(buffer*match pyeval_callobject(pat_search,args)py_decref(args)if (match !py_noneprintf("% ",buffer)py_xdecref(match)py_decref(pat)py_decref(re_compile)py_decref(re)py_finalize()return in any embedding codeit is critically important to properly manage reference counts in particularyou will need to decrease the reference count on any objects created from or returned to as result of evaluating functions converting python objects to major problem with embedded use of the interpreter is converting the result of python function or method call into suitable representation as general ruleyou need to know in advance exactly what kind of data an operation is going to return sadlythere is no high-level convenience function like pyarg_parsetuple(for converting single object value howeverthe following lists some low-level conversion functions that will convert few primitive python data types into an appropriate representation as long as you know exactly what kind of python object you are working withpython-to- conversion functions long pyint_aslong(pyobject *long pylong_aslong(pyobject *double pyfloat_asdouble(pyobject *char *pystring_asstring(pyobject *(python onlychar *pybytes_asstring(pyobject *(python onlyfor any types more complicated than thisyou will need to consult the api documentation ( lib fl ff |
18,459 | extending and embedding python ctypes the ctypes module provides python with access to functions defined in dlls and shared libraries although you need to know some details about the underlying library (namescalling argumentstypesand so on)you can use ctypes to access code without having to write extension wrapper code or compile anything with compiler ctypes is sizable library module with lot of advanced functionality herewe cover the essential parts of it that are needed to get going loading shared libraries the following classes are used to load shared library and return an instance representing its contentscdll(name [mode [handle [use_errno [use_last_error]]]] class representing standard shared library name is the name of the library such as 'libc so or 'msvcrt dllmode provides flags that determine how the library is loaded and are passed to the underlying dlopen(function on unix it can be set to the bitwise-or of rtld_localrtld_globalor rtld_default (the defaulton windowsmode is ignored handle specifies handle to an already loaded library (if availableby defaultit is none use_errno is boolean flag that adds an extra layer of safety around the handling of the errno variable in the loaded library this layer saves thread-local copy of errno prior to calling any foreign function and restores the value afterwards by defaultuse_errno is false use_last_error is boolean flag that enables pair of functions get_last_error(and set_last_error(that can be used to manipulate the system error code these are more commonly used on windows by defaultuse_last_error is false windll(name [mode [handle [use_errno [use_last_error]]]]the same as cdll(except that the functions in the library are assumed to follow the windows stdcall calling conventions (windowsthe following utility function can be used to locate shared libraries on the system and construct name suitable for use as the name parameter in the previous classes it is defined in the ctypes util submodulefind_library(namedefined in ctypes util returns path name corresponding to the library name name is library name without any file suffix such as 'libc''libm'and so on the string returned by the function is full path name such as '/usr/lib/libc so the behavior of this function is highly system-dependent and depends on the underlying configuration of shared libraries and environment (for examplethe setting of ld_library_path and other parametersreturns none if the library can' be located foreign functions the shared library instances created by the cdll(class operates as proxy to the underlying library to access library contentsyou just use attribute lookup (the operatorfor examplef lib fl ff |
18,460 | import ctypes libc ctypes cdll("/usr/lib/libc dylib"libc rand( libc atoi(" " in this exampleoperations such as libc rand(and libc atoi(are directly calling functions in the loaded library ctypes assumes that all functions accept parameters of type int or char and return results of type int thuseven though the previous function calls "worked,calls to other library functions do not work as expected for examplelibc atof(" "- to address this problemthe type signature and handling of any foreign function func can be set by changing the following attributesfunc argtypes tuple of ctypes datatypes (described heredescribing the input arguments to func func restype ctypes datatype describing the return value of func none is used for functions returning void func errcheck python callable object taking three parameters (resultfuncargswhere result is the value returned by foreign functionfunc is reference to the foreign function itselfand args is tuple of the input arguments this function is called after foreign function call and can be used to perform error checking and other actions here is an example of fixing the atof(function interfaceas shown in the previous examplelibc atof restype=ctypes c_double libc atof(" " the ctypes d_double is reference to predefined datatype the next section describes these datatypes datatypes table shows the ctypes datatypes that can be used in the argtypes and restype attributes of foreign functions the "python valuecolumn describes the type of python data that is accepted for the given data type lib fl ff |
18,461 | extending and embedding python table ctypes datatypes ctypes type name datatype python value c_bool c_bytes c_char bool signed char char true or false small integer single character c_char_p c_double c_longdouble c_float c_int c_int c_int c_int c_int c_long c_longlong c_short c_size_t c_ubyte c_uint c_uint c_uint c_uint c_uint c_ulong c_ulonglong c_ushort c_void_p c_wchar c_wchar_p char double long double float int signed char short int long long long long long short size_t unsigned char unsigned int unsigned char unsigned short unsigned int unsigned long long unsigned long unsigned long long unsigned short void wchar_t wchar_t null-terminated string or bytes floating point floating point floating point integer -bit integer -bit integer -bit integer -bit integer integer integer integer integer unsigned integer unsigned integer -bit unsigned integer -bit unsigned integer -bit unsigned integer -bit unsigned integer unsigned integer unsigned integer unsigned integer integer single unicode character null-terminated unicode to create type representing pointerapply the following function to one of the other typespointer(typedefines type that is pointer to type type for examplepointer(c_intrepresents the type int to define type representing fixed-size arraymultiply an existing type by the number of array dimensions for examplec_int* represents the datatype int[ to define type representing structure or unionyou inherit from one of the base classes structure or union within each derived classyou define class variable _fields_ that describes the contents _fields_ is list of or tuples of the form (namectypeor (namectypewidth)where name is an identifier for the lib fl ff |
18,462 | structure fieldctype is ctype class describing the typeand width is an integer bitfield width for exampleconsider the following structurestruct point double xy}the ctypes description of this structure is class point(structure)_fields_ (" "c_double)(" "c_doublecalling foreign functions to call functions in libraryyou simply call the appropriate function with set of arguments that are compatible with its type signature for simple datatypes such as c_intc_doubleand so forthyou can just pass compatible python types as input (integersfloatsand so onit is also possible to pass instances of c_intc_double and similar types as input for arraysyou can just pass python sequence of compatible types to pass pointer to foreign functionyou must first create ctypes instance that represents the value that will be pointed at and then create pointer object using one of the following functionsbyref(cvalue [offset]represents lightweight pointer to cvalue cvalue must be an instance of ctypes datatype offset is byte offset to add to the pointer value the value returned by the function can only be used in function calls pointer(cvaluecreates pointer instance pointing to cvalue cvalue must be an instance of ctypes datatype this creates an instance of the pointer type described earlier here is an example showing how you would pass parameter of type double into functiondval c_double( foo(byref(dval)create double instance calls foo(&dvalp_dval pointer(dvalr foo(p_dvalcreates pointer variable calls foo(p_dvalinspect the value of dval afterwards print (dval valueit should be noted that you cannot create pointers to built-in types such as int or float passing pointers to such types would violate mutability if the underlying function changed the value the cobj value attribute of ctypes instance cobj contains the internal data for examplethe reference to dval value in the previous code returns the floating-point value stored inside the ctypes c_double instance dval lib fl ff |
18,463 | extending and embedding python to pass structure to functionyou must create an instance of the structure or union to do thisyou call previous defined structure or union type structuretype as followsstructuretype(*args**kwargscreates an instance of structuretype where structuretype is class derived from structure or union positional arguments in *args are used to initialize the structure members in the same order as they are listed in _fields_ keyword arguments in **kwargs initialize just the named structure members alternative type construction methods all instances of ctypes types such as c_intpointerand so forth have some class methods that are used to create instances of ctypes types from memory locations and other objects ty from_buffer(source [,offset]creates an instance of ctypes type ty that shares the same memory buffer as source source must be any other object that supports the writable buffer interface ( bytearrayarray objects in the array modulemmapand so onoffset is the number of bytes from the start of the buffer to use ty from_buffer_copy(source [offset]the same as ty from_buffer(except that copy of the memory is made and that source can be read-only ty from_address(addresscreates an instance of ctypes type ty from raw memory address address specified as an integer ty from_param(objcreates an instance of ctypes type ty from python object obj this only works if the passed object obj can be adapted into the appropriate type for examplea python integer can be adapted into c_int instance ty in_dll(librarynamecreates an instance of ctypes type ty from symbol in shared library library is an instance of the loaded library such as the object created by the cdll class name is the name of symbol this method can be used to put ctypes wrapper around global variables defined in library the following example shows how you might create reference to global variable int status defined in library libexample so libexample ctypes cdll("libexample so"status ctypes c_int in_dll(libexample,"status" lib fl ff |
18,464 | utility functions the following utility functions are defined by ctypesaddressof(cobjreturns the memory address of cobj as an integer cobj must be an instance of ctypes type alignment(ctype_or_objreturns the integer alignment requirements of ctypes type or object ctype_or_obj must be ctypes type or an instance of type cast(cobjctypecasts ctypes object cobj to new type given in ctype this only works for pointersso cobj must be pointer or array and ctype must be pointer type create_string_buffer(init [size]creates mutable character buffer as ctypes array of type c_char init is either an integer size or string representing the initial contents size is an optional parameter that specifies the size to use if init is string by defaultthe size is set to be one greater than the number of characters in init unicode strings are encoded into bytes using the default encoding create_unicode_buffer(init [size]the same as create_string_buffer()except that ctypes array of type c_wchar is created get_errno(returns the current value of the ctypes private copy of errno get_last_error(returns the current value of the ctypes private copy of lasterror on windows memmove(dstsrccountcopies count bytes from src to dst src and dst are either integers representing memory addresses or instances of ctypes types that can be converted to pointers the same as the memmove(library function memset(dstccountsets count bytes of memory starting at dst to the byte value dst is either an integer or ctypes instance is an integer representing byte in the range - resize(cobjsizeresizes the internal memory used to represent ctypes object cobj size is the new size in bytes set_conversion_mode(encodingerrorssets the unicode encoding used when converting from unicode strings to -bit strings encoding is the encoding name such as 'utf- 'and errors is the error-handling policy such as 'strictor 'ignorereturns tuple (encodingerrorswith the previous setting lib fl ff |
18,465 | extending and embedding python set_errno(valuesets the ctypes-private copy of the system errno variable returns the previous value set_last_error(valuesets the windows lasterror variable and returns the previous value sizeof(type_or_cobjreturns the size of ctypes type or object in bytes string_at(address [size]returns byte string representing size bytes of memory starting at address address if size is omittedit is assumed that the byte string is null-terminated wstring_at(address [size]returns unicode string representing size wide characters starting at address address if size is omittedthe character string is assumed to be null-terminated example the following example illustrates the use of the ctypes module by building an interface to the set of functions used in the very first part of this that covered the details of creating python extension modules by hand example py import ctypes _example ctypes cdll(/libexample so"int gcd(intintgcd _example gcd gcd argtypes (ctypes c_intctypes c_intgcd restype ctypes c_int int replace(char *schar olcdhchar newch_example replace argtypes (ctypes c_char_pctypes c_charctypes c_char_example replace restype ctypes c_int def replace(soldchnewch)sbuffer ctypes create_string_buffer(snrep _example replace(sbuffer,oldch,newchreturn (nrep,sbuffer valuedouble distance(point * point * class point(ctypes structure)_fields_ (" "ctypes c_double)(" "ctypes c_double_example distance argtypes (ctypes pointer(point)ctypes pointer(point)_example distance restype ctypes c_double def distance( , ) point(*ap point(*breturn _example distance(byref( ),byref( ) lib fl ff |
18,466 | as general noteusage of ctypes is always going to involve python wrapper layer of varying complexity for exampleit may be the case that you can call function directly howeveryou may also have to implement small wrapping layer to account for certain aspects of the underlying code in this examplethe replace(function is taking extra steps to account for the fact that the library mutates the input buffer the distance(function is performing extra steps to create point instances from tuples and to pass pointers note the ctypes module has large number of advanced features not covered here for examplethe library can access many different kinds of libraries on windowsand there is support for callback functionsincomplete typesand other details the online documentation is filled with many examples so that should be starting point for further use advanced extending and embedding creating handwritten extension modules or using ctypes is usually straightforward if you are extending python with simple code howeverfor anything more complexit can quickly become tedious for thisyou will want to look for suitable extension building tool these tools either automate much of the extension building process or provide programming interface that operates at much higher level links to variety of such tools can be found at howevera short example with swig (by the author with automated toolsyou usually just describe the contents of an extension module at high level for examplewith swigyou write short interface specification that looks like this/example sample swig specification *%module example %/preamble include all required header files here *#include "example %/module contents list all declarations here *typedef struct point double xdouble ypointextern int gcd(intint)extern int replace(char *schar oldchchar newch)extern double distance(point *apoint * )using this specificationswig automatically generates everything needed to make python extension module to run swigyou just invoke it like compilerswig -python example lib fl ff |
18,467 | extending and embedding python as outputit generates set of and py files howeveryou often don' have to worry much about this if you are using distutils and include file in the setup specificationit will run swig automatically for you when building an extension for examplethis setup py file automatically runs swig on the listed example file setup py from distutils core import setupextension setup(name="example"version=" "py_modules ['example py']ext_modules extension("_example"["example ","example "]it turns out that this example file and the setup py file are all that are needed to have working extension module in this example if you type python setup py build_ext --inplaceyou will find that you have fully working extension in your directory jython and ironpython extending and embedding is not restricted to programs if you are working with javaconsider the use of jython (the python interpreter in java with jythonyou can simply import java libraries using the import statement for examplebash- jython jython on java_ type "copyright""creditsor "licensefor more information from java lang import system system out println("hello world"hello world if you are working with the net framework on windowsconsider the use of ironpython (complete reimplementation of the python interpreter in cwith ironpythonyou can easily access all of the net libraries from python in similar manner for exampleipy ironpython (on net copyright (cmicrosoft corporation all rights reserved import system math dir(system math['abs''acos''asin''atan''atan ''bigmul''ceiling''cos''cosh'system math cos( - covering jython and ironpython in more detail is beyond the scope of this book howeverjust keep in mind that they're both python--the most major differences are in their libraries lib fl ff |
18,468 | python december python was released-- major update to the python language that breaks backwards compatibility with python in number of critical areas fairly complete survey of the changes made to python can be found in the "what' new in python document available at some sensethe first of this book can be viewed as the polar opposite of the "what' newdocument that isall of the material covered so far has focused on features that are shared by both python and python this includes all of the standard library modulesmajor language featuresand examples aside from few minor naming differences and the fact that print(is functionno unique python features have been described the main focus of this appendix is to describe new features to the python language that are only available in version as well as some important differences to keep in mind if you are going to migrate existing code at the end of this appendixsome porting strategies and use of the to code conversion tool is described who should be using python before going any furtherit is important to address the question of who should be using the python release within the python communityit has always been known that the transition to python would not happen overnight and that the python branch would continue to be maintained for some time (yearsinto the future soas of this writingthere is no urgent need to drop python code suspect that huge amounts of python code will continue to be in development when the th edition of this book is written years from now major problem facing python concerns the compatibility of third-party libraries much of python' power comes from its large variety of frameworks and libraries howeverunless these libraries are explicitly ported to python they are almost certain not to work this problem is amplified by the fact that many libraries depend upon other libraries that depend on yet more libraries as of this writing ( )there are major libraries and frameworks for python that haven' even been ported to python let alone or soif you are using python with the intention of running third-party codeyou are better off sticking with python for now if you've picked up this book and it' the year then hopefully the situation will have improved although python cleans up lot of minor warts in the languageit is unclear if python is currently wise choice for new users just trying to learn the basics almost all existing documentationtutorialscookbooksand examples assume python and use lib fl ff |
18,469 | appendix python coding conventions that are incompatible needless to saysomeone is not going to have positive learning experience if everything appears to be broken even the official documentation is not entirely up-to-date with python coding requirementswhile writing this bookthe author submitted numerous bug reports concerning documentation errors and omissions finallyeven though python is described as the latest and greatestit suffers from numerous performance and behavioral problems for examplethe / system in the initial release exhibits truly horrific and unacceptable runtime performance the separation of bytes and unicode is also not without problem even some of the built-in library modules are broken due to changes related to / and string handling obviously these issues will improve with time as more programmers stress-test the release howeverin the opinion of this authorpython is really only suitable for experimental use by seasoned python veterans if you're looking for stability and production quality codestick with python until some of the kinks have had time to be worked out of the python series new language features this section outlines some features of python that are not supported in python source code encoding and identifiers python assumes that source code is encoded as utf- in additionthe rules on what characters are legal in an identifier have been relaxed specificallyidentifiers can contain any valid unicode character with code point of + or greater for examplep print( * *rjust because you can use such characters in your source code doesn' mean that it' good idea not all editorsterminalsor development tools are equally adept at unicode handling plusit is extremely annoying to force programmers to type awkward key sequences for characters not visibly present on standard keyboard (not to mention the fact that it might make some of the gray-bearded hackers in the office tell everyone another amusing apl storysoit' probably better to reserve the use of unicode characters for comments and string literals set literals set of items can now be defined by enclosing collection of values in braces items for exampledays 'mon''tue''wed''thu''fri''sat''sunthis syntax is the same as using the set(functiondays set(['mon''tue''wed''thu''fri''sat''sun'] lib fl ff |
18,470 | set and dictionary comprehensions the syntax expr for in if conditionalis set comprehension it applies an operation to all of the elements of set and can be used in similar manner as list comprehensions for examplevalues squares { * for in valuessquares { the syntax kexpr:vexpr for , in if condition is dictionary comprehension it applies an operation to all of the keys and values in sequence of (keyvaluetuples and returns dictionary the keys of the new dictionary are described by an expression kexprand the values are described by the expression vexpr this can be viewed as more powerful version of the dict(function to illustratesuppose you had file of stock prices 'prices datlike thisgoog yhoo ibm msft aapl here is program that reads this file into dictionary mapping stock names to price using dictionary comprehensionfields (line split(for line in open("prices dat")prices {sym:float(valfor sym,val in fieldshere is an example that converts all of the keys of the prices dictionary to lowercased {sym lower():price for sym,price in prices items()here is an example that creates dictionary of prices for stocks over $ {sym:price for sym,price in prices items(if price > extended iterable unpacking in python items in an iterable can be unpacked into variables using syntax such as the followingitems [ , , , , , , items unpack items into variables in order for this unpacking to workthe number of variables and items to be unpacked must exactly match in python you can use wildcard variable to only unpack some of the items in sequenceplacing any remaining values in list for examplea,*rest items ,*rest, items *restd items rest [ , , rest [ , ] rest [ , , ] lib fl ff |
18,471 | appendix python in these examplesthe variable prefixed by receives all of the extra values and places them in list the list may be empty if there are no extra items one use of this feature is in looping over lists of tuples (or sequenceswhere the tuples may have differing sizes for examplepoints ( , )( , ,"red")( , ,"blue")( , for , *opt in pointsif optadditional fields were found statements no more than one starred variable can appear in any expansion nonlocal variables inner functions can modify variables in outer functions by using the nonlocal declaration for exampledef countdown( )def decrement()nonlocal - while print(" -minus"ndecrement(in python inner functions can read variables in outer functions but cannot modify them the nonlocal declaration enables this function annotations the arguments and return value of functions can be annotated with arbitrary values for exampledef foo( : , : - pass the function attribute _annotations_ is dictionary mapping argument names to the annotation values the special 'returnkey is mapped to the return value annotation for examplefoo _annotations_ {' ' ' ' 'return' the interpreter does not attach any significance to these annotations in factthey can be any values whatsoever howeverit is expected that type information will be most useful in the future for exampleyou could write thisdef foo( :inty:int-strstatements annotations are not limited to single values an annotation can be any valid python expression for variable positional and keyword argumentsthe same syntax applies for exampledef bar( *args:"additional"**kwargs:"options")statements lib fl ff |
18,472 | againit is important to emphasize that python does not attach any significance to annotations the intended use is in third-party libraries and frameworks that may want to use them for various applications involving metaprogramming examples includebut are not limited tostatic analysis toolsdocumentationtestingfunction overloadingmarshallingremote procedure callidescontractsetc here is an example of decorator function that enforces assertions on function arguments and return valuesdef ensure(func)extract annotation data return_check func _annotations_ get('return',nonearg_checks [(name,func _annotations_ get(name)for name in func _code_ co_varnamescreate wrapper that checks argument values and the return result using the functions specified in annotations def assert_call(*args,**kwargs)for (name,check),value in zip(arg_checks,args)if checkassert check(value)"% % (namecheck _doc_ _for name,check in arg_checks[len(args):]if checkassert check(kwargs[name])"% % (namecheck _doc_ _result func(*args,**kwargsassert return_check(result)"return %sreturn_check _doc_ return result return assert_call here is an example of code that uses the previous decoratordef positive( )"must be positivereturn def negative( )"must be negativereturn @ensure def foo( :positiveb:negative-positivereturn following is some sample output of using the functionfoo( ,- foo(- , traceback (most recent call last)file ""line in file "meta py"line in call def assert_call(*args,**kwargs)assertionerrora must be positive keyword-only arguments functions can specify keyword-only arguments this is indicated by defining extra parameters after the first starred parameter for exampledef foo( *argsstrict=false)statements lib fl ff |
18,473 | appendix python when calling this functionthe strict parameter can only be specified as keyword for examplea foo( strict=trueany additional positional arguments would just be placed in args and not used to set the value of strict if you don' want to accept variable number of arguments but want keyword-only argumentsuse bare in the parameter list for exampledef foo( *strict=false)statements here is an example of usagefoo( ,truefoo( ,strict=truefails typeerrorfoo(takes positional argument ok ellipsis as an expression the ellipsis object can now appear as an expression this allows it to be placed in containers and assigned to variables for examplex ellipsis [ , [ ellipsisin true is true assignment of ellipsis the interpretation of the ellipsis is still left up to the application that uses it this feature allows the to be used as an interesting piece of syntax in libraries and frameworks (for exampleto indicate wild-cardcontinuationor some similar conceptchained exceptions exceptions can now be chained together essentially this is way for the current exception to carry information about the previous exception the from qualifier is used with the raise statement to explicitly chain exceptions for exampletrystatements except valueerror as eraise syntaxerror("couldn' parse configuration"from when the syntaxerror exception is raiseda traceback message such as the following will be generated--showing both exceptionstraceback (most recent call last)file ""line in valueerrorinvalid literal for int(with base 'ninethe above exception was the direct cause of the following exceptionf lib fl ff |
18,474 | traceback (most recent call last)file ""line in syntaxerrorcouldn' parse configuration exception objects have _cause_ attributewhich is set to the previous exception use of the from qualifier with raise sets this attribute more subtle example of exception chaining involves exceptions raised within another exception handler for exampledef error(msg)print(mnotetypo is intentional ( undefinedtrystatements except valueerror as eerror("couldn' parse configuration"if you try this in python you only get an exception related to the nameerror in error(in python the previous exception being handled is chained with the result for exampleyou get this messagetraceback (most recent call last)file ""line in valueerrorinvalid literal for int(with base 'nineduring handling of the above exceptionanother exception occurredtraceback (most recent call last)file ""line in file ""line in error nameerrorglobal name 'mis not defined for implicit chainingthe _context_ attribute of an exception instance contains reference to previous exception improved super(the super(functionused to look up methods in base classescan be used without any arguments in python for exampleclass ( , )def bar(self)return super(bar(call bar(in bases in python you had to use super( ,selfbar(the old syntax is still supported but is significantly more clunky advanced metaclasses in python you can define metaclasses that alter the behavior of classes subtle facet of the implementation is that the processing carried out by metaclass only occurs after the body of class has executed that isthe interpreter executes the entire body of class and populates dictionary once the dictionary has been populatedthe dictionary is passed to the metaclass constructor (after the body of the class has executedin python metaclasses can additionally carry out extra work before the class body executes this is done by defining special class method called _prepare_ (clsnamebases**kwargsin the metaclass this method must return dictionary as lib fl ff |
18,475 | appendix python result this dictionary is what gets populated as the body of the class definition executes here is an example that outlines the basic procedureclass mymeta(type)@classmethod def _prepare_ (cls,name,bases,**kwargs)print("preparing",name,bases,kwargsreturn {def _new_ (cls,name,bases,classdict)print("creating",name,bases,classdictreturn type _new_ (cls,name,bases,classdictpython uses an alternative syntax for specifying metaclass for exampleto define class that uses mymetayou use thisclass foo(metaclass=mymeta)print("about to define methods"def _init_ (self)pass def bar(self)pass print("done defining methods"if you run the following codeyou will see the following output that illustrates the control flowpreparing foo ({about to define methods done defining methods creating foo ({' _module_ '' _main_ ''bar'' _init_ 'the additional keyword arguments on the _prepare_ (method of the metaclass are passed from keyword arguments used in the bases list of class statement for examplethe statement class foo(metaclass=mymeta,spam= ,blah="hello"passes the keyword arguments spam and blah to mymeta _prepare_ (this convention can be used to pass arbitrary configuration information to metaclass to perform any kind of useful processing with the new _prepare_ (method of metaclassesyou generally have the method return customized dictionary object for exampleif you wanted to perform special processing as class is definedyou define class that inherits from dict and reimplements the _setitem_ (method to capture assignments to the class dictionary the following example illustrates this by defining metaclass that reports errors if any method or class variable is multiply defined class multipledef(dict)def _init_ (self)self multipleset(def _setitem_ (self,name,value)if name in selfself multiple add(namedict _setitem_ (self,name,valueclass multimeta(type)@classmethod def _prepare_ (cls,name,bases,**kwargs)return multipledef(def _new_ (cls,name,bases,classdict)for name in classdict multipleprint(name,"multiply defined" lib fl ff |
18,476 | if classdict multipleraise typeerror("multiple definitions exist"return type _new_ (cls,name,bases,classdictif you apply this metaclass to another class definitionit will report an error if any method is redefined for exampleclass foo(metaclass=multimeta)def _init_ (self)pass def _init_ (self, )pass error _init_ multiply defined common pitfalls if you are migrating from python to be aware that python is more than just new syntax and language features major parts of the core language and library have been reworked in ways that are sometimes subtle there are aspects of python that may seem like bugs to python programmer in other casesthings that used to be "easyin python are now forbidden this section outlines some of the most major pitfalls that are likely to be encountered by python programmers making the switch text versus bytes python makes very strict distinction between text strings (charactersand binary data (bytesa literal such as "hellorepresents text string stored as unicodewhereas "hellorepresents string of bytes (containing ascii letters in this caseunder no circumstances can the str and bytes type be mixed in python for exampleif you try to concatenate strings and bytes togetheryou will get typeerror exception this differs from python where byte strings would be automatically coerced into unicode as needed to convert text string into bytesyou must use encode(encodingfor examples encode('utf- 'converts into utf- encoded byte string to convert byte string back into textyou must use decode(encodingyou can view the encode(and decode(methods as kind of "type castbetween strings and bytes keeping clean separation between text and bytes is ultimately good thing--the rules for mixing string types in python were obscure and difficult to understand at best howeverone consequence of the python approach is that byte strings are much more restricted in their ability to actually behave like "text although there are the standard string methods like split(and replace()other aspects of byte strings are not the same as in python for instanceif you print byte stringyou simply get its repr(output with quotes such as 'contentssimilarlynone of the string formatting operations (%format()work for examplex 'hello worldprint(xprint( "you said '% 'xproduces 'hello worldtypeerroroperator not supported the loss of text-like behavior with bytes is potential pitfall for system programmers despite the invasion of unicodethere are many cases where one actually does want to lib fl ff |
18,477 | appendix python work with and manipulate byte-oriented data such as ascii you might be inclined to use the bytes type to avoid all of the overhead and complexity of unicode howeverthis will actually make everything related to byte-oriented text handling more difficult here is an example that illustrates the potential problemscreate response message using strings (unicodestatus msg "okproto "http/ response "% % % (protostatusmsgprint(responsehttp/ ok create response message using only bytes (asciistatus msg "okproto "http/ response "% % % (protostatusmsgtraceback (most recent call last)file ""line in typeerrorunsupported operand type(sfor %'bytesand 'tupleresponse proto bstr(statusbmsg traceback (most recent call last)file ""line in typeerrorcan' concat bytes to str bytes(statusb'\ \ \ \ \ \ \ \ \ \ bytes(str(status)traceback (most recent call last)file ""line in typeerrorstring argument without an encoding bytes(str(status),'ascii' ' response proto bbytes(str(status),'ascii'bmsg print(responseb'http/ okprint(response decode('ascii')http/ ok in the exampleyou can see how python is strictly enforcing the text/bytes separation even operations that seem like they should be simplesuch as converting an integer into ascii charactersare much more complicated with bytes the bottom line is that if you're performing any kind of text-based processing or formattingyou are probably always better off using standard text strings if you need to obtain byte-string after the completion of such processingyou can use encode('latin- 'to convert from unicode the text/bytes distinction is somewhat more subtle when working with various library modules some libraries work equally well with text or byteswhile some forbid bytes altogether in other casesthe behavior is different depending on what kind of input is received for examplethe os listdir(dirnamefunction only returns filef lib fl ff |
18,478 | names that can be successfully decoded as unicode if dirname is string if dirname is byte stringthen all filenames are returned as byte strings new / system python implements an entirely new / systemthe details of which are described in the io module section of "operating system services "the new / system also reflects the strong distinction between text and binary data present with strings if you are performing any kind of / with textpython forces you to open files in "text modeand to supply an optional encoding if you want anything other than the default (usually utf- if you are performing / with binary datayou must open files in "binary modeand use byte strings common source of errors is passing output data to file or / stream opened in the wrong mode for examplef open("foo txt","wb" write("hello world\ "traceback (most recent call last)file ""line in file "/tmp/lib/python /io py"line in write raise typeerror("can' write str to binary stream"typeerrorcan' write str to binary stream socketspipesand other kinds of / channels should always be assumed to be in binary mode one potential problem with network code in particular is that many network protocols involve text-based request/response processing ( httpsmtpftpetc given that sockets are binarythis mix of binary / and text processing can lead to some of the problems related to mixing text and bytes that were described in the previous section you'll need to be careful print(and exec(functions the print and exec statements from python are now functions use of the print(function compared to its python counterpart is as followsprint( , ,zprint( , , ,end='print( ,file=fsame as print xyz same as print xyzsame as print >>fa the fact that print(is function that means you can replace it with an alternative definition if you want exec(is also now functionbut its behavior in python is subtly different than in python for exampleconsider this codedef foo()exec(" "print(ain python calling foo(will print the number ' in python you get nameerror exception with the variable being undefined what has happened here is that exec()as functiononly operates on the dictionaries returned by the globals(and locals(functions howeverthe dictionary returned by locals(is actually copy of the local variables the assignment made in the exec(function is lib fl ff |
18,479 | appendix python merely modifying this copy of the localsnot the local variables themselves here is one workarounddef foo()_locals locals(exec(" ",globals(),_localsa _locals[' 'extract the set variable print(aas general ruledon' expect python to support the same degree of "magicthat was possible using exec()eval()and execfile(in python in factexecfile(is gone entirely (you can emulate its functionality by passing an open file-like object to exec()use of iterators and views python makes much greater use of iterators and generators than python built-in functions such as zip()map()and range(that used to return lists now return iterables if you need to make list from the resultuse the list(function python takes slightly different approach to extracting key and value information from dictionary in python you could use methods such as keys() values()or items(to obtain lists of keysvaluesor key/value pairsrespectively in python these methods return so-called view objects for examples 'goog' 'aapl' 'ibm' keys( values( these objects support iteration so if you want to view the contentsyou can use for loop for examplefor in kprint(xgoog aapl ibm view objects are always tied back to the dictionary from which they were created subtle aspect of this is that if the underlying dictionary changesthe items produced by the view change as well for examples['acme' for in kprint(xgoog aapl ibm acme should it be necessary to build list of dictionary keys or valuessimply use the list(function--for examplelist( keys() lib fl ff |
18,480 | integers and integer division python no longer has an int type for -bit integers and separate long type for long integers the int type now represents an integer of arbitrary precision (the internal details of which are not exposed to the userin additioninteger division now always produces floating-point result for example / is not the conversion to float applies even if the result would have been an integer for example / is not comparisons python is much more strict about how values are compared in python it is the case that any two objects can be compared even if it doesn' make sense for example "hellotrue in python this results in typeerror for example "hellotraceback (most recent call last)file ""line in typeerrorunorderable typesint(str(this change is minorbut it means that in python you have to be much more careful about making sure data is of appropriate types for exampleif you use the sort(method of listall of the items in the list must be compatible with the operatoror you get an error in python the operation would be silently carried out anyways with usually meaningless result iterators and generators python has made slight change to the iterator protocol instead of calling _iter_ (and the next(method to perform iterationthe next(method has been renamed to _next_ (most users will be unaffected by this change except if you have written code that manually iterates over an iterable or if you have defined your own custom iterator objects you will need to make sure you change the name of the next(method in your classes use the built-in next(function to invoke the next(or _next_ (method of an iterator in portable manner file namesargumentsand environment variables in python filenamescommand-line arguments in sys argvand environment variables in os environ may or may not be treated as unicode depending on local settings the only problem is that the usage of unicode within the operating system environment is not entirely universal for exampleon many systems it may be technically possible to specify filenamescommand-line optionsand environment variables that are just raw sequence of bytes that don' correspond to valid unicode encoding although these situations might be rare in practiceit may be of some concern for programming using python to perform tasks related to systems administration as previously notedsupplying file and directory names as byte strings will fix many of the problems for exampleos listdir( '/foo' lib fl ff |
18,481 | library reorganization python reorganizes and changes the names of several parts of the standard librarymost notably modules related to networking and internet data formats in additiona wide variety of legacy modules have been dropped from the library ( gopherlibrfc and so onit is now standard practice to use lowercase names for modules several modules such as configparserqueueand socketserver have been renamed to configparserqueueand socketserverrespectively you should try to follow similar conventions in your own code packages have been created to reorganize code that was formerly contained in disparate modules--for examplethe http package containing all the module used to write http serversthe html package has modules for parsing htmlthe xmlrpc package has modules for xml-rpcand so forth as for deprecated modulesthis book has been careful to only document modules that are in current use with python and python if you are working with existing python code and see it using module not documented herethere is good chance that the module has been deprecated in favor of something more modern just as an examplepython doesn' have the popen module commonly used in python to launch subprocesses insteadyou should use the subprocess module absolute imports related to library reorganizationall import statements appearing in submodules of package use absolute names this is covered in more detailed in "modulespackagesand distribution,but suppose you have package organized like thisfoo_ _init_ py spam py bar py if the file spam py uses the statement import baryou get an importerror exception even though bar py is located in the same directory to load this submodulespam py either needs to use import foo bar or package relative import such as from import bar this differs from python where import always checks the current directory for match before moving onto checking other directories in sys path code migration and to converting code from python to python is delicate topic just to be absolutely clearthere are no magic importsflagsenvironment variablesor tools that will enable python to run an arbitrary python program howeverthere are some very specific steps that can be taken to migrate codeeach of which is now described porting code to python it is recommended that anyone porting code to python first port to python python is not only backwards-compatible with python but it also supports subset of new features found in python examples include advanced string formattingthe new exception syntaxbyte literalsi/ libraryand abstract base classes thusa lib fl ff |
18,482 | python program can start to take advantage of useful python features now even if it is not yet ready to make the full migration the other reason to port to python is that python issues warning messages for deprecated features if you run it with the - command-line option for examplebash- python - python (trunk: : moct : : [gcc (apple computerinc build )on darwin type "help""copyright""creditsor "licensefor more information has_key('foo' _main_ : deprecationwarningdict has_key(not supported in xuse the in operator false >using these warning messages as guideyou should take great care to make sure that your program runs warning-free on python before moving forward with python port providing test coverage python has useful testing modules including doctest and unittest make sure your application has thorough test coverage before attempting python port if your program has not had any tests to this pointnow would be good time to start you will want to make sure your tests cover as much as possible and that all tests pass without any warning messages when run on python using the to tool python includes tool called to that can assist with code migration from python to python this tool is normally found in the tools/scripts directory of the python source distribution and is also installed in the same directory as the python binary on most systems it is command-line tool that would normally run from unix or windows command shell as an exampleconsider the following program that contains number of deprecated features example py import configparser for in xrange( )print * def spam( )if not has_key("spam") ["spam"load_spam(return ["spam"to run to on this programtype " to example pyfor example to example py refactoringtoolskipping implicit fixerbuffer refactoringtoolskipping implicit fixeridioms refactoringtoolskipping implicit fixerset_literal refactoringtoolskipping implicit fixerws_comma --example py (original++example py (refactored@- , + , @ lib fl ff |
18,483 | appendix python example py -import configparser +import configparser -for in xrange( )print * +for in range( )print( *idef spam( )if not has_key("spam")if "spamnot in dd["spam"load_spam(return ["spam"refactoringtoolfiles that need to be modifiedrefactoringtoolexample py as output to will identify parts of the program that it considers to be problematic and that might need to be changed these are shown as context-diffs in the output although we have used to on single fileif you give it the name of directoryit recursively looks for all python files contained in the directory structure and generates report for everything by default to does not actually fix any of the source code it scans--it merely reports parts of the code that might need to be changed challenge faced by to is that it often only has incomplete information for exampleconsider the spam(function in the example code this function calls method has_key(for dictionarieshas_key(has been removed in favor of the in operator to reports this changebut without more informationit is not clear if spam(is actually manipulating dictionary or not it might be the case that is some other kind of object ( database perhapsthat happens to provide has_key(methodbut where using the in operator would fail another problematic area for to is in the handling of byte strings and unicode given that python would automatically promote byte strings to unicodeit is somewhat common to see code that carelessly mixes the two string types together unfortunately to is unable to sort all of this out this is one reason why it' important to have good unit test coverage of courseall of this depends on the application as an option to can be instructed to fix selected incompatibilities firsta list of "fixerscan be obtained by typing to - for example to - available transformations for the - /--fix optionapply basestring buffer callable xrange xreadlines zip using names from this listyou can see what selected fix would actually change by simply typing " to - fixname filenameif you want to apply multiple fixesjust specify each one with separate - option if you actually want to apply the fix to source fileadd the - option as in to - fixname - filename here is an examplef lib fl ff |
18,484 | to - xrange - example py --example py (original++example py (refactored@- , + , @example py import configparser -for in xrange( )+for in range( )print * def spam( )refactoringtoolfiles that were modifiedrefactoringtoolexample py if you look at example py after this operationyou will find that xrange(has been changed to range(and that no other changes have been made backup of the original example py file is found in example py bak counterpart to the - option is the - option if you use to - fixname filenameit will run all of the fixers except for the ones you listed with the - option although it is possible to instruct to to fix everything and to overwrite all of your filesthis is probably something best avoided in practice keep in mind that code translation is an inexact science and that to is not always going to do the "right thing it is always better to approach code migration in methodical calculated manner as opposed to crossing your fingers and hoping that it all just magically "works to has couple of additional options that may be useful the - option enables verbose mode that prints additional information that might be useful for debugging the - option tells to that you are already using the print statement as function in your code and that it shouldn' be converted (enabled by the from _future_ import print_statement statementa practical porting strategy here is practical strategy for porting python code to python againit is better to approach migration in methodical manner as opposed to doing everything at once make sure your code has an adequate unit testing suite and that all tests pass under python port your code and testing suite to python and make sure that all tests still pass turn on the - option to python address all warning messages and make sure your program runs and passes all tests without any warning messages if you've done this correctlychances are that your code will still work with python and maybe even earlier releases you're really just cleaning out some of the cruft that' accumulated in your program make backup of your code (this goes without saying port the unit testing suite to python and make sure that the testing environment itself is working the individual unit tests themselves will fail (because you haven' yet ported any codehowevera properly written test suite should be able to deal with test failures without having an internal crash of the test software itself lib fl ff |
18,485 | appendix python convert the program itself to python using to run the unit testing suite on the resulting code and fix all of the issues that arise there are varying strategies for doing this if you're feeling luckyyou can always tell to to just fix everything and see what happens if you're more cautiousyou might start by having to fix the really obvious things (printexcept statementsxrange()library module namesetc and then proceed in more piecemeal manner with the remaining issues by the end of this processyour code should pass all unit tests and operate in the same manner as before in theoryit is possible to structure code in way so that it both runs in python and automatically translates to python without any user intervention howeverthis will require very careful adherence to modern python coding conventions--at the very least you will absolutely need to make sure there are no warnings in python if the automatic translation process requires very specific use of to (such as running only selected set of fixers)you should probably write shell script that automatically carries out the required operations as opposed to requiring users to run to on their own simultaneous python and python support final question concerning python migration is whether or not it' possible to have single code base that works unmodified on python and python although this is possible in certain casesthe resulting code runs the risk of becoming contorted mess for instanceyou will have to avoid all print statements and make sure all except clauses never take any exception values (extracting them from sys exc_info(insteadother python features can' be made to work at all for exampledue to syntax differencesthere is no possible way to use metaclasses in way that would be portable between python and python thusif you're maintaining code that must work on python and your best bet is to make sure your code is as clean as possible and runs under python make sure you have unit testing suiteand try to develop set of to fixes to make automatic translation possible one case where it might make sense to have single code base is with unit testing test suite that operates without modification on python and python could be useful in verifying the correct behavior of the application after being translated by to participate as an open-source projectpython continues to be developed with the contributions of its users for python especiallyit is critically to report bugsperformance problemsand other issues to report buggo to feedback makes python better for everyone lib fl ff |
18,486 | symbols numbers debugger commandpdb module !not equal to operator single quotes ''triple quotes double quotes ""triple quotes comment #in unix shell scripts rewriting on package installation modulo operator string formatting operator %operator bitwise-and operator set intersection operator addition operator list concatenation operator sequence concatenation operator string concatenation operator unary plus operator +operator hyphen characterused as filename set difference operator subtraction operator unary minus operator -*codingcommentin source code -operator attribute binding operator and modules special methods for &operator directory reference in relative import statements (function call operator ellipsis (tuple interpreter prompt keyword only argumentspython division operator multiplication operator /truncating division operator passing sequences as function arguments //operator sequence replication operator /operator colon in string formatting specifiers variable arguments in function definition semicolon wildcard left alignment in string format specifiers from module import iterable unpacking in python *passing dictionaries as keyword arguments less than operator <left shift operator <<operator *power operator <less than or equal to operator *variable keyword arguments in function definition =equal to operator **operator right alignment in string format specifiers *operator greater than operator lib fl ff |
18,487 | >greater than or equal to operator >greater than or equal to operator >file redirection modifier to print 'amodeto open(function >right shift operator (argsdebugger commandpdb module >>operator interpreter prompt b_base (functionbinascii module decorator b_hex(functionbinascii module [::extended slicing operator - - b_hqx(functionbinascii module [:slicing operator - - b_uu(functionbinascii module [indexing operator - abc module and special methods on mappings on sequences [list line continuation character string escape codes bitwise-xor operator centered alignment in string format specifiers set symmetric difference operator ^operator variableinteractive mode {dict {placeholder in format strings {set literalpython bitwise-or operator set union operator |operator bitwise-negation operator expanding user home directory in filenames $variables in strings binary integer literal octal integer literal hexadecimal integer literal ' complement and integers to tool - limitations of - command line option abcmeta metaclass abort(functionos module abort(methodof ftp objects abs(function operator module _abs_ (method absolute imports python compared to relative imports absolute value abspath(functionos path module abstract base class calling methods in subclasses checking performed container objects error if instantiated example files and / numeric types registering pre-existing classes special methods for @abstractmethod decorator - - _abstractmethods_ attributeof types @abstractproperty decorator - - accept(method of listener objects of dispatcher objects of socket objects accept dyear variabletime module access control specifierslack of lib fl ff |
18,488 | acos(functionmath module addlevelname(functionlogging module acosh(functionmath module address attribute access(functionos module acquire(method of condition objects of lock objects of rlock objects of semaphore objects of basemanager objects of listener objects address familiesof sockets address_family attributeof socketserver class activate(methodof socketserver class addressesnetwork active_children(functionmultiprocessing module adjacent string literalsconcatenation of active_count(functionthreading module advanced string formatting activepython add(functionoperator module add(method of tarfile objects of sets _add_ (method add_data(methodof request objects add_header(method of message objects of request objects add_option(methodof optionparser objects add_password(methodof authhandler objects addressof(functionctypes module adler (functionzlib module af_constantssocket module aifc module aio_family of system callslack of ajaxexample of alarm(functionsignal module alarms alias debugger commandpdb module alignment(functionctypes module _all_ variable and import statements in packages all(function allow_reuse_address attributeof socketserver class altsep variableos module add_section(methodof configparser objects altzone variabletime module add_type(functionmimetypes module and_(functionoperator module add_unredirected_header(methodof request objects addfile(methodof tarfile objects addfilter(method of handler objects of logger objects addhandler(methodof logger objects addition operator + and operatorboolean expressions _and_ (method _annotations_ attributeof functions anonymous functions any(function anydbm module api_version variablesys module %appdataenvironment variablewindows how can we make this index more usefulemail us at indexes@samspublishing com lib fl ff |
18,489 | append(method append(method of element objects of array objects of deque objects of lists ascii_letters variablestring module ascii_lowercase variablestring module ascii_uppercase variablestring module appendchild(methodof dom node objects asctime(functiontime module appendleft(methodof deque objects asinh(functionmath module application logging assert statement applicationswsgi assert_(methodof testcase objects applicative order evaluation assertalmostequal(methodof testcase objects apply(methodof pool objects apply_async(methodof pool objects args attribute asin(functionmath module assertequal(methodof testcase objects of exception objects of exceptions of partial objects assertionerror exception argtypes attributeof ctypes function objects assertnotalmostequal(methodof testcase objects argv variablesys module assertnotequal(methodof testcase objects arithmeticerror exception assertraises(methodof testcase objects array module array(functionmultiprocessing module array(methodof manager objects array(functionarray module arrayscreating from uniform type arraysize attributeof cursor objects as qualifier of except statement of from-import statement of import statement of with statement assertions stripping with - option assignment and reference counting augmented in-place operators of instance attributes of variables to variables in nested functions associative array associativity of operators astimezone(methodof datetime objects asynchat classasynchat module as_integer_ratio(methodof floating point asynchat module as_string(methodof message objects asynchronous / ascii encodingdescription of asynchronous networking ascii(function and python future_builtins module asciiand compatibility with utf- use of and blocking operations when to consider asyncore module use of asyncresult objectsmultiprocessing module lib fl ff |
18,490 | atan(functionmath module atan (functionmath module atanh(functionmath module atexit module - command line option characterbefore string literal atomic operationsdisassembly (reakdebugger commandpdb module attach(methodof message objects decode(functionbase module attrgetter(functionoperator module encode(functionbase module attrib attributeof element objects attribute assignmenton instances a_base (functionbinascii module attribute binding operator a_hex(functionbinascii module optimization of attribute binding and inheritance and methods instances and classes of user-defined objects process of redefining in classes special methods for attribute deletionon instances a_hqx(functionbinascii module a_uu(functionbinascii module decode(functionbase module encode(functionbase module decode(functionbase module encode(functionbase module backslash rulesand raw strings 'backslashreplaceerror handlingunicode encoding attribute lookup in string formatting badstatusline exceptionhttp client module attributeerror exception base class and attribute binding attributes attributeof dom node objects attributes computed as properties creation in _init_ (method descriptors encapsulation of lookup in composite string formatting of objects private restricting names with _slots_ user defined on functions audioop module augmented assignment operators authenticationfetching urls authkey attributeof process objects base- decimals and floating point base encodingdescription of base module basecgihandler(functionwsgiref handlers module baseexception class baseexception exception basehttprequesthandler classhttp server module basehttpserver modulesee http server basemanager(functionmultiprocessing module basename(functionos path module baseproxy classmultiprocessing module awk unix commandsimilarity to list comprehensions how can we make this index more usefulemail us at indexes@samspublishing com lib fl ff |
18,491 | baserequesthandler classsocketserver module baserequesthandler classsocketserver module bitwise-negation operator ~ _bases_ attribute bitwise-xor operator ^ of classes of types basestring variable bitwise-or operator | blank lines block_size attributeof digest objects basicconfig(functionlogging module blocking operationsand asynchronous networking basiccontext variabledecimal module bluetooth protocol bat fileswindows bom (byte order marker) bdb module address format and unicode beautiful soup package bom_constantscodecs module betavariate(functionrandom module bool type bidirectional(functionunicodedata module bool(function big endian format big endianpacking and unpacking bin(function binary data structurespacking and unpacking binary distributioncreating with distutils binary file mode binary files buffered / caution on using line-oriented functions - _bool_ (method boolean expressions evaluation rules boolean operators boolean values boolean(functionxmlrpc client module bound method boundedsemaphore object multiprocessing module threading module binary integer literals boundedsemaphore(methodof manager objects binary(function break statement - database api xmlrpc client module binascii module bind(method of socketserver class of dispatcher objects of socket objects binhex module bisect module bisect(functionbisect module bisect_left(functionbisect module bisect_right(functionbisect module bitwise operations and native integers bitwise-and operator & and generators breaking long statements on multiple lines breakpoint setting in debugger setting manually browserlaunching from python bsdkqueue interface btproto_constantssocket module buffercircular buffer_info(methodof array objects buffered binary / bufferediobase abstract base class bufferedrandom classio module bufferedreader classio module lib fl ff |
18,492 | bufferedrwpair classio module bufferedwriter classio module bufferingand generators extensions and egg files and module reloading compiling with distutils creating with swig example with ctypes releasing global interpreter lock build_opener(functionurllib request module built-in exceptions built-in functions and types built-in functionsusing python functions in python built-in types _builtin_ module builtin_module_names variablesys module builtinfunctiontype builtinfunctiontype type builtins modulepython byref(functionctypes module byte literals byte strings and wsgi and files and system interfaces in python as in-memory binary files decoding as unicode different behavior in python lack of formatting in python mixing with unicode strings mutable byte arrays use in system interfaces bytearray(function byteorder variablesys module bytes datatypepython bytes(function - bytesescape code in strings bytesio classio module - command line option - # (ont(inue)debugger commandpdb module ++difference in class system python variables compared to implementation of functions / +codein third-party packages linearization algorithmand inheritance c_datatypesctypes module cacheftphandler classurllib request module caching results of function calcsize(functionstruct module calendar module call(functionsubprocess module _call_ (method callable abstract base class callable objects and _call_ (method classes instances types of callback functions and lambda byteswap(methodof array objects calling python functions from bz module calling function bz compressor(functionbz module _callmethod(methodof baseproxy objects bz decompressor(functionbz module callproc(methodof cursor objects bz file(functionbz module cancel(methodof timer objects how can we make this index more usefulemail us at indexes@samspublishing com lib fl ff |
18,493 | cancel_join_thread(methodof queue objects cancel_join_thread(methodof queue objects chained comparisons cannotsendheader exceptionhttp client module changing display of resultsinteractive mode cannotsendrequest exceptionhttp client module changing module name on import capitalize(methodof strings - chained exceptionspython changing the working directory capitals attributeof context objects changing user-agent header in http requests capwords(functionstring module character substitution case conversionof strings - case sensitivityof identifiers characters(methodof contenthandler objects case statementlack of characters cast(functionctypes module catching all exceptions escape codes specifying unicode catching multiple exceptions chdir(functionos module category(functionunicodedata module check_call(functionsubprocess module _cause_ attributeof exception objects check_unused_args(methodof formatter objects caution with range(function checking if running as main program cdll(functionctypes module checking multiple cases with conditional ceil(functionmath module center(methodof strings - cert_time_to_seconds(functionssl module cgi script advice for writing environment variables executing xml-rpc server within running wsgi application use of databases web frameworks cgi module cgihandler(functionwsgiref handlers module cgihttprequesthandler classhttp server module cgihttpserver modulesee http server cgitb module cgixmlrpcrequesthandler classxmlrpc server module chain(functionitertools module chflags(functionos module chickenmultithreaded childnodes attributeof dom node objects chmod(functionos module choice(functionrandom module chown(functionos module chr(function chroot(functionos module chunk module cipher(methodof ssl objects circular buffer or queue with deque objects cl(eardebugger commandpdb module class decorators class method attribute binding of practical use of class statement and inheritance execution of class body lib fl ff |
18,494 | class variables sharing by all instances _class_ attribute of instances of methods classes _del_ (method and garbage collection - _init_ (method _init_ (method and inheritance _slots_ attribute abstract base class access control specifierslack of accessing in modules and metaclasses as callable as namespaces attribute binding rules class method creation of instances customizing attribute access - decorators applied to defining methods descriptor attributes difference from +or java inheritance inheriting from built-in types memory management mixin multiple inheritance - object base class old-style operating overloading optimization of optimization of inheritance performance of _slots_ pickling of private members redefining attribute binding scoping rules within self parameter of methods special methods static methods super(function in methods supporting pickle module type of uniform access principle versus dicts for storing data @classmethod decorator classtype typeold-style classes cleandoc(functioninspect module clear(method of element objects of event objects of deque objects of dicts of sets clear_flags(methodof context objects clear_memo(methodof pickler objects _clear_type_cache(functionsys module clearing dictionary clearing last exception client classmultiprocessing module client program tcp example udp example client_address attribute of basehttprequesthandler objects of baserequesthandler objects clock(functiontime module clonenode(methodof dom node objects close(functionos module close(method of connection objects of cursor objects of ftp objects of htmlparser objects of httpconnection objects of handler objects how can we make this index more usefulemail us at indexes@samspublishing com lib fl ff |
18,495 | close(method of iobase objects of listener objects of pool objects of queue objects of tarfile objects of treebuilder objects of zipfile objects of dbm-style database objects of dispatcher objects of files of generators of generators and synchronization of mmap objects of shelve objects of socket objects of urlopen objects close_when_done(methodof asynchat objects closed attribute of iobase objects of files code objects attributes of creating with compile(function code pointunicode _code_ attributeof functions codeexecuting strings codecinfo classcodecs module codecs module removal of compression codecs use of byte strings coded_value attributeof morsel objects codeop module codetype type _coerce_ (methoddeprecation of coercion of numeric types - collect functiongc module collect(functiongc module collect_incoming_data(methodof asynchat objects closefd attributeof fileio objects collectiondefinition of closefd parameterto open(function collections module closekey(functionwinreg module colorsys module closerange(functionos module combinations(functionitertools module closing(functioncontextlib module _closure_ attributeof functions closures - and decorators and nested functions and wrappers speedup over classes cmath module cmd module cmp(function filecmp module combine(methodof datetime class combining(functionunicodedata module command attributeof basehttprequesthandler objects command line options python detecting settings in program for interpreter parsing with optparse cmpfiles(functionfilecmp module commands debugger commandpdb module co_attributesof code objects - commands module code executionin modules - comment attributeof zipinfo objects code migration comment(functionxml etree elementtree module python to practical strategy for code module comments commit(methodof connection objects lib fl ff |
18,496 | common attributeof dircmp objects compress(method common_dirs attributeof dircmp objects of bz compressor objects of compressobj objects common_files attributeof dircmp objects compress_size attributeof zipinfo objects common_funny attributeof dircmp objects compress_type attributeof zipinfo objects commonprefix(functionos path module compression communicate(methodof popen objects of files zlib compression comparison operators compressionerror exceptiontarfile module comparison compressobj(functionzlib module python chained of incompatible objects of objects of sequences of weak references compilation into bytecode compile(function re module - compileall module compilerlack of complete_statement(functionsqlite module complex abstract base class complex numbers cmath library module comparison of computed attributes and properties concat(functionoperator module concatenation of adjacent string literals of lists of strings concurrency advice on multiprocessing and python programs and side effects coroutines global interpreter lock limitations on multicore message passing - multitasking with generators scaling issues synchronization problems complex type concurrent programming complex(function condition object _complex_ (method - and type coercion composing email messages composite string formatting and _format_ () and lookups compress(function bz module zlib module multiprocessing module threading module condition debugger commandpdb module condition variable condition(methodof manager objects conditional expressions conditionals configparser classconfigparser module how can we make this index more usefulemail us at indexes@samspublishing com lib fl ff |
18,497 | configparser module configparser module configuration files difference from python script - for logging module variable substitution locking nested _context_ attributeof exception objects contextlib module confstr(functionos module @contextmanager decorator conjugate(method continue statement - of complex numbers of floating point connect(function database api sqlite module connect(method of basemanager objects of ftp objects of httpconnection objects of smtp objects of dispatcher objects of socket objects connect_ex(methodof socket objects connecting processesmultiprocessing module connection class database api sqlite module connectregistry(functionwinreg module console windowwindows container abstract base class container objects and reference counting definition of containment testin operator contains(functionoperator module _contains_ (method contenthandler classxml sax module contenttooshort exceptionurllib error module context classdecimal module control charactersstripping from string conversion of strings to numbers conversion operations convert_field(methodof formatter objects converting python types to converting dictionaries to list converting sequences to list converting sequences to set converting sequences to tuple converting types from to python converting types from python to cookie modulesee http cookies cookieerror exceptionhttp cookies module cookiejar classhttp cookiejar module cookielib modulesee http cookiejar cookies http fetching urls with cookie support copy module limitations of copy(function copy module shutil module copy(method of context objects of dicts of digest objects of hmac objects of sets context management protocol copy (functionshutil module context managers _copy_ (method decimal module defining with generator copy_reg module lib fl ff |
18,498 | copyfile(functionshutil module countingin loops copyfileobj(functionshutil module countof(functionoperator module copying directories cp encodingdescription of copying files cp encodingdescription of copying cpickle module and reference counting deep copy dictionary of mutable objects shallow copy cprofile module cpu timeobtaining cpuobtaining number on system cpu-bound tasks and threads copymode(functionshutil module cpu_count(functionmultiprocessing module copyright variablesys module crc attributeof zipinfo objects copysign(functionmath module crc (function copystat(functionshutil module copytree(functionshutil module binascii module zlib module @coroutine decorator example crc_hqx(functionbinascii module coroutines create_aggregate(methodof connection objects advanced example asynchronous / handling building call stack of concurrency concurrent programming example of execution behavior message passing multitasking example practical use of recursion sending and returning values task scheduler with select() transferring control to another coroutine use of next(method use with network programming create_collation(methodof connection objects create_connection(functionsocket module create_decimal(methodof context objects create_function(methodof connection objects create_socket(methodof dispatcher objects create_string_buffer(functionctypes module create_system attributeof zipinfo objects create_unicode_buffer(functionctypes module cos(functionmath module create_version attributeof zipinfo objects cosh(functionmath module created attributeof record objects count(functionitertools module createkey(functionwinreg module count(method creating windows installer of array objects of lists of strings creating binary distribution creating source distribution creating custom string formatters how can we make this index more usefulemail us at indexes@samspublishing com lib fl ff |
18,499 | creating programs creating random numbers creating user-defined instances creation of instances steps involved creation of pyc and pyo files critical sectionslocking of critical(methodof logger objects current_thread(functionthreading module currentframe(functioninspect module curryingand partial function evaluation curses module cursor classdatabase api crypt module cursor(methodof connection objects crytographic hashing functions cwd(methodof ftp objects csv dataexample of reading cycle(functionitertools module csv files cyclesand garbage collection parsing type conversion of columns cyclic data structuresand _del_ (method csv module ctermid(functionos module ctime(functiontime module ctime(methodof date objects (owndebugger commandpdb module ctrl-ckeyboard interrupt daemon attribute ctypes module array types available datatypes casting datatypes creating byte strings creating objects from buffers example of finding library modules loading shared libraries memory copying passing pointers and references pointer types setting function prototypes shared data with multiprocessing structure types of process objects of thread objects daemonic process daemonic thread dangling comma and print statement and tuples print statement data attributeof dom text objects data encapsulation data structures and dictionaries lists and tuples named tuples cunifvariate(functionrandom module data(methodof treebuilder objects curdir variableos module database api curly bracesand dictionary database interface current timeobtaining _current_frames(functionsys module data-flow processingand coroutines and threads database resultsconverting into dictionaries current_process(functionmultiprocessing module lib fl ff |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.