id
int64
0
2.72k
content
stringlengths
5
4.1k
language
stringclasses
4 values
embedding
unknown
2,300
l last File stdin line 1 in module TypeError unhashable type set Contributed by Yurii Karabas in bpo 42345 macOS 11 0 Big Sur and Apple Silicon Mac support As of 3 9 1 Python now fully supports building and running on macOS 11 0 Big Sur and on Apple Silicon Macs based on the ARM64 architecture A new universal build variant universal2 is now available to natively support both ARM64 and Intel 64 in one set of executables Binaries can also now be built on current versions of macOS to be deployed on a range of older macOS versions tested to 10 9 while making some newer OS functions and options conditionally available based on the operating system version in use at runtime weaklinking Contributed by Ronald Oussoren and Lawrence D Anna in bpo 41100 Notable changes in Python 3 9 2 collections abc collections abc Callable generic now flattens type parameters similar to what typing Callable currently does This means that collections abc Callable int str str will have __args__ of int str str previously this was int str str To allow this change types GenericAlias can now be subclassed and a subclass will be returned when subscripting the collections abc Callable type Code which accesses the arguments via typing get_args or __args__ need to account for this change A DeprecationWarning may be emitted for invalid forms of parameterizing collections abc Callable which may have passed silently in Python 3 9 1 This DeprecationWarning will become a TypeError in Python 3 10 Contributed by Ken Jin in bpo 42195 urllib parse Earlier Python versions allowed using both and as query parameter separators in urllib parse parse_qs and urllib parse parse_qsl Due to security concerns and to conform with newer W3C recommendations this has been changed to allow only a single separator key with as the default This change also affects cgi parse and cgi parse_multipart as they use the affected functions internally For more details please see their respective documentation Contributed by Adam Goldschmidt Senthil Kumaran and Ken Jin in bpo 42967 Notable changes in Python 3 9 3 A security fix alters the ftplib FTP behavior to not trust the IPv4 address sent from the remote server when setting up a passive data channel We reuse the ftp server IP address instead For unusual code requiring the old behavior set a trust_server_pasv_ipv4_address attribute on your FTP instance to True See gh 87451 Notable changes in Python 3 9 5 urllib parse The presence of newline or tab characters in parts of a URL allows for some forms of attacks Following the WHATWG specification that updates RFC 3986 ASCII newline n r and tab t characters are stripped from the URL by the parser in urllib parse preventing such attacks The removal characters are controlled by a new module level variable urllib parse _UNSAFE_URL_BYTES_TO_REMOVE See gh 88048 Notable security feature in 3 9 14 Converting between int and str in bases other than 2 binary 4 8 octal 16 hexadecimal or 32 such as base 10 decimal now raises a ValueError if the number of digits in string form is above a limit to avoid potential denial of service attacks due to the algorithmic complexity This is a mitigation for CVE 2020 10735 This limit can be configured or disabled by environment variable command line flag or sys APIs See the integer string conversion length limitation documentation The default limit is 4300 digits in string form Notable changes in 3 9 17 tarfile The extraction methods in tarfile and shutil unpack_archive have a new a filter argument that allows limiting tar features than may be surprising or dangerous such as creating files outside the destination directory See Extraction filters for details In Python 3 12 use without the filter argument will show a DeprecationWarning In Python 3 14 the default will switch to data Contributed by Petr Viktorin in PEP 706
en
null
2,301
cgitb Traceback manager for CGI scripts Source code Lib cgitb py Deprecated since version 3 11 will be removed in version 3 13 The cgitb module is deprecated see PEP 594 for details The cgitb module provides a special exception handler for Python scripts Its name is a bit misleading It was originally designed to display extensive traceback information in HTML for CGI scripts It was later generalized to also display this information in plain text After this module is activated if an uncaught exception occurs a detailed formatted report will be displayed The report includes a traceback showing excerpts of the source code for each level as well as the values of the arguments and local variables to currently running functions to help you debug the problem Optionally you can save this information to a file instead of sending it to the browser To enable this feature simply add this to the top of your CGI script import cgitb cgitb enable The options to the enable function control whether the report is displayed in the browser and whether the report is logged to a file for later analysis cgitb enable display 1 logdir None context 5 format html This function causes the cgitb module to take over the interpreter s default handling for exceptions by setting the value of sys excepthook The optional argument display defaults to 1 and can be set to 0 to suppress sending the traceback to the browser If the argument logdir is present the traceback reports are written to files The value of logdir should be a directory where these files will be placed The optional argument context is the number of lines of context to display around the current line of source code in the traceback this defaults to 5 If the optional argument format is html the output is formatted as HTML Any other value forces plain text output The default value is html cgitb text info context 5 This function handles the exception described by info a 3 tuple containing the result of sys exc_info formatting its traceback as text and returning the result as a string The optional argument context is the number of lines of context to display around the current line of source code in the traceback this defaults to 5 cgitb html info context 5 This function handles the exception described by info a 3 tuple containing the result of sys exc_info formatting its traceback as HTML and returning the result as a string The optional argument context is the number of lines of context to display around the current line of source code in the traceback this defaults to 5 cgitb handler info None This function handles an exception using the default settings that is show a report in the browser but don t log to a file This can be used when you ve caught an exception and want to report it using cgitb The optional info argument should be a 3 tuple containing an exception type exception value and traceback object exactly like the tuple returned by sys exc_info If the info argument is not supplied the current exception is obtained from sys exc_info
en
null
2,302
tracemalloc Trace memory allocations New in version 3 4 Source code Lib tracemalloc py The tracemalloc module is a debug tool to trace memory blocks allocated by Python It provides the following information Traceback where an object was allocated Statistics on allocated memory blocks per filename and per line number total size number and average size of allocated memory blocks Compute the differences between two snapshots to detect memory leaks To trace most memory blocks allocated by Python the module should be started as early as possible by setting the PYTHONTRACEMALLOC environment variable to 1 or by using X tracemalloc command line option The tracemalloc start function can be called at runtime to start tracing Python memory allocations By default a trace of an allocated memory block only stores the most recent frame 1 frame To store 25 frames at startup set the PYTHONTRACEMALLOC environment variable to 25 or use the X tracemalloc 25 command line option Examples Display the top 10 Display the 10 files allocating the most memory import tracemalloc tracemalloc start run your application snapshot tracemalloc take_snapshot top_stats snapshot statistics lineno print Top 10 for stat in top_stats 10 print stat Example of output of the Python test suite Top 10 frozen importlib _bootstrap 716 size 4855 KiB count 39328 average 126 B frozen importlib _bootstrap 284 size 521 KiB count 3199 average 167 B usr lib python3 4 collections __init__ py 368 size 244 KiB count 2315 average 108 B usr lib python3 4 unittest case py 381 size 185 KiB count 779 average 243 B usr lib python3 4 unittest case py 402 size 154 KiB count 378 average 416 B usr lib python3 4 abc py 133 size 88 7 KiB count 347 average 262 B frozen importlib _bootstrap 1446 size 70 4 KiB count 911 average 79 B frozen importlib _bootstrap 1454 size 52 0 KiB count 25 average 2131 B string 5 size 49 7 KiB count 148 average 344 B usr lib python3 4 sysconfig py 411 size 48 0 KiB count 1 average 48 0 KiB We can see that Python loaded 4855 KiB data bytecode and constants from modules and that the collections module allocated 244 KiB to build namedtuple types See Snapshot statistics for more options Compute differences Take two snapshots and display the differences import tracemalloc tracemalloc start start your application snapshot1 tracemalloc take_snapshot call the function leaking memory snapshot2 tracemalloc take_snapshot top_stats snapshot2 compare_to snapshot1 lineno print Top 10 differences for stat in top_stats 10 print stat Example of output before after running some tests of the Python test suite Top 10 differences frozen importlib _bootstrap 716 size 8173 KiB 4428 KiB count 71332 39369 average 117 B usr lib python3 4 linecache py 127 size 940 KiB 940 KiB count 8106 8106 average 119 B usr lib python3 4 unittest case py 571 size 298 KiB 298 KiB count 589 589 average 519 B frozen importlib _bootstrap 284 size 1005 KiB 166 KiB count 7423 1526 average 139 B usr lib python3 4 mimetypes py 217 size 112 KiB 112 KiB count 1334 1334 average 86 B usr lib python3 4 http server py 848 size 96 0 KiB 96 0 KiB count 1 1 average 96 0 KiB usr lib python3 4 inspect py 1465 size 83 5 KiB 83 5 KiB count 109 109 average 784 B usr lib python3 4 unittest mock py 491 size 77 7 KiB 77 7 KiB count 143 143 average 557 B usr lib python3 4 urllib parse py 476 size 71 8 KiB 71 8 KiB count 969 969 average 76 B usr lib python3 4 contextlib py 38 size 67 2 KiB 67 2 KiB count 126 126 average 546 B We can see that Python has loaded 8173 KiB of module data bytecode and constants and that this is 4428 KiB more than had been loaded before the tests when the previous snapshot was taken Similarly the linecache module has cached 940 KiB of Python source code to format tracebacks all of it since the previous snapshot If the system has little free memory snapshots can be written on disk using the Snapshot dump method to analyze the snapshot offline Then use the Snapshot load method reload the snapshot Get the traceback of a memory block Code to display the traceback of the biggest memory block import tracemal
en
null
2,303
loc Store 25 frames tracemalloc start 25 run your application snapshot tracemalloc take_snapshot top_stats snapshot statistics traceback pick the biggest memory block stat top_stats 0 print s memory blocks 1f KiB stat count stat size 1024 for line in stat traceback format print line Example of output of the Python test suite traceback limited to 25 frames 903 memory blocks 870 1 KiB File frozen importlib _bootstrap line 716 File frozen importlib _bootstrap line 1036 File frozen importlib _bootstrap line 934 File frozen importlib _bootstrap line 1068 File frozen importlib _bootstrap line 619 File frozen importlib _bootstrap line 1581 File frozen importlib _bootstrap line 1614 File usr lib python3 4 doctest py line 101 import pdb File frozen importlib _bootstrap line 284 File frozen importlib _bootstrap line 938 File frozen importlib _bootstrap line 1068 File frozen importlib _bootstrap line 619 File frozen importlib _bootstrap line 1581 File frozen importlib _bootstrap line 1614 File usr lib python3 4 test support __init__ py line 1728 import doctest File usr lib python3 4 test test_pickletools py line 21 support run_doctest pickletools File usr lib python3 4 test regrtest py line 1276 test_runner File usr lib python3 4 test regrtest py line 976 display_failure not verbose File usr lib python3 4 test regrtest py line 761 match_tests ns match_tests File usr lib python3 4 test regrtest py line 1563 main File usr lib python3 4 test __main__ py line 3 regrtest main_in_temp_cwd File usr lib python3 4 runpy py line 73 exec code run_globals File usr lib python3 4 runpy py line 160 __main__ fname loader pkg_name We can see that the most memory was allocated in the importlib module to load data bytecode and constants from modules 870 1 KiB The traceback is where the importlib loaded data most recently on the import pdb line of the doctest module The traceback may change if a new module is loaded Pretty top Code to display the 10 lines allocating the most memory with a pretty output ignoring frozen importlib _bootstrap and unknown files import linecache import os import tracemalloc def display_top snapshot key_type lineno limit 10 snapshot snapshot filter_traces tracemalloc Filter False frozen importlib _bootstrap tracemalloc Filter False unknown top_stats snapshot statistics key_type print Top s lines limit for index stat in enumerate top_stats limit 1 frame stat traceback 0 print s s s 1f KiB index frame filename frame lineno stat size 1024 line linecache getline frame filename frame lineno strip if line print s line other top_stats limit if other size sum stat size for stat in other print s other 1f KiB len other size 1024 total sum stat size for stat in top_stats print Total allocated size 1f KiB total 1024 tracemalloc start run your application snapshot tracemalloc take_snapshot display_top snapshot Example of output of the Python test suite Top 10 lines 1 Lib base64 py 414 419 8 KiB _b85chars2 a b for a in _b85chars for b in _b85chars 2 Lib base64 py 306 419 8 KiB _a85chars2 a b for a in _a85chars for b in _a85chars 3 collections __init__ py 368 293 6 KiB exec class_definition namespace 4 Lib abc py 133 115 2 KiB cls super __new__ mcls name bases namespace 5 unittest case py 574 103 1 KiB testMethod 6 Lib linecache py 127 95 4 KiB lines fp readlines 7 urllib parse py 476 71 8 KiB for a in _hexdig for b in _hexdig 8 string 5 62 0 KiB 9 Lib _weakrefset py 37 60 0 KiB self data set 10 Lib base64 py 142 59 8 KiB _b32tab2 a b for a in _b32tab for b in _b32tab 6220 other 3602 8 KiB Total allocated size 5303 1 KiB See Snapshot statistics for more options Record the current and peak size of all traced memory blocks The following code computes two sums like 0 1 2 inefficiently by creating a list of those numbers This list consumes a lot of memory temporarily We can use get_traced_memory and reset_peak to observe the small memory usage after the sum is computed as well as the peak memory usage during the computations import tracemalloc tracemalloc start Example code compute a sum with a large temporary list large_sum sum list range 100
en
null
2,304
000 first_size first_peak tracemalloc get_traced_memory tracemalloc reset_peak Example code compute a sum with a small temporary list small_sum sum list range 1000 second_size second_peak tracemalloc get_traced_memory print f first_size first_peak print f second_size second_peak Output first_size 664 first_peak 3592984 second_size 804 second_peak 29704 Using reset_peak ensured we could accurately record the peak during the computation of small_sum even though it is much smaller than the overall peak size of memory blocks since the start call Without the call to reset_peak second_peak would still be the peak from the computation large_sum that is equal to first_peak In this case both peaks are much higher than the final memory usage and which suggests we could optimise by removing the unnecessary call to list and writing sum range API Functions tracemalloc clear_traces Clear traces of memory blocks allocated by Python See also stop tracemalloc get_object_traceback obj Get the traceback where the Python object obj was allocated Return a Traceback instance or None if the tracemalloc module is not tracing memory allocations or did not trace the allocation of the object See also gc get_referrers and sys getsizeof functions tracemalloc get_traceback_limit Get the maximum number of frames stored in the traceback of a trace The tracemalloc module must be tracing memory allocations to get the limit otherwise an exception is raised The limit is set by the start function tracemalloc get_traced_memory Get the current size and peak size of memory blocks traced by the tracemalloc module as a tuple current int peak int tracemalloc reset_peak Set the peak size of memory blocks traced by the tracemalloc module to the current size Do nothing if the tracemalloc module is not tracing memory allocations This function only modifies the recorded peak size and does not modify or clear any traces unlike clear_traces Snapshots taken with take_snapshot before a call to reset_peak can be meaningfully compared to snapshots taken after the call See also get_traced_memory New in version 3 9 tracemalloc get_tracemalloc_memory Get the memory usage in bytes of the tracemalloc module used to store traces of memory blocks Return an int tracemalloc is_tracing True if the tracemalloc module is tracing Python memory allocations False otherwise See also start and stop functions tracemalloc start nframe int 1 Start tracing Python memory allocations install hooks on Python memory allocators Collected tracebacks of traces will be limited to nframe frames By default a trace of a memory block only stores the most recent frame the limit is 1 nframe must be greater or equal to 1 You can still read the original number of total frames that composed the traceback by looking at the Traceback total_nframe attribute Storing more than 1 frame is only useful to compute statistics grouped by traceback or to compute cumulative statistics see the Snapshot compare_to and Snapshot statistics methods Storing more frames increases the memory and CPU overhead of the tracemalloc module Use the get_tracemalloc_memory function to measure how much memory is used by the tracemalloc module The PYTHONTRACEMALLOC environment variable PYTHONTRACEMALLOC NFRAME and the X tracemalloc NFRAME command line option can be used to start tracing at startup See also stop is_tracing and get_traceback_limit functions tracemalloc stop Stop tracing Python memory allocations uninstall hooks on Python memory allocators Also clears all previously collected traces of memory blocks allocated by Python Call take_snapshot function to take a snapshot of traces before clearing them See also start is_tracing and clear_traces functions tracemalloc take_snapshot Take a snapshot of traces of memory blocks allocated by Python Return a new Snapshot instance The snapshot does not include memory blocks allocated before the tracemalloc module started to trace memory allocations Tracebacks of traces are limited to get_traceback_limit frames Use the nframe parameter of the start function to store more frames The tracemalloc m
en
null
2,305
odule must be tracing memory allocations to take a snapshot see the start function See also the get_object_traceback function DomainFilter class tracemalloc DomainFilter inclusive bool domain int Filter traces of memory blocks by their address space domain New in version 3 6 inclusive If inclusive is True include match memory blocks allocated in the address space domain If inclusive is False exclude match memory blocks not allocated in the address space domain domain Address space of a memory block int Read only property Filter class tracemalloc Filter inclusive bool filename_pattern str lineno int None all_frames bool False domain int None Filter on traces of memory blocks See the fnmatch fnmatch function for the syntax of filename_pattern The pyc file extension is replaced with py Examples Filter True subprocess __file__ only includes traces of the subprocess module Filter False tracemalloc __file__ excludes traces of the tracemalloc module Filter False unknown excludes empty tracebacks Changed in version 3 5 The pyo file extension is no longer replaced with py Changed in version 3 6 Added the domain attribute domain Address space of a memory block int or None tracemalloc uses the domain 0 to trace memory allocations made by Python C extensions can use other domains to trace other resources inclusive If inclusive is True include only match memory blocks allocated in a file with a name matching filename_pattern at line number lineno If inclusive is False exclude ignore memory blocks allocated in a file with a name matching filename_pattern at line number lineno lineno Line number int of the filter If lineno is None the filter matches any line number filename_pattern Filename pattern of the filter str Read only property all_frames If all_frames is True all frames of the traceback are checked If all_frames is False only the most recent frame is checked This attribute has no effect if the traceback limit is 1 See the get_traceback_limit function and Snapshot traceback_limit attribute Frame class tracemalloc Frame Frame of a traceback The Traceback class is a sequence of Frame instances filename Filename str lineno Line number int Snapshot class tracemalloc Snapshot Snapshot of traces of memory blocks allocated by Python The take_snapshot function creates a snapshot instance compare_to old_snapshot Snapshot key_type str cumulative bool False Compute the differences with an old snapshot Get statistics as a sorted list of StatisticDiff instances grouped by key_type See the Snapshot statistics method for key_type and cumulative parameters The result is sorted from the biggest to the smallest by absolute value of StatisticDiff size_diff StatisticDiff size absolute value of StatisticDiff count_diff Statistic count and then by StatisticDiff traceback dump filename Write the snapshot into a file Use load to reload the snapshot filter_traces filters Create a new Snapshot instance with a filtered traces sequence filters is a list of DomainFilter and Filter instances If filters is an empty list return a new Snapshot instance with a copy of the traces All inclusive filters are applied at once a trace is ignored if no inclusive filters match it A trace is ignored if at least one exclusive filter matches it Changed in version 3 6 DomainFilter instances are now also accepted in filters classmethod load filename Load a snapshot from a file See also dump statistics key_type str cumulative bool False Get statistics as a sorted list of Statistic instances grouped by key_type key_type description filename filename lineno filename and line number traceback traceback If cumulative is True cumulate size and count of memory blocks of all frames of the traceback of a trace not only the most recent frame The cumulative mode can only be used with key_type equals to filename and lineno The result is sorted from the biggest to the smallest by Statistic size Statistic count and then by Statistic traceback traceback_limit Maximum number of frames stored in the traceback of traces result of the get_traceback_limit when the snapshot was taken traces Trace
en
null
2,306
s of all memory blocks allocated by Python sequence of Trace instances The sequence has an undefined order Use the Snapshot statistics method to get a sorted list of statistics Statistic class tracemalloc Statistic Statistic on memory allocations Snapshot statistics returns a list of Statistic instances See also the StatisticDiff class count Number of memory blocks int size Total size of memory blocks in bytes int traceback Traceback where the memory block was allocated Traceback instance StatisticDiff class tracemalloc StatisticDiff Statistic difference on memory allocations between an old and a new Snapshot instance Snapshot compare_to returns a list of StatisticDiff instances See also the Statistic class count Number of memory blocks in the new snapshot int 0 if the memory blocks have been released in the new snapshot count_diff Difference of number of memory blocks between the old and the new snapshots int 0 if the memory blocks have been allocated in the new snapshot size Total size of memory blocks in bytes in the new snapshot int 0 if the memory blocks have been released in the new snapshot size_diff Difference of total size of memory blocks in bytes between the old and the new snapshots int 0 if the memory blocks have been allocated in the new snapshot traceback Traceback where the memory blocks were allocated Traceback instance Trace class tracemalloc Trace Trace of a memory block The Snapshot traces attribute is a sequence of Trace instances Changed in version 3 6 Added the domain attribute domain Address space of a memory block int Read only property tracemalloc uses the domain 0 to trace memory allocations made by Python C extensions can use other domains to trace other resources size Size of the memory block in bytes int traceback Traceback where the memory block was allocated Traceback instance Traceback class tracemalloc Traceback Sequence of Frame instances sorted from the oldest frame to the most recent frame A traceback contains at least 1 frame If the tracemalloc module failed to get a frame the filename unknown at line number 0 is used When a snapshot is taken tracebacks of traces are limited to get_traceback_limit frames See the take_snapshot function The original number of frames of the traceback is stored in the Traceback total_nframe attribute That allows to know if a traceback has been truncated by the traceback limit The Trace traceback attribute is an instance of Traceback instance Changed in version 3 7 Frames are now sorted from the oldest to the most recent instead of most recent to oldest total_nframe Total number of frames that composed the traceback before truncation This attribute can be set to None if the information is not available Changed in version 3 9 The Traceback total_nframe attribute was added format limit None most_recent_first False Format the traceback as a list of lines Use the linecache module to retrieve lines from the source code If limit is set format the limit most recent frames if limit is positive Otherwise format the abs limit oldest frames If most_recent_first is True the order of the formatted frames is reversed returning the most recent frame first instead of last Similar to the traceback format_tb function except that format does not include newlines Example print Traceback most recent call first for line in traceback print line Output Traceback most recent call first File test py line 9 obj Object File test py line 12 tb tracemalloc get_object_traceback f
en
null
2,307
termios POSIX style tty control This module provides an interface to the POSIX calls for tty I O control For a complete description of these calls see termios 3 Unix manual page It is only available for those Unix versions that support POSIX termios style tty I O control configured during installation Availability Unix All functions in this module take a file descriptor fd as their first argument This can be an integer file descriptor such as returned by sys stdin fileno or a file object such as sys stdin itself This module also defines all the constants needed to work with the functions provided here these have the same name as their counterparts in C Please refer to your system documentation for more information on using these terminal control interfaces The module defines the following functions termios tcgetattr fd Return a list containing the tty attributes for file descriptor fd as follows iflag oflag cflag lflag ispeed ospeed cc where cc is a list of the tty special characters each a string of length 1 except the items with indices VMIN and VTIME which are integers when these fields are defined The interpretation of the flags and the speeds as well as the indexing in the cc array must be done using the symbolic constants defined in the termios module termios tcsetattr fd when attributes Set the tty attributes for file descriptor fd from the attributes which is a list like the one returned by tcgetattr The when argument determines when the attributes are changed termios TCSANOW Change attributes immediately termios TCSADRAIN Change attributes after transmitting all queued output termios TCSAFLUSH Change attributes after transmitting all queued output and discarding all queued input termios tcsendbreak fd duration Send a break on file descriptor fd A zero duration sends a break for 0 25 0 5 seconds a nonzero duration has a system dependent meaning termios tcdrain fd Wait until all output written to file descriptor fd has been transmitted termios tcflush fd queue Discard queued data on file descriptor fd The queue selector specifies which queue TCIFLUSH for the input queue TCOFLUSH for the output queue or TCIOFLUSH for both queues termios tcflow fd action Suspend or resume input or output on file descriptor fd The action argument can be TCOOFF to suspend output TCOON to restart output TCIOFF to suspend input or TCION to restart input termios tcgetwinsize fd Return a tuple ws_row ws_col containing the tty window size for file descriptor fd Requires termios TIOCGWINSZ or termios TIOCGSIZE New in version 3 11 termios tcsetwinsize fd winsize Set the tty window size for file descriptor fd from winsize which is a two item tuple ws_row ws_col like the one returned by tcgetwinsize Requires at least one of the pairs termios TIOCGWINSZ termios TIOCSWINSZ termios TIOCGSIZE termios TIOCSSIZE to be defined New in version 3 11 See also Module tty Convenience functions for common terminal control operations Example Here s a function that prompts for a password with echoing turned off Note the technique using a separate tcgetattr call and a try finally statement to ensure that the old tty attributes are restored exactly no matter what happens def getpass prompt Password import termios sys fd sys stdin fileno old termios tcgetattr fd new termios tcgetattr fd new 3 new 3 termios ECHO lflags try termios tcsetattr fd termios TCSADRAIN new passwd input prompt finally termios tcsetattr fd termios TCSADRAIN old return passwd
en
null
2,308
xml dom minidom Minimal DOM implementation Source code Lib xml dom minidom py xml dom minidom is a minimal implementation of the Document Object Model interface with an API similar to that in other languages It is intended to be simpler than the full DOM and also significantly smaller Users who are not already proficient with the DOM should consider using the xml etree ElementTree module for their XML processing instead Warning The xml dom minidom module is not secure against maliciously constructed data If you need to parse untrusted or unauthenticated data see XML vulnerabilities DOM applications typically start by parsing some XML into a DOM With xml dom minidom this is done through the parse functions from xml dom minidom import parse parseString dom1 parse c temp mydata xml parse an XML file by name datasource open c temp mydata xml dom2 parse datasource parse an open file dom3 parseString myxml Some data empty some more data myxml The parse function can take either a filename or an open file object xml dom minidom parse filename_or_file parser None bufsize None Return a Document from the given input filename_or_file may be either a file name or a file like object parser if given must be a SAX2 parser object This function will change the document handler of the parser and activate namespace support other parser configuration like setting an entity resolver must have been done in advance If you have XML in a string you can use the parseString function instead xml dom minidom parseString string parser None Return a Document that represents the string This method creates an io StringIO object for the string and passes that on to parse Both functions return a Document object representing the content of the document What the parse and parseString functions do is connect an XML parser with a DOM builder that can accept parse events from any SAX parser and convert them into a DOM tree The name of the functions are perhaps misleading but are easy to grasp when learning the interfaces The parsing of the document will be completed before these functions return it s simply that these functions do not provide a parser implementation themselves You can also create a Document by calling a method on a DOM Implementation object You can get this object either by calling the getDOMImplementation function in the xml dom package or the xml dom minidom module Once you have a Document you can add child nodes to it to populate the DOM from xml dom minidom import getDOMImplementation impl getDOMImplementation newdoc impl createDocument None some_tag None top_element newdoc documentElement text newdoc createTextNode Some textual content top_element appendChild text Once you have a DOM document object you can access the parts of your XML document through its properties and methods These properties are defined in the DOM specification The main property of the document object is the documentElement property It gives you the main element in the XML document the one that holds all others Here is an example program dom3 parseString myxml Some data myxml assert dom3 documentElement tagName myxml When you are finished with a DOM tree you may optionally call the unlink method to encourage early cleanup of the now unneeded objects unlink is an xml dom minidom specific extension to the DOM API that renders the node and its descendants essentially useless Otherwise Python s garbage collector will eventually take care of the objects in the tree See also Document Object Model DOM Level 1 Specification The W3C recommendation for the DOM supported by xml dom minidom DOM Objects The definition of the DOM API for Python is given as part of the xml dom module documentation This section lists the differences between the API and xml dom minidom Node unlink Break internal references within the DOM so that it will be garbage collected on versions of Python without cyclic GC Even when cyclic GC is available using this can make large amounts of memory available sooner so calling this on DOM objects as soon as they are no longer needed is good practice This only nee
en
null
2,309
ds to be called on the Document object but may be called on child nodes to discard children of that node You can avoid calling this method explicitly by using the with statement The following code will automatically unlink dom when the with block is exited with xml dom minidom parse datasource as dom Work with dom Node writexml writer indent addindent newl encoding None standalone None Write XML to the writer object The writer receives texts but not bytes as input it should have a write method which matches that of the file object interface The indent parameter is the indentation of the current node The addindent parameter is the incremental indentation to use for subnodes of the current one The newl parameter specifies the string to use to terminate newlines For the Document node an additional keyword argument encoding can be used to specify the encoding field of the XML header Similarly explicitly stating the standalone argument causes the standalone document declarations to be added to the prologue of the XML document If the value is set to True standalone yes is added otherwise it is set to no Not stating the argument will omit the declaration from the document Changed in version 3 8 The writexml method now preserves the attribute order specified by the user Changed in version 3 9 The standalone parameter was added Node toxml encoding None standalone None Return a string or byte string containing the XML represented by the DOM node With an explicit encoding 1 argument the result is a byte string in the specified encoding With no encoding argument the result is a Unicode string and the XML declaration in the resulting string does not specify an encoding Encoding this string in an encoding other than UTF 8 is likely incorrect since UTF 8 is the default encoding of XML The standalone argument behaves exactly as in writexml Changed in version 3 8 The toxml method now preserves the attribute order specified by the user Changed in version 3 9 The standalone parameter was added Node toprettyxml indent t newl n encoding None standalone None Return a pretty printed version of the document indent specifies the indentation string and defaults to a tabulator newl specifies the string emitted at the end of each line and defaults to n The encoding argument behaves like the corresponding argument of toxml The standalone argument behaves exactly as in writexml Changed in version 3 8 The toprettyxml method now preserves the attribute order specified by the user Changed in version 3 9 The standalone parameter was added DOM Example This example program is a fairly realistic example of a simple program In this particular case we do not take much advantage of the flexibility of the DOM import xml dom minidom document slideshow title Demo slideshow title slide title Slide title title point This is a demo point point Of a program for processing slides point slide slide title Another demo slide title point It is important point point To have more than point point one slide point slide slideshow dom xml dom minidom parseString document def getText nodelist rc for node in nodelist if node nodeType node TEXT_NODE rc append node data return join rc def handleSlideshow slideshow print html handleSlideshowTitle slideshow getElementsByTagName title 0 slides slideshow getElementsByTagName slide handleToc slides handleSlides slides print html def handleSlides slides for slide in slides handleSlide slide def handleSlide slide handleSlideTitle slide getElementsByTagName title 0 handlePoints slide getElementsByTagName point def handleSlideshowTitle title print f title getText title childNodes title def handleSlideTitle title print f h2 getText title childNodes h2 def handlePoints points print ul for point in points handlePoint point print ul def handlePoint point print f li getText point childNodes li def handleToc slides for slide in slides title slide getElementsByTagName title 0 print f p getText title childNodes p handleSlideshow dom minidom and the DOM standard The xml dom minidom module is essentially a DOM 1 0 compatible DOM with some DOM 2 feat
en
null
2,310
ures primarily namespace features Usage of the DOM interface in Python is straight forward The following mapping rules apply Interfaces are accessed through instance objects Applications should not instantiate the classes themselves they should use the creator functions available on the Document object Derived interfaces support all operations and attributes from the base interfaces plus any new operations Operations are used as methods Since the DOM uses only in parameters the arguments are passed in normal order from left to right There are no optional arguments void operations return None IDL attributes map to instance attributes For compatibility with the OMG IDL language mapping for Python an attribute foo can also be accessed through accessor methods _get_foo and _set_foo readonly attributes must not be changed this is not enforced at runtime The types short int unsigned int unsigned long long and boolean all map to Python integer objects The type DOMString maps to Python strings xml dom minidom supports either bytes or strings but will normally produce strings Values of type DOMString may also be None where allowed to have the IDL null value by the DOM specification from the W3C const declarations map to variables in their respective scope e g xml dom minidom Node PROCESSING_INSTRUCTION_NODE they must not be changed DOMException is currently not supported in xml dom minidom Instead xml dom minidom uses standard Python exceptions such as TypeError and AttributeError NodeList objects are implemented using Python s built in list type These objects provide the interface defined in the DOM specification but with earlier versions of Python they do not support the official API They are however much more Pythonic than the interface defined in the W3C recommendations The following interfaces have no implementation in xml dom minidom DOMTimeStamp EntityReference Most of these reflect information in the XML document that is not of general utility to most DOM users Footnotes 1 The encoding name included in the XML output should conform to the appropriate standards For example UTF 8 is valid but UTF8 is not valid in an XML document s declaration even though Python accepts it as an encoding name See https www w3 org TR 2006 REC xml11 20060816 NT EncodingDecl and https www iana org assignments character sets character sets xhtml
en
null
2,311
Internationalization The modules described in this chapter help you write software that is independent of language and locale by providing mechanisms for selecting a language to be used in program messages or by tailoring output to match local conventions The list of modules described in this chapter is gettext Multilingual internationalization services GNU gettext API Class based API The NullTranslations class The GNUTranslations class Solaris message catalog support The Catalog constructor Internationalizing your programs and modules Localizing your module Localizing your application Changing languages on the fly Deferred translations Acknowledgements locale Internationalization services Background details hints tips and caveats For extension writers and programs that embed Python Access to message catalogs
en
null
2,312
What s New In Python 3 2 Author Raymond Hettinger This article explains the new features in Python 3 2 as compared to 3 1 Python 3 2 was released on February 20 2011 It focuses on a few highlights and gives a few examples For full details see the Misc NEWS file See also PEP 392 Python 3 2 Release Schedule PEP 384 Defining a Stable ABI In the past extension modules built for one Python version were often not usable with other Python versions Particularly on Windows every feature release of Python required rebuilding all extension modules that one wanted to use This requirement was the result of the free access to Python interpreter internals that extension modules could use With Python 3 2 an alternative approach becomes available extension modules which restrict themselves to a limited API by defining Py_LIMITED_API cannot use many of the internals but are constrained to a set of API functions that are promised to be stable for several releases As a consequence extension modules built for 3 2 in that mode will also work with 3 3 3 4 and so on Extension modules that make use of details of memory structures can still be built but will need to be recompiled for every feature release See also PEP 384 Defining a Stable ABI PEP written by Martin von Löwis PEP 389 Argparse Command Line Parsing Module A new module for command line parsing argparse was introduced to overcome the limitations of optparse which did not provide support for positional arguments not just options subcommands required options and other common patterns of specifying and validating options This module has already had widespread success in the community as a third party module Being more fully featured than its predecessor the argparse module is now the preferred module for command line processing The older module is still being kept available because of the substantial amount of legacy code that depends on it Here s an annotated example parser showing features like limiting results to a set of choices specifying a metavar in the help screen validating that one or more positional arguments is present and making a required option import argparse parser argparse ArgumentParser description Manage servers main description for help epilog Tested on Solaris and Linux displayed after help parser add_argument action argument name choices deploy start stop three allowed values help action on each target help msg parser add_argument targets metavar HOSTNAME var name used in help msg nargs require one or more targets help url for target machines help msg explanation parser add_argument u user u or user option required True make it a required argument help login as user Example of calling the parser on a command string cmd deploy sneezy example com sleepy example com u skycaptain result parser parse_args cmd split result action deploy result targets sneezy example com sleepy example com result user skycaptain Example of the parser s automatically generated help parser parse_args h split usage manage_cloud py h u USER deploy start stop HOSTNAME HOSTNAME Manage servers positional arguments deploy start stop action on each target HOSTNAME url for target machines optional arguments h help show this help message and exit u USER user USER login as user Tested on Solaris and Linux An especially nice argparse feature is the ability to define subparsers each with their own argument patterns and help displays import argparse parser argparse ArgumentParser prog HELM subparsers parser add_subparsers parser_l subparsers add_parser launch help Launch Control first subgroup parser_l add_argument m missiles action store_true parser_l add_argument t torpedos action store_true parser_m subparsers add_parser move help Move Vessel second subgroup aliases steer turn equivalent names parser_m add_argument c course type int required True parser_m add_argument s speed type int default 0 helm py help top level help launch and move helm py launch help help for launch options helm py launch missiles set missiles True and torpedos False helm py steer course 180 speed 5 set movement parameters See
en
null
2,313
also PEP 389 New Command Line Parsing Module PEP written by Steven Bethard Upgrading optparse code for details on the differences from optparse PEP 391 Dictionary Based Configuration for Logging The logging module provided two kinds of configuration one style with function calls for each option or another style driven by an external file saved in a configparser format Those options did not provide the flexibility to create configurations from JSON or YAML files nor did they support incremental configuration which is needed for specifying logger options from a command line To support a more flexible style the module now offers logging config dictConfig for specifying logging configuration with plain Python dictionaries The configuration options include formatters handlers filters and loggers Here s a working example of a configuration dictionary version 1 formatters brief format levelname 8s name 15s message s full format asctime s name 15s levelname 8s message s handlers console class logging StreamHandler formatter brief level INFO stream ext sys stdout console_priority class logging StreamHandler formatter full level ERROR stream ext sys stderr root level DEBUG handlers console console_priority If that dictionary is stored in a file called conf json it can be loaded and called with code like this import json logging config with open conf json as f conf json load f logging config dictConfig conf logging info Transaction completed normally INFO root Transaction completed normally logging critical Abnormal termination 2011 02 17 11 14 36 694 root CRITICAL Abnormal termination See also PEP 391 Dictionary Based Configuration for Logging PEP written by Vinay Sajip PEP 3148 The concurrent futures module Code for creating and managing concurrency is being collected in a new top level namespace concurrent Its first member is a futures package which provides a uniform high level interface for managing threads and processes The design for concurrent futures was inspired by the java util concurrent package In that model a running call and its result are represented by a Future object that abstracts features common to threads processes and remote procedure calls That object supports status checks running or done timeouts cancellations adding callbacks and access to results or exceptions The primary offering of the new module is a pair of executor classes for launching and managing calls The goal of the executors is to make it easier to use existing tools for making parallel calls They save the effort needed to setup a pool of resources launch the calls create a results queue add time out handling and limit the total number of threads processes or remote procedure calls Ideally each application should share a single executor across multiple components so that process and thread limits can be centrally managed This solves the design challenge that arises when each component has its own competing strategy for resource management Both classes share a common interface with three methods submit for scheduling a callable and returning a Future object map for scheduling many asynchronous calls at a time and shutdown for freeing resources The class is a context manager and can be used in a with statement to assure that resources are automatically released when currently pending futures are done executing A simple of example of ThreadPoolExecutor is a launch of four parallel threads for copying files import concurrent futures shutil with concurrent futures ThreadPoolExecutor max_workers 4 as e e submit shutil copy src1 txt dest1 txt e submit shutil copy src2 txt dest2 txt e submit shutil copy src3 txt dest3 txt e submit shutil copy src3 txt dest4 txt See also PEP 3148 Futures Execute Computations Asynchronously PEP written by Brian Quinlan Code for Threaded Parallel URL reads an example using threads to fetch multiple web pages in parallel Code for computing prime numbers in parallel an example demonstrating ProcessPoolExecutor PEP 3147 PYC Repository Directories Python s scheme for caching bytecode in pyc files did not work well in environ
en
null
2,314
ments with multiple Python interpreters If one interpreter encountered a cached file created by another interpreter it would recompile the source and overwrite the cached file thus losing the benefits of caching The issue of pyc fights has become more pronounced as it has become commonplace for Linux distributions to ship with multiple versions of Python These conflicts also arise with CPython alternatives such as Unladen Swallow To solve this problem Python s import machinery has been extended to use distinct filenames for each interpreter Instead of Python 3 2 and Python 3 3 and Unladen Swallow each competing for a file called mymodule pyc they will now look for mymodule cpython 32 pyc mymodule cpython 33 pyc and mymodule unladen10 pyc And to prevent all of these new files from cluttering source directories the pyc files are now collected in a __pycache__ directory stored under the package directory Aside from the filenames and target directories the new scheme has a few aspects that are visible to the programmer Imported modules now have a __cached__ attribute which stores the name of the actual file that was imported import collections collections __cached__ c py32 lib __pycache__ collections cpython 32 pyc The tag that is unique to each interpreter is accessible from the imp module import imp imp get_tag cpython 32 Scripts that try to deduce source filename from the imported file now need to be smarter It is no longer sufficient to simply strip the c from a pyc filename Instead use the new functions in the imp module imp source_from_cache c py32 lib __pycache__ collections cpython 32 pyc c py32 lib collections py imp cache_from_source c py32 lib collections py c py32 lib __pycache__ collections cpython 32 pyc The py_compile and compileall modules have been updated to reflect the new naming convention and target directory The command line invocation of compileall has new options i for specifying a list of files and directories to compile and b which causes bytecode files to be written to their legacy location rather than __pycache__ The importlib abc module has been updated with new abstract base classes for loading bytecode files The obsolete ABCs PyLoader and PyPycLoader have been deprecated instructions on how to stay Python 3 1 compatible are included with the documentation See also PEP 3147 PYC Repository Directories PEP written by Barry Warsaw PEP 3149 ABI Version Tagged so Files The PYC repository directory allows multiple bytecode cache files to be co located This PEP implements a similar mechanism for shared object files by giving them a common directory and distinct names for each version The common directory is pyshared and the file names are made distinct by identifying the Python implementation such as CPython PyPy Jython etc the major and minor version numbers and optional build flags such as d for debug m for pymalloc u for wide unicode For an arbitrary package foo you may see these files when the distribution package is installed usr share pyshared foo cpython 32m so usr share pyshared foo cpython 33md so In Python itself the tags are accessible from functions in the sysconfig module import sysconfig sysconfig get_config_var SOABI find the version tag cpython 32mu sysconfig get_config_var EXT_SUFFIX find the full filename extension cpython 32mu so See also PEP 3149 ABI Version Tagged so Files PEP written by Barry Warsaw PEP 3333 Python Web Server Gateway Interface v1 0 1 This informational PEP clarifies how bytes text issues are to be handled by the WSGI protocol The challenge is that string handling in Python 3 is most conveniently handled with the str type even though the HTTP protocol is itself bytes oriented The PEP differentiates so called native strings that are used for request response headers and metadata versus byte strings which are used for the bodies of requests and responses The native strings are always of type str but are restricted to code points between U 0000 through U 00FF which are translatable to bytes using Latin 1 encoding These strings are used for the keys and values in the e
en
null
2,315
nvironment dictionary and for response headers and statuses in the start_response function They must follow RFC 2616 with respect to encoding That is they must either be ISO 8859 1 characters or use RFC 2047 MIME encoding For developers porting WSGI applications from Python 2 here are the salient points If the app already used strings for headers in Python 2 no change is needed If instead the app encoded output headers or decoded input headers then the headers will need to be re encoded to Latin 1 For example an output header encoded in utf 8 was using h encode utf 8 now needs to convert from bytes to native strings using h encode utf 8 decode latin 1 Values yielded by an application or sent using the write method must be byte strings The start_response function and environ must use native strings The two cannot be mixed For server implementers writing CGI to WSGI pathways or other CGI style protocols the users must to be able access the environment using native strings even though the underlying platform may have a different convention To bridge this gap the wsgiref module has a new function wsgiref handlers read_environ for transcoding CGI variables from os environ into native strings and returning a new dictionary See also PEP 3333 Python Web Server Gateway Interface v1 0 1 PEP written by Phillip Eby Other Language Changes Some smaller changes made to the core Python language are String formatting for format and str format gained new capabilities for the format character Previously for integers in binary octal or hexadecimal it caused the output to be prefixed with 0b 0o or 0x respectively Now it can also handle floats complex and Decimal causing the output to always have a decimal point even when no digits follow it format 20 o 0o24 format 12 34 5 0f 12 Suggested by Mark Dickinson and implemented by Eric Smith in bpo 7094 There is also a new str format_map method that extends the capabilities of the existing str format method by accepting arbitrary mapping objects This new method makes it possible to use string formatting with any of Python s many dictionary like objects such as defaultdict Shelf ConfigParser or dbm It is also useful with custom dict subclasses that normalize keys before look up or that supply a __missing__ method for unknown keys import shelve d shelve open tmp shl The project_name status is status as of date format_map d The testing project status is green as of February 15 2011 class LowerCasedDict dict def __getitem__ self key return dict __getitem__ self key lower lcd LowerCasedDict part widgets quantity 10 There are QUANTITY Part in stock format_map lcd There are 10 widgets in stock class PlaceholderDict dict def __missing__ self key return format key Hello name welcome to location format_map PlaceholderDict Hello name welcome to location Suggested by Raymond Hettinger and implemented by Eric Smith in bpo 6081 The interpreter can now be started with a quiet option q to prevent the copyright and version information from being displayed in the interactive mode The option can be introspected using the sys flags attribute python q sys flags sys flags debug 0 division_warning 0 inspect 0 interactive 0 optimize 0 dont_write_bytecode 0 no_user_site 0 no_site 0 ignore_environment 0 verbose 0 bytes_warning 0 quiet 1 Contributed by Marcin Wojdyr in bpo 1772833 The hasattr function works by calling getattr and detecting whether an exception is raised This technique allows it to detect methods created dynamically by __getattr__ or __getattribute__ which would otherwise be absent from the class dictionary Formerly hasattr would catch any exception possibly masking genuine errors Now hasattr has been tightened to only catch AttributeError and let other exceptions pass through class A property def f self return 1 0 a A hasattr a f Traceback most recent call last ZeroDivisionError integer division or modulo by zero Discovered by Yury Selivanov and fixed by Benjamin Peterson bpo 9666 The str of a float or complex number is now the same as its repr Previously the str form was shorter but that just caused confusi
en
null
2,316
on and is no longer needed now that the shortest possible repr is displayed by default import math repr math pi 3 141592653589793 str math pi 3 141592653589793 Proposed and implemented by Mark Dickinson bpo 9337 memoryview objects now have a release method and they also now support the context management protocol This allows timely release of any resources that were acquired when requesting a buffer from the original object with memoryview b abcdefgh as v print v tolist 97 98 99 100 101 102 103 104 Added by Antoine Pitrou bpo 9757 Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block def outer x def inner return x inner del x This is now allowed Remember that the target of an except clause is cleared so this code which used to work with Python 2 6 raised a SyntaxError with Python 3 1 and now works again def f def print_error print e try something except Exception as e print_error implicit del e here See bpo 4617 Struct sequence types are now subclasses of tuple This means that C structures like those returned by os stat time gmtime and sys version_info now work like a named tuple and now work with functions and methods that expect a tuple as an argument This is a big step forward in making the C structures as flexible as their pure Python counterparts import sys isinstance sys version_info tuple True Version d d d s d sys version_info Version 3 2 0 final 0 Suggested by Arfrever Frehtes Taifersar Arahesis and implemented by Benjamin Peterson in bpo 8413 Warnings are now easier to control using the PYTHONWARNINGS environment variable as an alternative to using W at the command line export PYTHONWARNINGS ignore RuntimeWarning once UnicodeWarning Suggested by Barry Warsaw and implemented by Philip Jenvey in bpo 7301 A new warning category ResourceWarning has been added It is emitted when potential issues with resource consumption or cleanup are detected It is silenced by default in normal release builds but can be enabled through the means provided by the warnings module or on the command line A ResourceWarning is issued at interpreter shutdown if the gc garbage list isn t empty and if gc DEBUG_UNCOLLECTABLE is set all uncollectable objects are printed This is meant to make the programmer aware that their code contains object finalization issues A ResourceWarning is also issued when a file object is destroyed without having been explicitly closed While the deallocator for such object ensures it closes the underlying operating system resource usually a file descriptor the delay in deallocating the object could produce various issues especially under Windows Here is an example of enabling the warning from the command line python q Wdefault f open foo wb del f __main__ 1 ResourceWarning unclosed file _io BufferedWriter name foo Added by Antoine Pitrou and Georg Brandl in bpo 10093 and bpo 477863 range objects now support index and count methods This is part of an effort to make more objects fully implement the collections Sequence abstract base class As a result the language will have a more uniform API In addition range objects now support slicing and negative indices even with values larger than sys maxsize This makes range more interoperable with lists range 0 100 2 count 10 1 range 0 100 2 index 10 5 range 0 100 2 5 10 range 0 100 2 0 5 range 0 10 2 Contributed by Daniel Stutzbach in bpo 9213 by Alexander Belopolsky in bpo 2690 and by Nick Coghlan in bpo 10889 The callable builtin function from Py2 x was resurrected It provides a concise readable alternative to using an abstract base class in an expression like isinstance x collections Callable callable max True callable 20 False See bpo 10518 Python s import mechanism can now load modules installed in directories with non ASCII characters in the path name This solved an aggravating problem with home directories for users with non ASCII characters in their usernames Required extensive work by Victor Stinner in bpo 9425 New Improved and Deprecated Modules Python s standard library has undergone significant maint
en
null
2,317
enance efforts and quality improvements The biggest news for Python 3 2 is that the email package mailbox module and nntplib modules now work correctly with the bytes text model in Python 3 For the first time there is correct handling of messages with mixed encodings Throughout the standard library there has been more careful attention to encodings and text versus bytes issues In particular interactions with the operating system are now better able to exchange non ASCII data using the Windows MBCS encoding locale aware encodings or UTF 8 Another significant win is the addition of substantially better support for SSL connections and security certificates In addition more classes now implement a context manager to support convenient and reliable resource clean up using a with statement email The usability of the email package in Python 3 has been mostly fixed by the extensive efforts of R David Murray The problem was that emails are typically read and stored in the form of bytes rather than str text and they may contain multiple encodings within a single email So the email package had to be extended to parse and generate email messages in bytes format New functions message_from_bytes and message_from_binary_file and new classes BytesFeedParser and BytesParser allow binary message data to be parsed into model objects Given bytes input to the model get_payload will by default decode a message body that has a Content Transfer Encoding of 8bit using the charset specified in the MIME headers and return the resulting string Given bytes input to the model Generator will convert message bodies that have a Content Transfer Encoding of 8bit to instead have a 7bit Content Transfer Encoding Headers with unencoded non ASCII bytes are deemed to be RFC 2047 encoded using the unknown 8bit character set A new class BytesGenerator produces bytes as output preserving any unchanged non ASCII data that was present in the input used to build the model including message bodies with a Content Transfer Encoding of 8bit The smtplib SMTP class now accepts a byte string for the msg argument to the sendmail method and a new method send_message accepts a Message object and can optionally obtain the from_addr and to_addrs addresses directly from the object Proposed and implemented by R David Murray bpo 4661 and bpo 10321 elementtree The xml etree ElementTree package and its xml etree cElementTree counterpart have been updated to version 1 3 Several new and useful functions and methods have been added xml etree ElementTree fromstringlist which builds an XML document from a sequence of fragments xml etree ElementTree register_namespace for registering a global namespace prefix xml etree ElementTree tostringlist for string representation including all sublists xml etree ElementTree Element extend for appending a sequence of zero or more elements xml etree ElementTree Element iterfind searches an element and subelements xml etree ElementTree Element itertext creates a text iterator over an element and its subelements xml etree ElementTree TreeBuilder end closes the current element xml etree ElementTree TreeBuilder doctype handles a doctype declaration Two methods have been deprecated xml etree ElementTree getchildren use list elem instead xml etree ElementTree getiterator use Element iter instead For details of the update see Introducing ElementTree on Fredrik Lundh s website Contributed by Florent Xicluna and Fredrik Lundh bpo 6472 functools The functools module includes a new decorator for caching function calls functools lru_cache can save repeated queries to an external resource whenever the results are expected to be the same For example adding a caching decorator to a database query function can save database accesses for popular searches import functools functools lru_cache maxsize 300 def get_phone_number name c conn cursor c execute SELECT phonenumber FROM phonelist WHERE name name return c fetchone 0 for name in user_requests get_phone_number name cached lookup To help with choosing an effective cache size the wrapped function is instrumented for
en
null
2,318
tracking cache statistics get_phone_number cache_info CacheInfo hits 4805 misses 980 maxsize 300 currsize 300 If the phonelist table gets updated the outdated contents of the cache can be cleared with get_phone_number cache_clear Contributed by Raymond Hettinger and incorporating design ideas from Jim Baker Miki Tebeka and Nick Coghlan see recipe 498245 recipe 577479 bpo 10586 and bpo 10593 The functools wraps decorator now adds a __wrapped__ attribute pointing to the original callable function This allows wrapped functions to be introspected It also copies __annotations__ if defined And now it also gracefully skips over missing attributes such as __doc__ which might not be defined for the wrapped callable In the above example the cache can be removed by recovering the original function get_phone_number get_phone_number __wrapped__ uncached function By Nick Coghlan and Terrence Cole bpo 9567 bpo 3445 and bpo 8814 To help write classes with rich comparison methods a new decorator functools total_ordering will use existing equality and inequality methods to fill in the remaining methods For example supplying __eq__ and __lt__ will enable total_ordering to fill in __le__ __gt__ and __ge__ total_ordering class Student def __eq__ self other return self lastname lower self firstname lower other lastname lower other firstname lower def __lt__ self other return self lastname lower self firstname lower other lastname lower other firstname lower With the total_ordering decorator the remaining comparison methods are filled in automatically Contributed by Raymond Hettinger To aid in porting programs from Python 2 the functools cmp_to_key function converts an old style comparison function to modern key function locale aware sort order sorted iterable key cmp_to_key locale strcoll For sorting examples and a brief sorting tutorial see the Sorting HowTo tutorial Contributed by Raymond Hettinger itertools The itertools module has a new accumulate function modeled on APL s scan operator and Numpy s accumulate function from itertools import accumulate list accumulate 8 2 50 8 10 60 prob_dist 0 1 0 4 0 2 0 3 list accumulate prob_dist cumulative probability distribution 0 1 0 5 0 7 1 0 For an example using accumulate see the examples for the random module Contributed by Raymond Hettinger and incorporating design suggestions from Mark Dickinson collections The collections Counter class now has two forms of in place subtraction the existing operator for saturating subtraction and the new subtract method for regular subtraction The former is suitable for multisets which only have positive counts and the latter is more suitable for use cases that allow negative counts from collections import Counter tally Counter dogs 5 cats 3 tally Counter dogs 2 cats 8 saturating subtraction tally Counter dogs 3 tally Counter dogs 5 cats 3 tally subtract dogs 2 cats 8 regular subtraction tally Counter dogs 3 cats 5 Contributed by Raymond Hettinger The collections OrderedDict class has a new method move_to_end which takes an existing key and moves it to either the first or last position in the ordered sequence The default is to move an item to the last position This is equivalent of renewing an entry with od k od pop k A fast move to end operation is useful for resequencing entries For example an ordered dictionary can be used to track order of access by aging entries from the oldest to the most recently accessed from collections import OrderedDict d OrderedDict fromkeys a b X d e list d a b X d e d move_to_end X list d a b d e X Contributed by Raymond Hettinger The collections deque class grew two new methods count and reverse that make them more substitutable for list objects from collections import deque d deque simsalabim d count s 2 d reverse d deque m i b a l a s m i s Contributed by Raymond Hettinger threading The threading module has a new Barrier synchronization class for making multiple threads wait until all of them have reached a common barrier point Barriers are useful for making sure that a task with multiple preconditions does not run until all o
en
null
2,319
f the predecessor tasks are complete Barriers can work with an arbitrary number of threads This is a generalization of a Rendezvous which is defined for only two threads Implemented as a two phase cyclic barrier Barrier objects are suitable for use in loops The separate filling and draining phases assure that all threads get released drained before any one of them can loop back and re enter the barrier The barrier fully resets after each cycle Example of using barriers from threading import Barrier Thread def get_votes site ballots conduct_election site all_polls_closed wait do not count until all polls are closed totals summarize ballots publish site totals all_polls_closed Barrier len sites for site in sites Thread target get_votes args site start In this example the barrier enforces a rule that votes cannot be counted at any polling site until all polls are closed Notice how a solution with a barrier is similar to one with threading Thread join but the threads stay alive and continue to do work summarizing ballots after the barrier point is crossed If any of the predecessor tasks can hang or be delayed a barrier can be created with an optional timeout parameter Then if the timeout period elapses before all the predecessor tasks reach the barrier point all waiting threads are released and a BrokenBarrierError exception is raised def get_votes site ballots conduct_election site try all_polls_closed wait timeout midnight time now except BrokenBarrierError lockbox seal_ballots ballots queue put lockbox else totals summarize ballots publish site totals In this example the barrier enforces a more robust rule If some election sites do not finish before midnight the barrier times out and the ballots are sealed and deposited in a queue for later handling See Barrier Synchronization Patterns for more examples of how barriers can be used in parallel computing Also there is a simple but thorough explanation of barriers in The Little Book of Semaphores section 3 6 Contributed by Kristján Valur Jónsson with an API review by Jeffrey Yasskin in bpo 8777 datetime and time The datetime module has a new type timezone that implements the tzinfo interface by returning a fixed UTC offset and timezone name This makes it easier to create timezone aware datetime objects from datetime import datetime timezone datetime now timezone utc datetime datetime 2010 12 8 21 4 2 923754 tzinfo datetime timezone utc datetime strptime 01 01 2000 12 00 0000 m d Y H M z datetime datetime 2000 1 1 12 0 tzinfo datetime timezone utc Also timedelta objects can now be multiplied by float and divided by float and int objects And timedelta objects can now divide one another The datetime date strftime method is no longer restricted to years after 1900 The new supported year range is from 1000 to 9999 inclusive Whenever a two digit year is used in a time tuple the interpretation has been governed by time accept2dyear The default is True which means that for a two digit year the century is guessed according to the POSIX rules governing the y strptime format Starting with Py3 2 use of the century guessing heuristic will emit a DeprecationWarning Instead it is recommended that time accept2dyear be set to False so that large date ranges can be used without guesswork import time warnings warnings resetwarnings remove the default warning filters time accept2dyear True guess whether 11 means 11 or 2011 time asctime 11 1 1 12 34 56 4 1 0 Warning from warnings module DeprecationWarning Century info guessed for a 2 digit year Fri Jan 1 12 34 56 2011 time accept2dyear False use the full range of allowable dates time asctime 11 1 1 12 34 56 4 1 0 Fri Jan 1 12 34 56 11 Several functions now have significantly expanded date ranges When time accept2dyear is false the time asctime function will accept any year that fits in a C int while the time mktime and time strftime functions will accept the full range supported by the corresponding operating system functions Contributed by Alexander Belopolsky and Victor Stinner in bpo 1289118 bpo 5094 bpo 6641 bpo 2706 bpo 1777412 bpo 8013 and
en
null
2,320
bpo 10827 math The math module has been updated with six new functions inspired by the C99 standard The isfinite function provides a reliable and fast way to detect special values It returns True for regular numbers and False for Nan or Infinity from math import isfinite isfinite x for x in 123 4 56 float Nan float Inf True True False False The expm1 function computes e x 1 for small values of x without incurring the loss of precision that usually accompanies the subtraction of nearly equal quantities from math import expm1 expm1 0 013671875 more accurate way to compute e x 1 for a small x 0 013765762467652909 The erf function computes a probability integral or Gaussian error function The complementary error function erfc is 1 erf x from math import erf erfc sqrt erf 1 0 sqrt 2 0 portion of normal distribution within 1 standard deviation 0 682689492137086 erfc 1 0 sqrt 2 0 portion of normal distribution outside 1 standard deviation 0 31731050786291404 erf 1 0 sqrt 2 0 erfc 1 0 sqrt 2 0 1 0 The gamma function is a continuous extension of the factorial function See https en wikipedia org wiki Gamma_function for details Because the function is related to factorials it grows large even for small values of x so there is also a lgamma function for computing the natural logarithm of the gamma function from math import gamma lgamma gamma 7 0 six factorial 720 0 lgamma 801 0 log 800 factorial 4551 950730698041 Contributed by Mark Dickinson abc The abc module now supports abstractclassmethod and abstractstaticmethod These tools make it possible to define an abstract base class that requires a particular classmethod or staticmethod to be implemented class Temperature metaclass abc ABCMeta abc abstractclassmethod def from_fahrenheit cls t abc abstractclassmethod def from_celsius cls t Patch submitted by Daniel Urban bpo 5867 io The io BytesIO has a new method getbuffer which provides functionality similar to memoryview It creates an editable view of the data without making a copy The buffer s random access and support for slice notation are well suited to in place editing REC_LEN LOC_START LOC_LEN 34 7 11 def change_location buffer record_number location start record_number REC_LEN LOC_START buffer start start LOC_LEN location import io byte_stream io BytesIO b G3805 storeroom Main chassis b X7899 shipping Reserve cog b L6988 receiving Primary sprocket buffer byte_stream getbuffer change_location buffer 1 b warehouse change_location buffer 0 b showroom print byte_stream getvalue b G3805 showroom Main chassis b X7899 warehouse Reserve cog b L6988 receiving Primary sprocket Contributed by Antoine Pitrou in bpo 5506 reprlib When writing a __repr__ method for a custom container it is easy to forget to handle the case where a member refers back to the container itself Python s builtin objects such as list and set handle self reference by displaying in the recursive part of the representation string To help write such __repr__ methods the reprlib module has a new decorator recursive_repr for detecting recursive calls to __repr__ and substituting a placeholder string instead class MyList list recursive_repr def __repr__ self return join map repr self m MyList abc m append m m append x print m a b c x Contributed by Raymond Hettinger in bpo 9826 and bpo 9840 logging In addition to dictionary based configuration described above the logging package has many other improvements The logging documentation has been augmented by a basic tutorial an advanced tutorial and a cookbook of logging recipes These documents are the fastest way to learn about logging The logging basicConfig set up function gained a style argument to support three different types of string formatting It defaults to for traditional formatting can be set to for the new str format style or can be set to for the shell style formatting provided by string Template The following three configurations are equivalent from logging import basicConfig basicConfig style format name s levelname s message s basicConfig style format name levelname message basicConfig style format name leveln
en
null
2,321
ame message If no configuration is set up before a logging event occurs there is now a default configuration using a StreamHandler directed to sys stderr for events of WARNING level or higher Formerly an event occurring before a configuration was set up would either raise an exception or silently drop the event depending on the value of logging raiseExceptions The new default handler is stored in logging lastResort The use of filters has been simplified Instead of creating a Filter object the predicate can be any Python callable that returns True or False There were a number of other improvements that add flexibility and simplify configuration See the module documentation for a full listing of changes in Python 3 2 csv The csv module now supports a new dialect unix_dialect which applies quoting for all fields and a traditional Unix style with n as the line terminator The registered dialect name is unix The csv DictWriter has a new method writeheader for writing out an initial row to document the field names import csv sys w csv DictWriter sys stdout name dept dialect unix w writeheader name dept w writerows name tom dept accounting name susan dept Salesl tom accounting susan sales New dialect suggested by Jay Talbot in bpo 5975 and the new method suggested by Ed Abraham in bpo 1537721 contextlib There is a new and slightly mind blowing tool ContextDecorator that is helpful for creating a context manager that does double duty as a function decorator As a convenience this new functionality is used by contextmanager so that no extra effort is needed to support both roles The basic idea is that both context managers and function decorators can be used for pre action and post action wrappers Context managers wrap a group of statements using a with statement and function decorators wrap a group of statements enclosed in a function So occasionally there is a need to write a pre action or post action wrapper that can be used in either role For example it is sometimes useful to wrap functions or groups of statements with a logger that can track the time of entry and time of exit Rather than writing both a function decorator and a context manager for the task the contextmanager provides both capabilities in a single definition from contextlib import contextmanager import logging logging basicConfig level logging INFO contextmanager def track_entry_and_exit name logging info Entering s name yield logging info Exiting s name Formerly this would have only been usable as a context manager with track_entry_and_exit widget loader print Some time consuming activity goes here load_widget Now it can be used as a decorator as well track_entry_and_exit widget loader def activity print Some time consuming activity goes here load_widget Trying to fulfill two roles at once places some limitations on the technique Context managers normally have the flexibility to return an argument usable by a with statement but there is no parallel for function decorators In the above example there is not a clean way for the track_entry_and_exit context manager to return a logging instance for use in the body of enclosed statements Contributed by Michael Foord in bpo 9110 decimal and fractions Mark Dickinson crafted an elegant and efficient scheme for assuring that different numeric datatypes will have the same hash value whenever their actual values are equal bpo 8188 assert hash Fraction 3 2 hash 1 5 hash Decimal 1 5 hash complex 1 5 0 Some of the hashing details are exposed through a new attribute sys hash_info which describes the bit width of the hash value the prime modulus the hash values for infinity and nan and the multiplier used for the imaginary part of a number sys hash_info sys hash_info width 64 modulus 2305843009213693951 inf 314159 nan 0 imag 1000003 An early decision to limit the interoperability of various numeric types has been relaxed It is still unsupported and ill advised to have implicit mixing in arithmetic expressions such as Decimal 1 1 float 1 1 because the latter loses information in the process of constructing the binary float Howev
en
null
2,322
er since existing floating point value can be converted losslessly to either a decimal or rational representation it makes sense to add them to the constructor and to support mixed type comparisons The decimal Decimal constructor now accepts float objects directly so there in no longer a need to use the from_float method bpo 8257 Mixed type comparisons are now fully supported so that Decimal objects can be directly compared with float and fractions Fraction bpo 2531 and bpo 8188 Similar changes were made to fractions Fraction so that the from_float and from_decimal methods are no longer needed bpo 8294 from decimal import Decimal from fractions import Fraction Decimal 1 1 Decimal 1 100000000000000088817841970012523233890533447265625 Fraction 1 1 Fraction 2476979795053773 2251799813685248 Another useful change for the decimal module is that the Context clamp attribute is now public This is useful in creating contexts that correspond to the decimal interchange formats specified in IEEE 754 see bpo 8540 Contributed by Mark Dickinson and Raymond Hettinger ftp The ftplib FTP class now supports the context management protocol to unconditionally consume socket error exceptions and to close the FTP connection when done from ftplib import FTP with FTP ftp1 at proftpd org as ftp ftp login ftp dir 230 Anonymous login ok restrictions apply dr xr xr x 9 ftp ftp 154 May 6 10 43 dr xr xr x 9 ftp ftp 154 May 6 10 43 dr xr xr x 5 ftp ftp 4096 May 6 10 43 CentOS dr xr xr x 3 ftp ftp 18 Jul 10 2008 Fedora Other file like objects such as mmap mmap and fileinput input also grew auto closing context managers with fileinput input files log1 txt log2 txt as f for line in f process line Contributed by Tarek Ziadé and Giampaolo Rodolà in bpo 4972 and by Georg Brandl in bpo 8046 and bpo 1286 The FTP_TLS class now accepts a context parameter which is a ssl SSLContext object allowing bundling SSL configuration options certificates and private keys into a single potentially long lived structure Contributed by Giampaolo Rodolà bpo 8806 popen The os popen and subprocess Popen functions now support with statements for auto closing of the file descriptors Contributed by Antoine Pitrou and Brian Curtin in bpo 7461 and bpo 10554 select The select module now exposes a new constant attribute PIPE_BUF which gives the minimum number of bytes which are guaranteed not to block when select select says a pipe is ready for writing import select select PIPE_BUF 512 Available on Unix systems Patch by Sébastien Sablé in bpo 9862 gzip and zipfile gzip GzipFile now implements the io BufferedIOBase abstract base class except for truncate It also has a peek method and supports unseekable as well as zero padded file objects The gzip module also gains the compress and decompress functions for easier in memory compression and decompression Keep in mind that text needs to be encoded as bytes before compressing and decompressing import gzip s Three shall be the number thou shalt count s and the number of the counting shall be three b s encode convert to utf 8 len b 89 c gzip compress b len c 77 gzip decompress c decode 42 decompress and convert to text Three shall be the number thou shalt count Contributed by Anand B Pillai in bpo 3488 and by Antoine Pitrou Nir Aides and Brian Curtin in bpo 9962 bpo 1675951 bpo 7471 and bpo 2846 Also the zipfile ZipExtFile class was reworked internally to represent files stored inside an archive The new implementation is significantly faster and can be wrapped in an io BufferedReader object for more speedups It also solves an issue where interleaved calls to read and readline gave the wrong results Patch submitted by Nir Aides in bpo 7610 tarfile The TarFile class can now be used as a context manager In addition its add method has a new option filter that controls which files are added to the archive and allows the file metadata to be edited The new filter option replaces the older less flexible exclude parameter which is now deprecated If specified the optional filter parameter needs to be a keyword argument The user supplied filter function
en
null
2,323
accepts a TarInfo object and returns an updated TarInfo object or if it wants the file to be excluded the function can return None import tarfile glob def myfilter tarinfo if tarinfo isfile only save real files tarinfo uname monty redact the user name return tarinfo with tarfile open name myarchive tar gz mode w gz as tf for filename in glob glob txt tf add filename filter myfilter tf list rw r r monty 501 902 2011 01 26 17 59 11 annotations txt rw r r monty 501 123 2011 01 26 17 59 11 general_questions txt rw r r monty 501 3514 2011 01 26 17 59 11 prion txt rw r r monty 501 124 2011 01 26 17 59 11 py_todo txt rw r r monty 501 1399 2011 01 26 17 59 11 semaphore_notes txt Proposed by Tarek Ziadé and implemented by Lars Gustäbel in bpo 6856 hashlib The hashlib module has two new constant attributes listing the hashing algorithms guaranteed to be present in all implementations and those available on the current implementation import hashlib hashlib algorithms_guaranteed sha1 sha224 sha384 sha256 sha512 md5 hashlib algorithms_available md2 SHA256 SHA512 dsaWithSHA mdc2 SHA224 MD4 sha256 sha512 ripemd160 SHA1 MDC2 SHA SHA384 MD2 ecdsa with SHA1 md4 md5 sha1 DSA SHA sha224 dsaEncryption DSA RIPEMD160 sha MD5 sha384 Suggested by Carl Chenet in bpo 7418 ast The ast module has a wonderful a general purpose tool for safely evaluating expression strings using the Python literal syntax The ast literal_eval function serves as a secure alternative to the builtin eval function which is easily abused Python 3 2 adds bytes and set literals to the list of supported types strings bytes numbers tuples lists dicts sets booleans and None from ast import literal_eval request req 3 func pow args 2 0 5 literal_eval request args 2 0 5 req 3 func pow request os system do something harmful literal_eval request Traceback most recent call last ValueError malformed node or string _ast Call object at 0x101739a10 Implemented by Benjamin Peterson and Georg Brandl os Different operating systems use various encodings for filenames and environment variables The os module provides two new functions fsencode and fsdecode for encoding and decoding filenames import os filename Sehenswürdigkeiten os fsencode filename b Sehensw xc3 xbcrdigkeiten Some operating systems allow direct access to encoded bytes in the environment If so the os supports_bytes_environ constant will be true For direct access to encoded environment variables if available use the new os getenvb function or use os environb which is a bytes version of os environ Contributed by Victor Stinner shutil The shutil copytree function has two new options ignore_dangling_symlinks when symlinks False so that the function copies a file pointed to by a symlink not the symlink itself This option will silence the error raised if the file doesn t exist copy_function is a callable that will be used to copy files shutil copy2 is used by default Contributed by Tarek Ziadé In addition the shutil module now supports archiving operations for zipfiles uncompressed tarfiles gzipped tarfiles and bzipped tarfiles And there are functions for registering additional archiving file formats such as xz compressed tarfiles or custom formats The principal functions are make_archive and unpack_archive By default both operate on the current directory which can be set by os chdir and on any sub directories The archive filename needs to be specified with a full pathname The archiving step is non destructive the original files are left unchanged import shutil pprint os chdir mydata change to the source directory f shutil make_archive var backup mydata zip archive the current directory f show the name of archive var backup mydata zip os chdir tmp change to an unpacking shutil unpack_archive var backup mydata zip recover the data pprint pprint shutil get_archive_formats display known formats bztar bzip2 ed tar file gztar gzip ed tar file tar uncompressed tar file zip ZIP file shutil register_archive_format register a new archive format name xz function xz compress callable archiving function extra_args level 8 arguments to the functi
en
null
2,324
on description xz compression Contributed by Tarek Ziadé sqlite3 The sqlite3 module was updated to pysqlite version 2 6 0 It has two new capabilities The sqlite3 Connection in_transit attribute is true if there is an active transaction for uncommitted changes The sqlite3 Connection enable_load_extension and sqlite3 Connection load_extension methods allows you to load SQLite extensions from so files One well known extension is the fulltext search extension distributed with SQLite Contributed by R David Murray and Shashwat Anand bpo 8845 html A new html module was introduced with only a single function escape which is used for escaping reserved characters from HTML markup import html html escape x 2 x 7 x gt 2 amp amp x lt 7 socket The socket module has two new improvements Socket objects now have a detach method which puts the socket into closed state without actually closing the underlying file descriptor The latter can then be reused for other purposes Added by Antoine Pitrou bpo 8524 socket create_connection now supports the context management protocol to unconditionally consume socket error exceptions and to close the socket when done Contributed by Giampaolo Rodolà bpo 9794 ssl The ssl module added a number of features to satisfy common requirements for secure encrypted authenticated internet connections A new class SSLContext serves as a container for persistent SSL data such as protocol settings certificates private keys and various other options It includes a wrap_socket for creating an SSL socket from an SSL context A new function ssl match_hostname supports server identity verification for higher level protocols by implementing the rules of HTTPS from RFC 2818 which are also suitable for other protocols The ssl wrap_socket constructor function now takes a ciphers argument The ciphers string lists the allowed encryption algorithms using the format described in the OpenSSL documentation When linked against recent versions of OpenSSL the ssl module now supports the Server Name Indication extension to the TLS protocol allowing multiple virtual hosts using different certificates on a single IP port This extension is only supported in client mode and is activated by passing the server_hostname argument to ssl SSLContext wrap_socket Various options have been added to the ssl module such as OP_NO_SSLv2 which disables the insecure and obsolete SSLv2 protocol The extension now loads all the OpenSSL ciphers and digest algorithms If some SSL certificates cannot be verified they are reported as an unknown algorithm error The version of OpenSSL being used is now accessible using the module attributes ssl OPENSSL_VERSION a string ssl OPENSSL_VERSION_INFO a 5 tuple and ssl OPENSSL_VERSION_NUMBER an integer Contributed by Antoine Pitrou in bpo 8850 bpo 1589 bpo 8322 bpo 5639 bpo 4870 bpo 8484 and bpo 8321 nntp The nntplib module has a revamped implementation with better bytes and text semantics as well as more practical APIs These improvements break compatibility with the nntplib version in Python 3 1 which was partly dysfunctional in itself Support for secure connections through both implicit using nntplib NNTP_SSL and explicit using nntplib NNTP starttls TLS has also been added Contributed by Antoine Pitrou in bpo 9360 and Andrew Vant in bpo 1926 certificates http client HTTPSConnection urllib request HTTPSHandler and urllib request urlopen now take optional arguments to allow for server certificate checking against a set of Certificate Authorities as recommended in public uses of HTTPS Added by Antoine Pitrou bpo 9003 imaplib Support for explicit TLS on standard IMAP4 connections has been added through the new imaplib IMAP4 starttls method Contributed by Lorenzo M Catucci and Antoine Pitrou bpo 4471 http client There were a number of small API improvements in the http client module The old style HTTP 0 9 simple responses are no longer supported and the strict parameter is deprecated in all classes The HTTPConnection and HTTPSConnection classes now have a source_address parameter for a host port tuple indicating where the HTTP
en
null
2,325
connection is made from Support for certificate checking and HTTPS virtual hosts were added to HTTPSConnection The request method on connection objects allowed an optional body argument so that a file object could be used to supply the content of the request Conveniently the body argument now also accepts an iterable object so long as it includes an explicit Content Length header This extended interface is much more flexible than before To establish an HTTPS connection through a proxy server there is a new set_tunnel method that sets the host and port for HTTP Connect tunneling To match the behavior of http server the HTTP client library now also encodes headers with ISO 8859 1 Latin 1 encoding It was already doing that for incoming headers so now the behavior is consistent for both incoming and outgoing traffic See work by Armin Ronacher in bpo 10980 unittest The unittest module has a number of improvements supporting test discovery for packages easier experimentation at the interactive prompt new testcase methods improved diagnostic messages for test failures and better method names The command line call python m unittest can now accept file paths instead of module names for running specific tests bpo 10620 The new test discovery can find tests within packages locating any test importable from the top level directory The top level directory can be specified with the t option a pattern for matching files with p and a directory to start discovery with s python m unittest discover s my_proj_dir p _test py Contributed by Michael Foord Experimentation at the interactive prompt is now easier because the unittest TestCase class can now be instantiated without arguments from unittest import TestCase TestCase assertEqual pow 2 3 8 Contributed by Michael Foord The unittest module has two new methods assertWarns and assertWarnsRegex to verify that a given warning type is triggered by the code under test with self assertWarns DeprecationWarning legacy_function XYZ Contributed by Antoine Pitrou bpo 9754 Another new method assertCountEqual is used to compare two iterables to determine if their element counts are equal whether the same elements are present with the same number of occurrences regardless of order def test_anagram self self assertCountEqual algorithm logarithm Contributed by Raymond Hettinger A principal feature of the unittest module is an effort to produce meaningful diagnostics when a test fails When possible the failure is recorded along with a diff of the output This is especially helpful for analyzing log files of failed test runs However since diffs can sometime be voluminous there is a new maxDiff attribute that sets maximum length of diffs displayed In addition the method names in the module have undergone a number of clean ups For example assertRegex is the new name for assertRegexpMatches which was misnamed because the test uses re search not re match Other methods using regular expressions are now named using short form Regex in preference to Regexp this matches the names used in other unittest implementations matches Python s old name for the re module and it has unambiguous camel casing Contributed by Raymond Hettinger and implemented by Ezio Melotti To improve consistency some long standing method aliases are being deprecated in favor of the preferred names Old Name Preferred Name assert_ assertTrue assertEquals assertEqual assertNotEquals assertNotEqual assertAlmostEquals assertAlmostEqual assertNotAlmostEquals assertNotAlmostEqual Likewise the TestCase fail methods deprecated in Python 3 1 are expected to be removed in Python 3 3 Contributed by Ezio Melotti bpo 9424 The assertDictContainsSubset method was deprecated because it was misimplemented with the arguments in the wrong order This created hard to debug optical illusions where tests like TestCase assertDictContainsSubset a 1 b 2 a 1 would fail Contributed by Raymond Hettinger random The integer methods in the random module now do a better job of producing uniform distributions Previously they computed selections with int n random which had a slig
en
null
2,326
ht bias whenever n was not a power of two Now multiple selections are made from a range up to the next power of two and a selection is kept only when it falls within the range 0 x n The functions and methods affected are randrange randint choice shuffle and sample Contributed by Raymond Hettinger bpo 9025 poplib POP3_SSL class now accepts a context parameter which is a ssl SSLContext object allowing bundling SSL configuration options certificates and private keys into a single potentially long lived structure Contributed by Giampaolo Rodolà bpo 8807 asyncore asyncore dispatcher now provides a handle_accepted method returning a sock addr pair which is called when a connection has actually been established with a new remote endpoint This is supposed to be used as a replacement for old handle_accept and avoids the user to call accept directly Contributed by Giampaolo Rodolà bpo 6706 tempfile The tempfile module has a new context manager TemporaryDirectory which provides easy deterministic cleanup of temporary directories with tempfile TemporaryDirectory as tmpdirname print created temporary dir tmpdirname Contributed by Neil Schemenauer and Nick Coghlan bpo 5178 inspect The inspect module has a new function getgeneratorstate to easily identify the current state of a generator iterator from inspect import getgeneratorstate def gen yield demo g gen getgeneratorstate g GEN_CREATED next g demo getgeneratorstate g GEN_SUSPENDED next g None getgeneratorstate g GEN_CLOSED Contributed by Rodolpho Eckhardt and Nick Coghlan bpo 10220 To support lookups without the possibility of activating a dynamic attribute the inspect module has a new function getattr_static Unlike hasattr this is a true read only search guaranteed not to change state while it is searching class A property def f self print Running return 10 a A getattr a f Running 10 inspect getattr_static a f property object at 0x1022bd788 Contributed by Michael Foord pydoc The pydoc module now provides a much improved web server interface as well as a new command line option b to automatically open a browser window to display that server pydoc3 2 b Contributed by Ron Adam bpo 2001 dis The dis module gained two new functions for inspecting code code_info and show_code Both provide detailed code object information for the supplied function method source code string or code object The former returns a string and the latter prints it import dis random dis show_code random choice Name choice Filename Library Frameworks Python framework Versions 3 2 lib python3 2 random py Argument count 2 Kw only arguments 0 Number of locals 3 Stack size 11 Flags OPTIMIZED NEWLOCALS NOFREE Constants 0 Choose a random element from a non empty sequence 1 Cannot choose from an empty sequence Names 0 _randbelow 1 len 2 ValueError 3 IndexError Variable names 0 self 1 seq 2 i In addition the dis function now accepts string arguments so that the common idiom dis compile s eval can be shortened to dis s dis 3 x 1 if x 2 1 else x 2 1 0 LOAD_NAME 0 x 3 LOAD_CONST 0 2 6 BINARY_MODULO 7 LOAD_CONST 1 1 10 COMPARE_OP 2 13 POP_JUMP_IF_FALSE 28 16 LOAD_CONST 2 3 19 LOAD_NAME 0 x 22 BINARY_MULTIPLY 23 LOAD_CONST 1 1 26 BINARY_ADD 27 RETURN_VALUE 28 LOAD_NAME 0 x 31 LOAD_CONST 0 2 34 BINARY_FLOOR_DIVIDE 35 RETURN_VALUE Taken together these improvements make it easier to explore how CPython is implemented and to see for yourself what the language syntax does under the hood Contributed by Nick Coghlan in bpo 9147 dbm All database modules now support the get and setdefault methods Suggested by Ray Allen in bpo 9523 ctypes A new type ctypes c_ssize_t represents the C ssize_t datatype site The site module has three new functions useful for reporting on the details of a given Python installation getsitepackages lists all global site packages directories getuserbase reports on the user s base directory where data can be stored getusersitepackages reveals the user specific site packages directory path import site site getsitepackages Library Frameworks Python framework Versions 3 2 lib python3 2 site packages Library Framewor
en
null
2,327
ks Python framework Versions 3 2 lib site python Library Python 3 2 site packages site getuserbase Users raymondhettinger Library Python 3 2 site getusersitepackages Users raymondhettinger Library Python 3 2 lib python site packages Conveniently some of site s functionality is accessible directly from the command line python m site user base Users raymondhettinger local python m site user site Users raymondhettinger local lib python3 2 site packages Contributed by Tarek Ziadé in bpo 6693 sysconfig The new sysconfig module makes it straightforward to discover installation paths and configuration variables that vary across platforms and installations The module offers access simple access functions for platform and version information get_platform returning values like linux i586 or macosx 10 6 ppc get_python_version returns a Python version string such as 3 2 It also provides access to the paths and variables corresponding to one of seven named schemes used by distutils Those include posix_prefix posix_home posix_user nt nt_user os2 os2_home get_paths makes a dictionary containing installation paths for the current installation scheme get_config_vars returns a dictionary of platform specific variables There is also a convenient command line interface C Python32 python m sysconfig Platform win32 Python version 3 2 Current installation scheme nt Paths data C Python32 include C Python32 Include platinclude C Python32 Include platlib C Python32 Lib site packages platstdlib C Python32 Lib purelib C Python32 Lib site packages scripts C Python32 Scripts stdlib C Python32 Lib Variables BINDIR C Python32 BINLIBDEST C Python32 Lib EXE exe INCLUDEPY C Python32 Include LIBDEST C Python32 Lib SO pyd VERSION 32 abiflags base C Python32 exec_prefix C Python32 platbase C Python32 prefix C Python32 projectbase C Python32 py_version 3 2 py_version_nodot 32 py_version_short 3 2 srcdir C Python32 userbase C Documents and Settings Raymond Application Data Python Moved out of Distutils by Tarek Ziadé pdb The pdb debugger module gained a number of usability improvements pdb py now has a c option that executes commands as given in a pdbrc script file A pdbrc script file can contain continue and next commands that continue debugging The Pdb class constructor now accepts a nosigint argument New commands l list ll long list and source for listing source code New commands display and undisplay for showing or hiding the value of an expression if it has changed New command interact for starting an interactive interpreter containing the global and local names found in the current scope Breakpoints can be cleared by breakpoint number Contributed by Georg Brandl Antonio Cuni and Ilya Sandler configparser The configparser module was modified to improve usability and predictability of the default parser and its supported INI syntax The old ConfigParser class was removed in favor of SafeConfigParser which has in turn been renamed to ConfigParser Support for inline comments is now turned off by default and section or option duplicates are not allowed in a single configuration source Config parsers gained a new API based on the mapping protocol parser ConfigParser parser read_string DEFAULT location upper left visible yes editable no color blue main title Main Menu color green options title Options parser main color green parser main editable no section parser options section title Options section title Options editable editable s section title Options editable no The new API is implemented on top of the classical API so custom parser subclasses should be able to use it without modifications The INI file structure accepted by config parsers can now be customized Users can specify alternative option value delimiters and comment prefixes change the name of the DEFAULT section or switch the interpolation syntax There is support for pluggable interpolation including an additional interpolation handler ExtendedInterpolation parser ConfigParser interpolation ExtendedInterpolation parser read_dict buildout directory home ambv zope9 custom prefix usr local parser rea
en
null
2,328
d_string buildout parts zope9 instance find links buildout directory downloads dist zope9 recipe plone recipe zope9install location opt zope instance recipe plone recipe zope9instance zope9 location zope9 location zope conf custom prefix etc zope conf parser buildout find links n home ambv zope9 downloads dist parser instance zope conf usr local etc zope conf instance parser instance instance zope conf usr local etc zope conf instance zope9 location opt zope A number of smaller features were also introduced like support for specifying encoding in read operations specifying fallback values for get functions or reading directly from dictionaries and strings All changes contributed by Łukasz Langa urllib parse A number of usability improvements were made for the urllib parse module The urlparse function now supports IPv6 addresses as described in RFC 2732 import urllib parse urllib parse urlparse http dead beef cafe 5417 affe 8FA3 deaf feed foo ParseResult scheme http netloc dead beef cafe 5417 affe 8FA3 deaf feed path foo params query fragment The urldefrag function now returns a named tuple r urllib parse urldefrag http python org about target r DefragResult url http python org about fragment target r 0 http python org about r fragment target And the urlencode function is now much more flexible accepting either a string or bytes type for the query argument If it is a string then the safe encoding and error parameters are sent to quote_plus for encoding urllib parse urlencode type telenovela name Dónde Está Elisa encoding latin 1 type telenovela name BFD F3nde Est E1 Elisa 3F As detailed in Parsing ASCII Encoded Bytes all the urllib parse functions now accept ASCII encoded byte strings as input so long as they are not mixed with regular strings If ASCII encoded byte strings are given as parameters the return types will also be an ASCII encoded byte strings urllib parse urlparse b http www python org 80 about ParseResultBytes scheme b http netloc b www python org 80 path b about params b query b fragment b Work by Nick Coghlan Dan Mahn and Senthil Kumaran in bpo 2987 bpo 5468 and bpo 9873 mailbox Thanks to a concerted effort by R David Murray the mailbox module has been fixed for Python 3 2 The challenge was that mailbox had been originally designed with a text interface but email messages are best represented with bytes because various parts of a message may have different encodings The solution harnessed the email package s binary support for parsing arbitrary email messages In addition the solution required a number of API changes As expected the add method for mailbox Mailbox objects now accepts binary input StringIO and text file input are deprecated Also string input will fail early if non ASCII characters are used Previously it would fail when the email was processed in a later step There is also support for binary output The get_file method now returns a file in the binary mode where it used to incorrectly set the file to text mode There is also a new get_bytes method that returns a bytes representation of a message corresponding to a given key It is still possible to get non binary output using the old API s get_string method but that approach is not very useful Instead it is best to extract messages from a Message object or to load them from binary input Contributed by R David Murray with efforts from Steffen Daode Nurpmeso and an initial patch by Victor Stinner in bpo 9124 turtledemo The demonstration code for the turtle module was moved from the Demo directory to main library It includes over a dozen sample scripts with lively displays Being on sys path it can now be run directly from the command line python m turtledemo Moved from the Demo directory by Alexander Belopolsky in bpo 10199 Multi threading The mechanism for serializing execution of concurrently running Python threads generally known as the GIL or Global Interpreter Lock has been rewritten Among the objectives were more predictable switching intervals and reduced overhead due to lock contention and the number of ensuing system calls The notion of a c
en
null
2,329
heck interval to allow thread switches has been abandoned and replaced by an absolute duration expressed in seconds This parameter is tunable through sys setswitchinterval It currently defaults to 5 milliseconds Additional details about the implementation can be read from a python dev mailing list message however priority requests as exposed in this message have not been kept for inclusion Contributed by Antoine Pitrou Regular and recursive locks now accept an optional timeout argument to their acquire method Contributed by Antoine Pitrou bpo 7316 Similarly threading Semaphore acquire also gained a timeout argument Contributed by Torsten Landschoff bpo 850728 Regular and recursive lock acquisitions can now be interrupted by signals on platforms using Pthreads This means that Python programs that deadlock while acquiring locks can be successfully killed by repeatedly sending SIGINT to the process by pressing Ctrl C in most shells Contributed by Reid Kleckner bpo 8844 Optimizations A number of small performance enhancements have been added Python s peephole optimizer now recognizes patterns such x in 1 2 3 as being a test for membership in a set of constants The optimizer recasts the set as a frozenset and stores the pre built constant Now that the speed penalty is gone it is practical to start writing membership tests using set notation This style is both semantically clear and operationally fast extension name rpartition 2 if extension in xml html xhtml css handle name Patch and additional tests contributed by Dave Malcolm bpo 6690 Serializing and unserializing data using the pickle module is now several times faster Contributed by Alexandre Vassalotti Antoine Pitrou and the Unladen Swallow team in bpo 9410 and bpo 3873 The Timsort algorithm used in list sort and sorted now runs faster and uses less memory when called with a key function Previously every element of a list was wrapped with a temporary object that remembered the key value associated with each element Now two arrays of keys and values are sorted in parallel This saves the memory consumed by the sort wrappers and it saves time lost to delegating comparisons Patch by Daniel Stutzbach in bpo 9915 JSON decoding performance is improved and memory consumption is reduced whenever the same string is repeated for multiple keys Also JSON encoding now uses the C speedups when the sort_keys argument is true Contributed by Antoine Pitrou in bpo 7451 and by Raymond Hettinger and Antoine Pitrou in bpo 10314 Recursive locks created with the threading RLock API now benefit from a C implementation which makes them as fast as regular locks and between 10x and 15x faster than their previous pure Python implementation Contributed by Antoine Pitrou bpo 3001 The fast search algorithm in stringlib is now used by the split rsplit splitlines and replace methods on bytes bytearray and str objects Likewise the algorithm is also used by rfind rindex rsplit and rpartition Patch by Florent Xicluna in bpo 7622 and bpo 7462 Integer to string conversions now work two digits at a time reducing the number of division and modulo operations bpo 6713 by Gawain Bolton Mark Dickinson and Victor Stinner There were several other minor optimizations Set differencing now runs faster when one operand is much larger than the other patch by Andress Bennetts in bpo 8685 The array repeat method has a faster implementation bpo 1569291 by Alexander Belopolsky The BaseHTTPRequestHandler has more efficient buffering bpo 3709 by Andrew Schaaf The operator attrgetter function has been sped up bpo 10160 by Christos Georgiou And ConfigParser loads multi line arguments a bit faster bpo 7113 by Łukasz Langa Unicode Python has been updated to Unicode 6 0 0 The update to the standard adds over 2 000 new characters including emoji symbols which are important for mobile phones In addition the updated standard has altered the character properties for two Kannada characters U 0CF1 U 0CF2 and one New Tai Lue numeric character U 19DA making the former eligible for use in identifiers while disqualifying the latter For more i
en
null
2,330
nformation see Unicode Character Database Changes Codecs Support was added for cp720 Arabic DOS encoding bpo 1616979 MBCS encoding no longer ignores the error handler argument In the default strict mode it raises an UnicodeDecodeError when it encounters an undecodable byte sequence and an UnicodeEncodeError for an unencodable character The MBCS codec supports strict and ignore error handlers for decoding and strict and replace for encoding To emulate Python3 1 MBCS encoding select the ignore handler for decoding and the replace handler for encoding On Mac OS X Python decodes command line arguments with utf 8 rather than the locale encoding By default tarfile uses utf 8 encoding on Windows instead of mbcs and the surrogateescape error handler on all operating systems Documentation The documentation continues to be improved A table of quick links has been added to the top of lengthy sections such as Built in Functions In the case of itertools the links are accompanied by tables of cheatsheet style summaries to provide an overview and memory jog without having to read all of the docs In some cases the pure Python source code can be a helpful adjunct to the documentation so now many modules now feature quick links to the latest version of the source code For example the functools module documentation has a quick link at the top labeled Source code Lib functools py Contributed by Raymond Hettinger see rationale The docs now contain more examples and recipes In particular re module has an extensive section Regular Expression Examples Likewise the itertools module continues to be updated with new Itertools Recipes The datetime module now has an auxiliary implementation in pure Python No functionality was changed This just provides an easier to read alternate implementation Contributed by Alexander Belopolsky in bpo 9528 The unmaintained Demo directory has been removed Some demos were integrated into the documentation some were moved to the Tools demo directory and others were removed altogether Contributed by Georg Brandl in bpo 7962 IDLE The format menu now has an option to clean source files by stripping trailing whitespace Contributed by Raymond Hettinger bpo 5150 IDLE on Mac OS X now works with both Carbon AquaTk and Cocoa AquaTk Contributed by Kevin Walzer Ned Deily and Ronald Oussoren bpo 6075 Code Repository In addition to the existing Subversion code repository at https svn python org there is now a Mercurial repository at https hg python org After the 3 2 release there are plans to switch to Mercurial as the primary repository This distributed version control system should make it easier for members of the community to create and share external changesets See PEP 385 for details To learn to use the new version control system see the Quick Start or the Guide to Mercurial Workflows Build and C API Changes Changes to Python s build process and to the C API include The idle pydoc and 2to3 scripts are now installed with a version specific suffix on make altinstall bpo 10679 The C functions that access the Unicode Database now accept and return characters from the full Unicode range even on narrow unicode builds Py_UNICODE_TOLOWER Py_UNICODE_ISDECIMAL and others A visible difference in Python is that unicodedata numeric now returns the correct value for large code points and repr may consider more characters as printable Reported by Bupjoe Lee and fixed by Amaury Forgeot D Arc bpo 5127 Computed gotos are now enabled by default on supported compilers which are detected by the configure script They can still be disabled selectively by specifying without computed gotos Contributed by Antoine Pitrou bpo 9203 The option with wctype functions was removed The built in unicode database is now used for all functions Contributed by Amaury Forgeot D Arc bpo 9210 Hash values are now values of a new type Py_hash_t which is defined to be the same size as a pointer Previously they were of type long which on some 64 bit operating systems is still only 32 bits long As a result of this fix set and dict can now hold more than 2 32 entries on b
en
null
2,331
uilds with 64 bit pointers previously they could grow to that size but their performance degraded catastrophically Suggested by Raymond Hettinger and implemented by Benjamin Peterson bpo 9778 A new macro Py_VA_COPY copies the state of the variable argument list It is equivalent to C99 va_copy but available on all Python platforms bpo 2443 A new C API function PySys_SetArgvEx allows an embedded interpreter to set sys argv without also modifying sys path bpo 5753 PyEval_CallObject is now only available in macro form The function declaration which was kept for backwards compatibility reasons is now removed the macro was introduced in 1997 bpo 8276 There is a new function PyLong_AsLongLongAndOverflow which is analogous to PyLong_AsLongAndOverflow They both serve to convert Python int into a native fixed width type while providing detection of cases where the conversion won t fit bpo 7767 The PyUnicode_CompareWithASCIIString function now returns not equal if the Python string is NUL terminated There is a new function PyErr_NewExceptionWithDoc that is like PyErr_NewException but allows a docstring to be specified This lets C exceptions have the same self documenting capabilities as their pure Python counterparts bpo 7033 When compiled with the with valgrind option the pymalloc allocator will be automatically disabled when running under Valgrind This gives improved memory leak detection when running under Valgrind while taking advantage of pymalloc at other times bpo 2422 Removed the O format from the PyArg_Parse functions The format is no longer used and it had never been documented bpo 8837 There were a number of other small changes to the C API See the Misc NEWS file for a complete list Also there were a number of updates to the Mac OS X build see Mac BuildScript README txt for details For users running a 32 64 bit build there is a known problem with the default Tcl Tk on Mac OS X 10 6 Accordingly we recommend installing an updated alternative such as ActiveState Tcl Tk 8 5 9 See https www python org download mac tcltk for additional details Porting to Python 3 2 This section lists previously described changes and other bugfixes that may require changes to your code The configparser module has a number of clean ups The major change is to replace the old ConfigParser class with long standing preferred alternative SafeConfigParser In addition there are a number of smaller incompatibilities The interpolation syntax is now validated on get and set operations In the default interpolation scheme only two tokens with percent signs are valid name s and the latter being an escaped percent sign The set and add_section methods now verify that values are actual strings Formerly unsupported types could be introduced unintentionally Duplicate sections or options from a single source now raise either DuplicateSectionError or DuplicateOptionError Formerly duplicates would silently overwrite a previous entry Inline comments are now disabled by default so now the character can be safely used in values Comments now can be indented Consequently for or to appear at the start of a line in multiline values it has to be interpolated This keeps comment prefix characters in values from being mistaken as comments is now a valid value and is no longer automatically converted to an empty string For empty strings use option in a line The nntplib module was reworked extensively meaning that its APIs are often incompatible with the 3 1 APIs bytearray objects can no longer be used as filenames instead they should be converted to bytes The array tostring and array fromstring have been renamed to array tobytes and array frombytes for clarity The old names have been deprecated See bpo 8990 PyArg_Parse functions t format has been removed use s or s instead w and w formats has been removed use w instead The PyCObject type deprecated in 3 1 has been removed To wrap opaque C pointers in Python objects the PyCapsule API should be used instead the new type has a well defined interface for passing typing safety information and a less complicated signature for calling
en
null
2,332
a destructor The sys setfilesystemencoding function was removed because it had a flawed design The random seed function and method now salt string seeds with an sha512 hash function To access the previous version of seed in order to reproduce Python 3 1 sequences set the version argument to 1 random seed s version 1 The previously deprecated string maketrans function has been removed in favor of the static methods bytes maketrans and bytearray maketrans This change solves the confusion around which types were supported by the string module Now str bytes and bytearray each have their own maketrans and translate methods with intermediate translation tables of the appropriate type Contributed by Georg Brandl bpo 5675 The previously deprecated contextlib nested function has been removed in favor of a plain with statement which can accept multiple context managers The latter technique is faster because it is built in and it does a better job finalizing multiple context managers when one of them raises an exception with open mylog txt as infile open a out w as outfile for line in infile if critical in line outfile write line Contributed by Georg Brandl and Mattias Brändström appspot issue 53094 struct pack now only allows bytes for the s string pack code Formerly it would accept text arguments and implicitly encode them to bytes using UTF 8 This was problematic because it made assumptions about the correct encoding and because a variable length encoding can fail when writing to fixed length segment of a structure Code such as struct pack 6sHHBBB GIF87a x y should be rewritten with to use bytes instead of text struct pack 6sHHBBB b GIF87a x y Discovered by David Beazley and fixed by Victor Stinner bpo 10783 The xml etree ElementTree class now raises an xml etree ElementTree ParseError when a parse fails Previously it raised an xml parsers expat ExpatError The new longer str value on floats may break doctests which rely on the old output format In subprocess Popen the default value for close_fds is now True under Unix under Windows it is True if the three standard streams are set to None False otherwise Previously close_fds was always False by default which produced difficult to solve bugs or race conditions when open file descriptors would leak into the child process Support for legacy HTTP 0 9 has been removed from urllib request and http client Such support is still present on the server side in http server Contributed by Antoine Pitrou bpo 10711 SSL sockets in timeout mode now raise socket timeout when a timeout occurs rather than a generic SSLError Contributed by Antoine Pitrou bpo 10272 The misleading functions PyEval_AcquireLock and PyEval_ReleaseLock have been officially deprecated The thread state aware APIs such as PyEval_SaveThread and PyEval_RestoreThread should be used instead Due to security risks asyncore handle_accept has been deprecated and a new function asyncore handle_accepted was added to replace it Contributed by Giampaolo Rodola in bpo 6706 Due to the new GIL implementation PyEval_InitThreads cannot be called before Py_Initialize anymore
en
null
2,333
itertools Functions creating iterators for efficient looping This module implements a number of iterator building blocks inspired by constructs from APL Haskell and SML Each has been recast in a form suitable for Python The module standardizes a core set of fast memory efficient tools that are useful by themselves or in combination Together they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python For instance SML provides a tabulation tool tabulate f which produces a sequence f 0 f 1 The same effect can be achieved in Python by combining map and count to form map f count These tools and their built in counterparts also work well with the high speed functions in the operator module For example the multiplication operator can be mapped across two vectors to form an efficient dot product sum starmap operator mul zip vec1 vec2 strict True Infinite iterators Iterator Arguments Results Example count start step start start step start 2 step count 10 10 11 12 13 14 cycle p p0 p1 plast p0 p1 cycle ABCD A B C D A B C D repeat elem n elem elem elem endlessly or up to n times repeat 10 3 10 10 10 Iterators terminating on the shortest input sequence Iterator Arguments Results Example accumulate p func p0 p0 p1 p0 p1 p2 accumulate 1 2 3 4 5 1 3 6 10 15 batched p n p0 p1 p_n 1 batched ABCDEFG n 3 ABC DEF G chain p q p0 p1 plast q0 q1 chain ABC DEF A B C D E F chain from_iterable iterable p0 p1 plast q0 q1 chain from_iterable ABC DEF A B C D E F compress data selectors d 0 if s 0 d 1 if s 1 compress ABCDEF 1 0 1 0 1 1 A C E F dropwhile predicate seq seq n seq n 1 starting when predicate fails dropwhile lambda x x 5 1 4 6 4 1 6 4 1 filterfalse predicate seq elements of seq where predicate elem fails filterfalse lambda x x 2 range 10 0 2 4 6 8 groupby iterable key sub iterators grouped by value of key v islice seq start stop step elements from seq start stop step islice ABCDEFG 2 None C D E F G pairwise iterable p 0 p 1 p 1 p 2 pairwise ABCDEFG AB BC CD DE EF FG starmap func seq func seq 0 func seq 1 starmap pow 2 5 3 2 10 3 32 9 1000 takewhile predicate seq seq 0 seq 1 until predicate fails takewhile lambda x x 5 1 4 6 4 1 1 4 tee it n it1 it2 itn splits one iterator into n zip_longest p q p 0 q 0 p 1 q 1 zip_longest ABCD xy fillvalue Ax By C D Combinatoric iterators Iterator Arguments Results product p q repeat 1 cartesian product equivalent to a nested for loop permutations p r r length tuples all possible orderings no repeated elements combinations p r r length tuples in sorted order no repeated elements combinations_with_replacement p r r length tuples in sorted order with repeated elements Examples Results product ABCD repeat 2 AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD permutations ABCD 2 AB AC AD BA BC BD CA CB CD DA DB DC combinations ABCD 2 AB AC AD BC BD CD combinations_with_replacement ABCD 2 AA AB AC AD BB BC BD CC CD DD Itertool Functions The following module functions all construct and return iterators Some provide streams of infinite length so they should only be accessed by functions or loops that truncate the stream itertools accumulate iterable func initial None Make an iterator that returns accumulated sums or accumulated results of other binary functions specified via the optional func argument If func is supplied it should be a function of two arguments Elements of the input iterable may be any type that can be accepted as arguments to func For example with the default operation of addition elements may be any addable type including Decimal or Fraction Usually the number of elements output matches the input iterable However if the keyword argument initial is provided the accumulation leads off with the initial value so that the output has one more element than the input iterable Roughly equivalent to def accumulate iterable func operator add initial None Return running totals accumulate 1 2 3 4 5 1 3 6 10 15 accumulate 1 2 3 4 5 initial 100 100 101 103 106 110 115 accumulate 1 2 3 4 5 operator mul 1 2 6 24 120 it iter iterable total initial if init
en
null
2,334
ial is None try total next it except StopIteration return yield total for element in it total func total element yield total There are a number of uses for the func argument It can be set to min for a running minimum max for a running maximum or operator mul for a running product Amortization tables can be built by accumulating interest and applying payments data 3 4 6 2 1 9 0 7 5 8 list accumulate data operator mul running product 3 12 72 144 144 1296 0 0 0 0 list accumulate data max running maximum 3 4 6 6 6 9 9 9 9 9 Amortize a 5 loan of 1000 with 10 annual payments of 90 account_update lambda bal pmt round bal 1 05 pmt list accumulate repeat 90 10 account_update initial 1_000 1000 960 918 874 828 779 728 674 618 559 497 See functools reduce for a similar function that returns only the final accumulated value New in version 3 2 Changed in version 3 3 Added the optional func parameter Changed in version 3 8 Added the optional initial parameter itertools batched iterable n Batch data from the iterable into tuples of length n The last batch may be shorter than n Loops over the input iterable and accumulates data into tuples up to size n The input is consumed lazily just enough to fill a batch The result is yielded as soon as the batch is full or when the input iterable is exhausted flattened_data roses red violets blue sugar sweet unflattened list batched flattened_data 2 unflattened roses red violets blue sugar sweet for batch in batched ABCDEFG 3 print batch A B C D E F G Roughly equivalent to def batched iterable n batched ABCDEFG 3 ABC DEF G if n 1 raise ValueError n must be at least one it iter iterable while batch tuple islice it n yield batch New in version 3 12 itertools chain iterables Make an iterator that returns elements from the first iterable until it is exhausted then proceeds to the next iterable until all of the iterables are exhausted Used for treating consecutive sequences as a single sequence Roughly equivalent to def chain iterables chain ABC DEF A B C D E F for it in iterables for element in it yield element classmethod chain from_iterable iterable Alternate constructor for chain Gets chained inputs from a single iterable argument that is evaluated lazily Roughly equivalent to def from_iterable iterables chain from_iterable ABC DEF A B C D E F for it in iterables for element in it yield element itertools combinations iterable r Return r length subsequences of elements from the input iterable The combination tuples are emitted in lexicographic ordering according to the order of the input iterable So if the input iterable is sorted the output tuples will be produced in sorted order Elements are treated as unique based on their position not on their value So if the input elements are unique there will be no repeated values in each combination Roughly equivalent to def combinations iterable r combinations ABCD 2 AB AC AD BC BD CD combinations range 4 3 012 013 023 123 pool tuple iterable n len pool if r n return indices list range r yield tuple pool i for i in indices while True for i in reversed range r if indices i i n r break else return indices i 1 for j in range i 1 r indices j indices j 1 1 yield tuple pool i for i in indices The code for combinations can be also expressed as a subsequence of permutations after filtering entries where the elements are not in sorted order according to their position in the input pool def combinations iterable r pool tuple iterable n len pool for indices in permutations range n r if sorted indices list indices yield tuple pool i for i in indices The number of items returned is n r n r when 0 r n or zero when r n itertools combinations_with_replacement iterable r Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once The combination tuples are emitted in lexicographic ordering according to the order of the input iterable So if the input iterable is sorted the output tuples will be produced in sorted order Elements are treated as unique based on their position not on their value So if the input eleme
en
null
2,335
nts are unique the generated combinations will also be unique Roughly equivalent to def combinations_with_replacement iterable r combinations_with_replacement ABC 2 AA AB AC BB BC CC pool tuple iterable n len pool if not n and r return indices 0 r yield tuple pool i for i in indices while True for i in reversed range r if indices i n 1 break else return indices i indices i 1 r i yield tuple pool i for i in indices The code for combinations_with_replacement can be also expressed as a subsequence of product after filtering entries where the elements are not in sorted order according to their position in the input pool def combinations_with_replacement iterable r pool tuple iterable n len pool for indices in product range n repeat r if sorted indices list indices yield tuple pool i for i in indices The number of items returned is n r 1 r n 1 when n 0 New in version 3 1 itertools compress data selectors Make an iterator that filters elements from data returning only those that have a corresponding element in selectors that evaluates to True Stops when either the data or selectors iterables has been exhausted Roughly equivalent to def compress data selectors compress ABCDEF 1 0 1 0 1 1 A C E F return d for d s in zip data selectors if s New in version 3 1 itertools count start 0 step 1 Make an iterator that returns evenly spaced values starting with number start Often used as an argument to map to generate consecutive data points Also used with zip to add sequence numbers Roughly equivalent to def count start 0 step 1 count 10 10 11 12 13 14 count 2 5 0 5 2 5 3 0 3 5 n start while True yield n n step When counting with floating point numbers better accuracy can sometimes be achieved by substituting multiplicative code such as start step i for i in count Changed in version 3 1 Added step argument and allowed non integer arguments itertools cycle iterable Make an iterator returning elements from the iterable and saving a copy of each When the iterable is exhausted return elements from the saved copy Repeats indefinitely Roughly equivalent to def cycle iterable cycle ABCD A B C D A B C D A B C D saved for element in iterable yield element saved append element while saved for element in saved yield element Note this member of the toolkit may require significant auxiliary storage depending on the length of the iterable itertools dropwhile predicate iterable Make an iterator that drops elements from the iterable as long as the predicate is true afterwards returns every element Note the iterator does not produce any output until the predicate first becomes false so it may have a lengthy start up time Roughly equivalent to def dropwhile predicate iterable dropwhile lambda x x 5 1 4 6 4 1 6 4 1 iterable iter iterable for x in iterable if not predicate x yield x break for x in iterable yield x itertools filterfalse predicate iterable Make an iterator that filters elements from iterable returning only those for which the predicate is false If predicate is None return the items that are false Roughly equivalent to def filterfalse predicate iterable filterfalse lambda x x 2 range 10 0 2 4 6 8 if predicate is None predicate bool for x in iterable if not predicate x yield x itertools groupby iterable key None Make an iterator that returns consecutive keys and groups from the iterable The key is a function computing a key value for each element If not specified or is None key defaults to an identity function and returns the element unchanged Generally the iterable needs to already be sorted on the same key function The operation of groupby is similar to the uniq filter in Unix It generates a break or new group every time the value of the key function changes which is why it is usually necessary to have sorted the data using the same key function That behavior differs from SQL s GROUP BY which aggregates common elements regardless of their input order The returned group is itself an iterator that shares the underlying iterable with groupby Because the source is shared when the groupby object is advanced the previous group is no longer visible
en
null
2,336
So if that data is needed later it should be stored as a list groups uniquekeys data sorted data key keyfunc for k g in groupby data keyfunc groups append list g Store group iterator as a list uniquekeys append k groupby is roughly equivalent to class groupby k for k g in groupby AAAABBBCCDAABBB A B C D A B list g for k g in groupby AAAABBBCCD AAAA BBB CC D def __init__ self iterable key None if key is None key lambda x x self keyfunc key self it iter iterable self tgtkey self currkey self currvalue object def __iter__ self return self def __next__ self self id object while self currkey self tgtkey self currvalue next self it Exit on StopIteration self currkey self keyfunc self currvalue self tgtkey self currkey return self currkey self _grouper self tgtkey self id def _grouper self tgtkey id while self id is id and self currkey tgtkey yield self currvalue try self currvalue next self it except StopIteration return self currkey self keyfunc self currvalue itertools islice iterable stop itertools islice iterable start stop step Make an iterator that returns selected elements from the iterable If start is non zero then elements from the iterable are skipped until start is reached Afterward elements are returned consecutively unless step is set higher than one which results in items being skipped If stop is None then iteration continues until the iterator is exhausted if at all otherwise it stops at the specified position If start is None then iteration starts at zero If step is None then the step defaults to one Unlike regular slicing islice does not support negative values for start stop or step Can be used to extract related fields from data where the internal structure has been flattened for example a multi line report may list a name field on every third line Roughly equivalent to def islice iterable args islice ABCDEFG 2 A B islice ABCDEFG 2 4 C D islice ABCDEFG 2 None C D E F G islice ABCDEFG 0 None 2 A C E G s slice args start stop step s start or 0 s stop or sys maxsize s step or 1 it iter range start stop step try nexti next it except StopIteration Consume iterable up to the start position for i element in zip range start iterable pass return try for i element in enumerate iterable if i nexti yield element nexti next it except StopIteration Consume to stop for i element in zip range i 1 stop iterable pass itertools pairwise iterable Return successive overlapping pairs taken from the input iterable The number of 2 tuples in the output iterator will be one fewer than the number of inputs It will be empty if the input iterable has fewer than two values Roughly equivalent to def pairwise iterable pairwise ABCDEFG AB BC CD DE EF FG a b tee iterable next b None return zip a b New in version 3 10 itertools permutations iterable r None Return successive r length permutations of elements in the iterable If r is not specified or is None then r defaults to the length of the iterable and all possible full length permutations are generated The permutation tuples are emitted in lexicographic order according to the order of the input iterable So if the input iterable is sorted the output tuples will be produced in sorted order Elements are treated as unique based on their position not on their value So if the input elements are unique there will be no repeated values within a permutation Roughly equivalent to def permutations iterable r None permutations ABCD 2 AB AC AD BA BC BD CA CB CD DA DB DC permutations range 3 012 021 102 120 201 210 pool tuple iterable n len pool r n if r is None else r if r n return indices list range n cycles list range n n r 1 yield tuple pool i for i in indices r while n for i in reversed range r cycles i 1 if cycles i 0 indices i indices i 1 indices i i 1 cycles i n i else j cycles i indices i indices j indices j indices i yield tuple pool i for i in indices r break else return The code for permutations can be also expressed as a subsequence of product filtered to exclude entries with repeated elements those from the same position in the input pool def permutations iterable r None pool tuple iterab
en
null
2,337
le n len pool r n if r is None else r for indices in product range n repeat r if len set indices r yield tuple pool i for i in indices The number of items returned is n n r when 0 r n or zero when r n itertools product iterables repeat 1 Cartesian product of input iterables Roughly equivalent to nested for loops in a generator expression For example product A B returns the same as x y for x in A for y in B The nested loops cycle like an odometer with the rightmost element advancing on every iteration This pattern creates a lexicographic ordering so that if the input s iterables are sorted the product tuples are emitted in sorted order To compute the product of an iterable with itself specify the number of repetitions with the optional repeat keyword argument For example product A repeat 4 means the same as product A A A A This function is roughly equivalent to the following code except that the actual implementation does not build up intermediate results in memory def product args repeat 1 product ABCD xy Ax Ay Bx By Cx Cy Dx Dy product range 2 repeat 3 000 001 010 011 100 101 110 111 pools tuple pool for pool in args repeat result for pool in pools result x y for x in result for y in pool for prod in result yield tuple prod Before product runs it completely consumes the input iterables keeping pools of values in memory to generate the products Accordingly it is only useful with finite inputs itertools repeat object times Make an iterator that returns object over and over again Runs indefinitely unless the times argument is specified Roughly equivalent to def repeat object times None repeat 10 3 10 10 10 if times is None while True yield object else for i in range times yield object A common use for repeat is to supply a stream of constant values to map or zip list map pow range 10 repeat 2 0 1 4 9 16 25 36 49 64 81 itertools starmap function iterable Make an iterator that computes the function using arguments obtained from the iterable Used instead of map when argument parameters are already grouped in tuples from a single iterable when the data has been pre zipped The difference between map and starmap parallels the distinction between function a b and function c Roughly equivalent to def starmap function iterable starmap pow 2 5 3 2 10 3 32 9 1000 for args in iterable yield function args itertools takewhile predicate iterable Make an iterator that returns elements from the iterable as long as the predicate is true Roughly equivalent to def takewhile predicate iterable takewhile lambda x x 5 1 4 6 4 1 1 4 for x in iterable if predicate x yield x else break Note the element that first fails the predicate condition is consumed from the input iterator and there is no way to access it This could be an issue if an application wants to further consume the input iterator after takewhile has been run to exhaustion To work around this problem consider using more iterools before_and_after instead itertools tee iterable n 2 Return n independent iterators from a single iterable The following Python code helps explain what tee does although the actual implementation is more complex and uses only a single underlying FIFO first in first out queue def tee iterable n 2 it iter iterable deques collections deque for i in range n def gen mydeque while True if not mydeque when the local deque is empty try newval next it fetch a new value and except StopIteration return for d in deques load it to all the deques d append newval yield mydeque popleft return tuple gen d for d in deques Once a tee has been created the original iterable should not be used anywhere else otherwise the iterable could get advanced without the tee objects being informed tee iterators are not threadsafe A RuntimeError may be raised when simultaneously using iterators returned by the same tee call even if the original iterable is threadsafe This itertool may require significant auxiliary storage depending on how much temporary data needs to be stored In general if one iterator uses most or all of the data before another iterator starts it is faster to use list instead
en
null
2,338
of tee itertools zip_longest iterables fillvalue None Make an iterator that aggregates elements from each of the iterables If the iterables are of uneven length missing values are filled in with fillvalue Iteration continues until the longest iterable is exhausted Roughly equivalent to def zip_longest args fillvalue None zip_longest ABCD xy fillvalue Ax By C D iterators iter it for it in args num_active len iterators if not num_active return while True values for i it in enumerate iterators try value next it except StopIteration num_active 1 if not num_active return iterators i repeat fillvalue value fillvalue values append value yield tuple values If one of the iterables is potentially infinite then the zip_longest function should be wrapped with something that limits the number of calls for example islice or takewhile If not specified fillvalue defaults to None Itertools Recipes This section shows recipes for creating an extended toolset using the existing itertools as building blocks The primary purpose of the itertools recipes is educational The recipes show various ways of thinking about individual tools for example that chain from_iterable is related to the concept of flattening The recipes also give ideas about ways that the tools can be combined for example how starmap and repeat can work together The recipes also show patterns for using itertools with the operator and collections modules as well as with the built in itertools such as map filter reversed and enumerate A secondary purpose of the recipes is to serve as an incubator The accumulate compress and pairwise itertools started out as recipes Currently the sliding_window iter_index and sieve recipes are being tested to see whether they prove their worth Substantially all of these recipes and many many others can be installed from the more itertools project found on the Python Package Index python m pip install more itertools Many of the recipes offer the same high performance as the underlying toolset Superior memory performance is kept by processing elements one at a time rather than bringing the whole iterable into memory all at once Code volume is kept small by linking the tools together in a functional style High speed is retained by preferring vectorized building blocks over the use of for loops and generators which incur interpreter overhead import collections import functools import math import operator import random def take n iterable Return first n items of the iterable as a list return list islice iterable n def prepend value iterable Prepend a single value in front of an iterable prepend 1 2 3 4 1 2 3 4 return chain value iterable def tabulate function start 0 Return function 0 function 1 return map function count start def repeatfunc func times None args Repeat calls to func with specified arguments Example repeatfunc random random if times is None return starmap func repeat args return starmap func repeat args times def flatten list_of_lists Flatten one level of nesting return chain from_iterable list_of_lists def ncycles iterable n Returns the sequence elements n times return chain from_iterable repeat tuple iterable n def tail n iterable Return an iterator over the last n items tail 3 ABCDEFG E F G return iter collections deque iterable maxlen n def consume iterator n None Advance the iterator n steps ahead If n is None consume entirely Use functions that consume iterators at C speed if n is None feed the entire iterator into a zero length deque collections deque iterator maxlen 0 else advance to the empty slice starting at position n next islice iterator n n None def nth iterable n default None Returns the nth item or a default value return next islice iterable n None default def quantify iterable predicate bool Given a predicate that returns True or False count the True results return sum map predicate iterable def first_true iterable default False predicate None Returns the first true value or the default if there is no true value first_true a b c x a or b or c or x first_true a b x f a if f a else b if f b else x return next filter predi
en
null
2,339
cate iterable default def all_equal iterable key None Returns True if all the elements are equal to each other return len take 2 groupby iterable key 1 def unique_justseen iterable key None List unique elements preserving order Remember only the element just seen unique_justseen AAAABBBCCDAABBB A B C D A B unique_justseen ABBcCAD str casefold A B c A D if key is None return map operator itemgetter 0 groupby iterable return map next map operator itemgetter 1 groupby iterable key def unique_everseen iterable key None List unique elements preserving order Remember all elements ever seen unique_everseen AAAABBBCCDAABBB A B C D unique_everseen ABBcCAD str casefold A B c D seen set if key is None for element in filterfalse seen __contains__ iterable seen add element yield element else for element in iterable k key element if k not in seen seen add k yield element def sliding_window iterable n Collect data into overlapping fixed length chunks or blocks sliding_window ABCDEFG 4 ABCD BCDE CDEF DEFG it iter iterable window collections deque islice it n 1 maxlen n for x in it window append x yield tuple window def grouper iterable n incomplete fill fillvalue None Collect data into non overlapping fixed length chunks or blocks grouper ABCDEFG 3 fillvalue x ABC DEF Gxx grouper ABCDEFG 3 incomplete strict ABC DEF ValueError grouper ABCDEFG 3 incomplete ignore ABC DEF iterators iter iterable n match incomplete case fill return zip_longest iterators fillvalue fillvalue case strict return zip iterators strict True case ignore return zip iterators case _ raise ValueError Expected fill strict or ignore def roundrobin iterables Visit input iterables in a cycle until each is exhausted roundrobin ABC D EF A D E B F C Algorithm credited to George Sakkis iterators map iter iterables for num_active in range len iterables 0 1 iterators cycle islice iterators num_active yield from map next iterators def partition predicate iterable Partition entries into false entries and true entries If predicate is slow consider wrapping it with functools lru_cache partition is_odd range 10 0 2 4 6 8 and 1 3 5 7 9 t1 t2 tee iterable return filterfalse predicate t1 filter predicate t2 def subslices seq Return all contiguous non empty subslices of a sequence subslices ABCD A AB ABC ABCD B BC BCD C CD D slices starmap slice combinations range len seq 1 2 return map operator getitem repeat seq slices def iter_index iterable value start 0 stop None Return indices where a value occurs in a sequence or iterable iter_index AABCADEAF A 0 1 4 7 seq_index getattr iterable index None if seq_index is None Path for general iterables it islice iterable start stop for i element in enumerate it start if element is value or element value yield i else Path for sequences with an index method stop len iterable if stop is None else stop i start try while True yield i seq_index value i stop i 1 except ValueError pass def iter_except func exception first None Call a function repeatedly until an exception is raised Converts a call until exception interface to an iterator interface iter_except d popitem KeyError non blocking dictionary iterator try if first is not None yield first while True yield func except exception pass The following recipes have a more mathematical flavor def powerset iterable powerset 1 2 3 1 2 3 1 2 1 3 2 3 1 2 3 s list iterable return chain from_iterable combinations s r for r in range len s 1 def sum_of_squares iterable Add up the squares of the input values sum_of_squares 10 20 30 1400 return math sumprod tee iterable def reshape matrix cols Reshape a 2 D matrix to have a given number of columns reshape 0 1 2 3 4 5 3 0 1 2 3 4 5 return batched chain from_iterable matrix cols def transpose matrix Swap the rows and columns of a 2 D matrix transpose 1 2 3 11 22 33 1 11 2 22 3 33 return zip matrix strict True def matmul m1 m2 Multiply two matrices matmul 7 5 3 5 2 5 7 9 49 80 41 60 n len m2 0 return batched starmap math sumprod product m1 transpose m2 n def convolve signal kernel Discrete linear convolution of two iterables Equivalent to polynomial multiplication C
en
null
2,340
onvolutions are mathematically commutative however the inputs are evaluated differently The signal is consumed lazily and can be infinite The kernel is fully consumed before the calculations begin Article https betterexplained com articles intuitive convolution Video https www youtube com watch v KuXjwB4LzSA convolve 1 1 20 1 3 1 4 17 60 convolve data 0 25 0 25 0 25 0 25 Moving average blur convolve data 1 2 0 1 2 1st derivative estimate convolve data 1 2 1 2nd derivative estimate kernel tuple kernel 1 n len kernel padded_signal chain repeat 0 n 1 signal repeat 0 n 1 windowed_signal sliding_window padded_signal n return map math sumprod repeat kernel windowed_signal def polynomial_from_roots roots Compute a polynomial s coefficients from its roots x 5 x 4 x 3 expands to x³ 4x² 17x 60 polynomial_from_roots 5 4 3 1 4 17 60 factors zip repeat 1 map operator neg roots return list functools reduce convolve factors 1 def polynomial_eval coefficients x Evaluate a polynomial at a specific value Computes with better numeric stability than Horner s method Evaluate x³ 4x² 17x 60 at x 5 polynomial_eval 1 4 17 60 x 5 0 n len coefficients if not n return type x 0 powers map pow repeat x reversed range n return math sumprod coefficients powers def polynomial_derivative coefficients Compute the first derivative of a polynomial f x x³ 4x² 17x 60 f x 3x² 8x 17 polynomial_derivative 1 4 17 60 3 8 17 n len coefficients powers reversed range 1 n return list map operator mul coefficients powers def sieve n Primes less than n sieve 30 2 3 5 7 11 13 17 19 23 29 if n 2 yield 2 start 3 data bytearray 0 1 n 2 limit math isqrt n 1 for p in iter_index data 1 start limit yield from iter_index data 1 start p p data p p n p p bytes len range p p n p p start p p yield from iter_index data 1 start def factor n Prime factors of n factor 99 3 3 11 factor 1_000_000_000_000_007 47 59 360620266859 factor 1_000_000_000_000_403 1000000000000403 for prime in sieve math isqrt n 1 while not n prime yield prime n prime if n 1 return if n 1 yield n def totient n Count of natural numbers up to n that are coprime to n https mathworld wolfram com TotientFunction html totient 12 4 because len 1 5 7 11 4 for p in unique_justseen factor n n n p return n
en
null
2,341
What s New In Python 3 7 Editor Elvis Pranskevichus elvis magic io This article explains the new features in Python 3 7 compared to 3 6 Python 3 7 was released on June 27 2018 For full details see the changelog Summary Release Highlights New syntax features PEP 563 postponed evaluation of type annotations Backwards incompatible syntax changes async and await are now reserved keywords New library modules contextvars PEP 567 Context Variables dataclasses PEP 557 Data Classes importlib resources New built in features PEP 553 the new breakpoint function Python data model improvements PEP 562 customization of access to module attributes PEP 560 core support for typing module and generic types the insertion order preservation nature of dict objects has been declared to be an official part of the Python language spec Significant improvements in the standard library The asyncio module has received new features significant usability and performance improvements The time module gained support for functions with nanosecond resolution CPython implementation improvements Avoiding the use of ASCII as a default text encoding PEP 538 legacy C locale coercion PEP 540 forced UTF 8 runtime mode PEP 552 deterministic pycs New Python Development Mode PEP 565 improved DeprecationWarning handling C API improvements PEP 539 new C API for thread local storage Documentation improvements PEP 545 Python documentation translations New documentation translations Japanese French and Korean This release features notable performance improvements in many areas The Optimizations section lists them in detail For a list of changes that may affect compatibility with previous Python releases please refer to the Porting to Python 3 7 section New Features PEP 563 Postponed Evaluation of Annotations The advent of type hints in Python uncovered two glaring usability issues with the functionality of annotations added in PEP 3107 and refined further in PEP 526 annotations could only use names which were already available in the current scope in other words they didn t support forward references of any kind and annotating source code had adverse effects on startup time of Python programs Both of these issues are fixed by postponing the evaluation of annotations Instead of compiling code which executes expressions in annotations at their definition time the compiler stores the annotation in a string form equivalent to the AST of the expression in question If needed annotations can be resolved at runtime using typing get_type_hints In the common case where this is not required the annotations are cheaper to store since short strings are interned by the interpreter and make startup time faster Usability wise annotations now support forward references making the following syntax valid class C classmethod def from_string cls source str C def validate_b self obj B bool class B Since this change breaks compatibility the new behavior needs to be enabled on a per module basis in Python 3 7 using a __future__ import from __future__ import annotations It will become the default in Python 3 10 See also PEP 563 Postponed evaluation of annotations PEP written and implemented by Łukasz Langa PEP 538 Legacy C Locale Coercion An ongoing challenge within the Python 3 series has been determining a sensible default strategy for handling the 7 bit ASCII text encoding assumption currently implied by the use of the default C or POSIX locale on non Windows platforms PEP 538 updates the default interpreter command line interface to automatically coerce that locale to an available UTF 8 based locale as described in the documentation of the new PYTHONCOERCECLOCALE environment variable Automatically setting LC_CTYPE this way means that both the core interpreter and locale aware C extensions such as readline will assume the use of UTF 8 as the default text encoding rather than ASCII The platform support definition in PEP 11 has also been updated to limit full text handling support to suitably configured non ASCII based locales As part of this change the default error handler for stdin and stdou
en
null
2,342
t is now surrogateescape rather than strict when using any of the defined coercion target locales currently C UTF 8 C utf8 and UTF 8 The default error handler for stderr continues to be backslashreplace regardless of locale Locale coercion is silent by default but to assist in debugging potentially locale related integration problems explicit warnings emitted directly on stderr can be requested by setting PYTHONCOERCECLOCALE warn This setting will also cause the Python runtime to emit a warning if the legacy C locale remains active when the core interpreter is initialized While PEP 538 s locale coercion has the benefit of also affecting extension modules such as GNU readline as well as child processes including those running non Python applications and older versions of Python it has the downside of requiring that a suitable target locale be present on the running system To better handle the case where no suitable target locale is available as occurs on RHEL CentOS 7 for example Python 3 7 also implements PEP 540 Forced UTF 8 Runtime Mode See also PEP 538 Coercing the legacy C locale to a UTF 8 based locale PEP written and implemented by Nick Coghlan PEP 540 Forced UTF 8 Runtime Mode The new X utf8 command line option and PYTHONUTF8 environment variable can be used to enable the Python UTF 8 Mode When in UTF 8 mode CPython ignores the locale settings and uses the UTF 8 encoding by default The error handlers for sys stdin and sys stdout streams are set to surrogateescape The forced UTF 8 mode can be used to change the text handling behavior in an embedded Python interpreter without changing the locale settings of an embedding application While PEP 540 s UTF 8 mode has the benefit of working regardless of which locales are available on the running system it has the downside of having no effect on extension modules such as GNU readline child processes running non Python applications and child processes running older versions of Python To reduce the risk of corrupting text data when communicating with such components Python 3 7 also implements PEP 540 Forced UTF 8 Runtime Mode The UTF 8 mode is enabled by default when the locale is C or POSIX and the PEP 538 locale coercion feature fails to change it to a UTF 8 based alternative whether that failure is due to PYTHONCOERCECLOCALE 0 being set LC_ALL being set or the lack of a suitable target locale See also PEP 540 Add a new UTF 8 mode PEP written and implemented by Victor Stinner PEP 553 Built in breakpoint Python 3 7 includes the new built in breakpoint function as an easy and consistent way to enter the Python debugger Built in breakpoint calls sys breakpointhook By default the latter imports pdb and then calls pdb set_trace but by binding sys breakpointhook to the function of your choosing breakpoint can enter any debugger Additionally the environment variable PYTHONBREAKPOINT can be set to the callable of your debugger of choice Set PYTHONBREAKPOINT 0 to completely disable built in breakpoint See also PEP 553 Built in breakpoint PEP written and implemented by Barry Warsaw PEP 539 New C API for Thread Local Storage While Python provides a C API for thread local storage support the existing Thread Local Storage TLS API has used int to represent TLS keys across all platforms This has not generally been a problem for officially support platforms but that is neither POSIX compliant nor portable in any practical sense PEP 539 changes this by providing a new Thread Specific Storage TSS API to CPython which supersedes use of the existing TLS API within the CPython interpreter while deprecating the existing API The TSS API uses a new type Py_tss_t instead of int to represent TSS keys an opaque type the definition of which may depend on the underlying TLS implementation Therefore this will allow to build CPython on platforms where the native TLS key is defined in a way that cannot be safely cast to int Note that on platforms where the native TLS key is defined in a way that cannot be safely cast to int all functions of the existing TLS API will be no op and immediately return failu
en
null
2,343
re This indicates clearly that the old API is not supported on platforms where it cannot be used reliably and that no effort will be made to add such support See also PEP 539 A New C API for Thread Local Storage in CPython PEP written by Erik M Bray implementation by Masayuki Yamamoto PEP 562 Customization of Access to Module Attributes Python 3 7 allows defining __getattr__ on modules and will call it whenever a module attribute is otherwise not found Defining __dir__ on modules is now also allowed A typical example of where this may be useful is module attribute deprecation and lazy loading See also PEP 562 Module __getattr__ and __dir__ PEP written and implemented by Ivan Levkivskyi PEP 564 New Time Functions With Nanosecond Resolution The resolution of clocks in modern systems can exceed the limited precision of a floating point number returned by the time time function and its variants To avoid loss of precision PEP 564 adds six new nanosecond variants of the existing timer functions to the time module time clock_gettime_ns time clock_settime_ns time monotonic_ns time perf_counter_ns time process_time_ns time time_ns The new functions return the number of nanoseconds as an integer value Measurements show that on Linux and Windows the resolution of time time_ns is approximately 3 times better than that of time time See also PEP 564 Add new time functions with nanosecond resolution PEP written and implemented by Victor Stinner PEP 565 Show DeprecationWarning in __main__ The default handling of DeprecationWarning has been changed such that these warnings are once more shown by default but only when the code triggering them is running directly in the __main__ module As a result developers of single file scripts and those using Python interactively should once again start seeing deprecation warnings for the APIs they use but deprecation warnings triggered by imported application library and framework modules will continue to be hidden by default As a result of this change the standard library now allows developers to choose between three different deprecation warning behaviours FutureWarning always displayed by default recommended for warnings intended to be seen by application end users e g for deprecated application configuration settings DeprecationWarning displayed by default only in __main__ and when running tests recommended for warnings intended to be seen by other Python developers where a version upgrade may result in changed behaviour or an error PendingDeprecationWarning displayed by default only when running tests intended for cases where a future version upgrade will change the warning category to DeprecationWarning or FutureWarning Previously both DeprecationWarning and PendingDeprecationWarning were only visible when running tests which meant that developers primarily writing single file scripts or using Python interactively could be surprised by breaking changes in the APIs they used See also PEP 565 Show DeprecationWarning in __main__ PEP written and implemented by Nick Coghlan PEP 560 Core Support for typing module and Generic Types Initially PEP 484 was designed in such way that it would not introduce any changes to the core CPython interpreter Now type hints and the typing module are extensively used by the community so this restriction is removed The PEP introduces two special methods __class_getitem__ and __mro_entries__ these methods are now used by most classes and special constructs in typing As a result the speed of various operations with types increased up to 7 times the generic types can be used without metaclass conflicts and several long standing bugs in typing module are fixed See also PEP 560 Core support for typing module and generic types PEP written and implemented by Ivan Levkivskyi PEP 552 Hash based pyc Files Python has traditionally checked the up to dateness of bytecode cache files i e pyc files by comparing the source metadata last modified timestamp and size with source metadata saved in the cache file header when it was generated While effective this invalidation method has its
en
null
2,344
drawbacks When filesystem timestamps are too coarse Python can miss source updates leading to user confusion Additionally having a timestamp in the cache file is problematic for build reproducibility and content based build systems PEP 552 extends the pyc format to allow the hash of the source file to be used for invalidation instead of the source timestamp Such pyc files are called hash based By default Python still uses timestamp based invalidation and does not generate hash based pyc files at runtime Hash based pyc files may be generated with py_compile or compileall Hash based pyc files come in two variants checked and unchecked Python validates checked hash based pyc files against the corresponding source files at runtime but doesn t do so for unchecked hash based pycs Unchecked hash based pyc files are a useful performance optimization for environments where a system external to Python e g the build system is responsible for keeping pyc files up to date See Cached bytecode invalidation for more information See also PEP 552 Deterministic pycs PEP written and implemented by Benjamin Peterson PEP 545 Python Documentation Translations PEP 545 describes the process of creating and maintaining Python documentation translations Three new translations have been added Japanese https docs python org ja French https docs python org fr Korean https docs python org ko See also PEP 545 Python Documentation Translations PEP written and implemented by Julien Palard Inada Naoki and Victor Stinner Python Development Mode X dev The new X dev command line option or the new PYTHONDEVMODE environment variable can be used to enable Python Development Mode When in development mode Python performs additional runtime checks that are too expensive to be enabled by default See Python Development Mode documentation for the full description Other Language Changes An await expression and comprehensions containing an async for clause were illegal in the expressions in formatted string literals due to a problem with the implementation In Python 3 7 this restriction was lifted More than 255 arguments can now be passed to a function and a function can now have more than 255 parameters Contributed by Serhiy Storchaka in bpo 12844 and bpo 18896 bytes fromhex and bytearray fromhex now ignore all ASCII whitespace not only spaces Contributed by Robert Xiao in bpo 28927 str bytes and bytearray gained support for the new isascii method which can be used to test if a string or bytes contain only the ASCII characters Contributed by INADA Naoki in bpo 32677 ImportError now displays module name and module __file__ path when from import fails Contributed by Matthias Bussonnier in bpo 29546 Circular imports involving absolute imports with binding a submodule to a name are now supported Contributed by Serhiy Storchaka in bpo 30024 object __format__ x is now equivalent to str x rather than format str self Contributed by Serhiy Storchaka in bpo 28974 In order to better support dynamic creation of stack traces types TracebackType can now be instantiated from Python code and the tb_next attribute on tracebacks is now writable Contributed by Nathaniel J Smith in bpo 30579 When using the m switch sys path 0 is now eagerly expanded to the full starting directory path rather than being left as the empty directory which allows imports from the current working directory at the time when an import occurs Contributed by Nick Coghlan in bpo 33053 The new X importtime option or the PYTHONPROFILEIMPORTTIME environment variable can be used to show the timing of each module import Contributed by Inada Naoki in bpo 31415 New Modules contextvars The new contextvars module and a set of new C APIs introduce support for context variables Context variables are conceptually similar to thread local variables Unlike TLS context variables support asynchronous code correctly The asyncio and decimal modules have been updated to use and support context variables out of the box Particularly the active decimal context is now stored in a context variable which allows decimal operations to work
en
null
2,345
with the correct context in asynchronous code See also PEP 567 Context Variables PEP written and implemented by Yury Selivanov dataclasses The new dataclass decorator provides a way to declare data classes A data class describes its attributes using class variable annotations Its constructor and other magic methods such as __repr__ __eq__ and __hash__ are generated automatically Example dataclass class Point x float y float z float 0 0 p Point 1 5 2 5 print p produces Point x 1 5 y 2 5 z 0 0 See also PEP 557 Data Classes PEP written and implemented by Eric V Smith importlib resources The new importlib resources module provides several new APIs and one new ABC for access to opening and reading resources inside packages Resources are roughly similar to files inside packages but they needn t be actual files on the physical file system Module loaders can provide a get_resource_reader function which returns a importlib abc ResourceReader instance to support this new API Built in file path loaders and zip file loaders both support this Contributed by Barry Warsaw and Brett Cannon in bpo 32248 See also importlib_resources a PyPI backport for earlier Python versions Improved Modules argparse The new ArgumentParser parse_intermixed_args method allows intermixing options and positional arguments Contributed by paul j3 in bpo 14191 asyncio The asyncio module has received many new features usability and performance improvements Notable changes include The new provisional asyncio run function can be used to run a coroutine from synchronous code by automatically creating and destroying the event loop Contributed by Yury Selivanov in bpo 32314 asyncio gained support for contextvars loop call_soon loop call_soon_threadsafe loop call_later loop call_at and Future add_done_callback have a new optional keyword only context parameter Tasks now track their context automatically See PEP 567 for more details Contributed by Yury Selivanov in bpo 32436 The new asyncio create_task function has been added as a shortcut to asyncio get_event_loop create_task Contributed by Andrew Svetlov in bpo 32311 The new loop start_tls method can be used to upgrade an existing connection to TLS Contributed by Yury Selivanov in bpo 23749 The new loop sock_recv_into method allows reading data from a socket directly into a provided buffer making it possible to reduce data copies Contributed by Antoine Pitrou in bpo 31819 The new asyncio current_task function returns the currently running Task instance and the new asyncio all_tasks function returns a set of all existing Task instances in a given loop The Task current_task and Task all_tasks methods have been deprecated Contributed by Andrew Svetlov in bpo 32250 The new provisional BufferedProtocol class allows implementing streaming protocols with manual control over the receive buffer Contributed by Yury Selivanov in bpo 32251 The new asyncio get_running_loop function returns the currently running loop and raises a RuntimeError if no loop is running This is in contrast with asyncio get_event_loop which will create a new event loop if none is running Contributed by Yury Selivanov in bpo 32269 The new StreamWriter wait_closed coroutine method allows waiting until the stream writer is closed The new StreamWriter is_closing method can be used to determine if the writer is closing Contributed by Andrew Svetlov in bpo 32391 The new loop sock_sendfile coroutine method allows sending files using os sendfile when possible Contributed by Andrew Svetlov in bpo 32410 The new Future get_loop and Task get_loop methods return the instance of the loop on which a task or a future were created Server get_loop allows doing the same for asyncio Server objects Contributed by Yury Selivanov in bpo 32415 and Srinivas Reddy Thatiparthy in bpo 32418 It is now possible to control how instances of asyncio Server begin serving Previously the server would start serving immediately when created The new start_serving keyword argument to loop create_server and loop create_unix_server as well as Server start_serving and Server serve_forever can be
en
null
2,346
used to decouple server instantiation and serving The new Server is_serving method returns True if the server is serving Server objects are now asynchronous context managers srv await loop create_server async with srv some code At this point srv is closed and no longer accepts new connections Contributed by Yury Selivanov in bpo 32662 Callback objects returned by loop call_later gained the new when method which returns an absolute scheduled callback timestamp Contributed by Andrew Svetlov in bpo 32741 The loop create_datagram_endpoint method gained support for Unix sockets Contributed by Quentin Dawans in bpo 31245 The asyncio open_connection asyncio start_server functions loop create_connection loop create_server loop create_accepted_socket methods and their corresponding UNIX socket variants now accept the ssl_handshake_timeout keyword argument Contributed by Neil Aspinall in bpo 29970 The new Handle cancelled method returns True if the callback was cancelled Contributed by Marat Sharafutdinov in bpo 31943 The asyncio source has been converted to use the async await syntax Contributed by Andrew Svetlov in bpo 32193 The new ReadTransport is_reading method can be used to determine the reading state of the transport Additionally calls to ReadTransport resume_reading and ReadTransport pause_reading are now idempotent Contributed by Yury Selivanov in bpo 32356 Loop methods which accept socket paths now support passing path like objects Contributed by Yury Selivanov in bpo 32066 In asyncio TCP sockets on Linux are now created with TCP_NODELAY flag set by default Contributed by Yury Selivanov and Victor Stinner in bpo 27456 Exceptions occurring in cancelled tasks are no longer logged Contributed by Yury Selivanov in bpo 30508 New WindowsSelectorEventLoopPolicy and WindowsProactorEventLoopPolicy classes Contributed by Yury Selivanov in bpo 33792 Several asyncio APIs have been deprecated binascii The b2a_uu function now accepts an optional backtick keyword argument When it s true zeros are represented by instead of spaces Contributed by Xiang Zhang in bpo 30103 calendar The HTMLCalendar class has new class attributes which ease the customization of CSS classes in the produced HTML calendar Contributed by Oz Tiram in bpo 30095 collections collections namedtuple now supports default values Contributed by Raymond Hettinger in bpo 32320 compileall compileall compile_dir learned the new invalidation_mode parameter which can be used to enable hash based pyc invalidation The invalidation mode can also be specified on the command line using the new invalidation mode argument Contributed by Benjamin Peterson in bpo 31650 concurrent futures ProcessPoolExecutor and ThreadPoolExecutor now support the new initializer and initargs constructor arguments Contributed by Antoine Pitrou in bpo 21423 The ProcessPoolExecutor can now take the multiprocessing context via the new mp_context argument Contributed by Thomas Moreau in bpo 31540 contextlib The new nullcontext is a simpler and faster no op context manager than ExitStack Contributed by Jesse Bakker in bpo 10049 The new asynccontextmanager AbstractAsyncContextManager and AsyncExitStack have been added to complement their synchronous counterparts Contributed by Jelle Zijlstra in bpo 29679 and bpo 30241 and by Alexander Mohr and Ilya Kulakov in bpo 29302 cProfile The cProfile command line now accepts m module_name as an alternative to script path Contributed by Sanyam Khurana in bpo 21862 crypt The crypt module now supports the Blowfish hashing method Contributed by Serhiy Storchaka in bpo 31664 The mksalt function now allows specifying the number of rounds for hashing Contributed by Serhiy Storchaka in bpo 31702 datetime The new datetime fromisoformat method constructs a datetime object from a string in one of the formats output by datetime isoformat Contributed by Paul Ganssle in bpo 15873 The tzinfo class now supports sub minute offsets Contributed by Alexander Belopolsky in bpo 5288 dbm dbm dumb now supports reading read only files and no longer writes the index file when it is not changed
en
null
2,347
decimal The decimal module now uses context variables to store the decimal context Contributed by Yury Selivanov in bpo 32630 dis The dis function is now able to disassemble nested code objects the code of comprehensions generator expressions and nested functions and the code used for building nested classes The maximum depth of disassembly recursion is controlled by the new depth parameter Contributed by Serhiy Storchaka in bpo 11822 distutils README rst is now included in the list of distutils standard READMEs and therefore included in source distributions Contributed by Ryan Gonzalez in bpo 11913 enum The Enum learned the new _ignore_ class property which allows listing the names of properties which should not become enum members Contributed by Ethan Furman in bpo 31801 In Python 3 8 attempting to check for non Enum objects in Enum classes will raise a TypeError e g 1 in Color similarly attempting to check for non Flag objects in a Flag member will raise TypeError e g 1 in Perm RW currently both operations return False instead and are deprecated Contributed by Ethan Furman in bpo 33217 functools functools singledispatch now supports registering implementations using type annotations Contributed by Łukasz Langa in bpo 32227 gc The new gc freeze function allows freezing all objects tracked by the garbage collector and excluding them from future collections This can be used before a POSIX fork call to make the GC copy on write friendly or to speed up collection The new gc unfreeze functions reverses this operation Additionally gc get_freeze_count can be used to obtain the number of frozen objects Contributed by Li Zekun in bpo 31558 hmac The hmac module now has an optimized one shot digest function which is up to three times faster than HMAC Contributed by Christian Heimes in bpo 32433 http client HTTPConnection and HTTPSConnection now support the new blocksize argument for improved upload throughput Contributed by Nir Soffer in bpo 31945 http server SimpleHTTPRequestHandler now supports the HTTP If Modified Since header The server returns the 304 response status if the target file was not modified after the time specified in the header Contributed by Pierre Quentel in bpo 29654 SimpleHTTPRequestHandler accepts the new directory argument in addition to the new directory command line argument With this parameter the server serves the specified directory by default it uses the current working directory Contributed by Stéphane Wirtel and Julien Palard in bpo 28707 The new ThreadingHTTPServer class uses threads to handle requests using ThreadingMixin It is used when http server is run with m Contributed by Julien Palard in bpo 31639 idlelib and IDLE Multiple fixes for autocompletion Contributed by Louie Lu in bpo 15786 Module Browser on the File menu formerly called Class Browser now displays nested functions and classes in addition to top level functions and classes Contributed by Guilherme Polo Cheryl Sabella and Terry Jan Reedy in bpo 1612262 The Settings dialog Options Configure IDLE has been partly rewritten to improve both appearance and function Contributed by Cheryl Sabella and Terry Jan Reedy in multiple issues The font sample now includes a selection of non Latin characters so that users can better see the effect of selecting a particular font Contributed by Terry Jan Reedy in bpo 13802 The sample can be edited to include other characters Contributed by Serhiy Storchaka in bpo 31860 The IDLE features formerly implemented as extensions have been reimplemented as normal features Their settings have been moved from the Extensions tab to other dialog tabs Contributed by Charles Wohlganger and Terry Jan Reedy in bpo 27099 Editor code context option revised Box displays all context lines up to maxlines Clicking on a context line jumps the editor to that line Context colors for custom themes is added to Highlights tab of Settings dialog Contributed by Cheryl Sabella and Terry Jan Reedy in bpo 33642 bpo 33768 and bpo 33679 On Windows a new API call tells Windows that tk scales for DPI On Windows 8 1 or 10 with DPI compati
en
null
2,348
bility properties of the Python binary unchanged and a monitor resolution greater than 96 DPI this should make text and lines sharper It should otherwise have no effect Contributed by Terry Jan Reedy in bpo 33656 New in 3 7 1 Output over N lines 50 by default is squeezed down to a button N can be changed in the PyShell section of the General page of the Settings dialog Fewer but possibly extra long lines can be squeezed by right clicking on the output Squeezed output can be expanded in place by double clicking the button or into the clipboard or a separate window by right clicking the button Contributed by Tal Einat in bpo 1529353 The changes above have been backported to 3 6 maintenance releases NEW in 3 7 4 Add Run Customized to the Run menu to run a module with customized settings Any command line arguments entered are added to sys argv They re appear in the box for the next customized run One can also suppress the normal Shell main module restart Contributed by Cheryl Sabella Terry Jan Reedy and others in bpo 5680 and bpo 37627 New in 3 7 5 Add optional line numbers for IDLE editor windows Windows open without line numbers unless set otherwise in the General tab of the configuration dialog Line numbers for an existing window are shown and hidden in the Options menu Contributed by Tal Einat and Saimadhav Heblikar in bpo 17535 importlib The importlib abc ResourceReader ABC was introduced to support the loading of resources from packages See also importlib resources Contributed by Barry Warsaw Brett Cannon in bpo 32248 importlib reload now raises ModuleNotFoundError if the module lacks a spec Contributed by Garvit Khatri in bpo 29851 importlib find_spec now raises ModuleNotFoundError instead of AttributeError if the specified parent module is not a package i e lacks a __path__ attribute Contributed by Milan Oberkirch in bpo 30436 The new importlib source_hash can be used to compute the hash of the passed source A hash based pyc file embeds the value returned by this function io The new TextIOWrapper reconfigure method can be used to reconfigure the text stream with the new settings Contributed by Antoine Pitrou in bpo 30526 and INADA Naoki in bpo 15216 ipaddress The new subnet_of and supernet_of methods of ipaddress IPv6Network and ipaddress IPv4Network can be used for network containment tests Contributed by Michel Albert and Cheryl Sabella in bpo 20825 itertools itertools islice now accepts integer like objects as start stop and slice arguments Contributed by Will Roberts in bpo 30537 locale The new monetary argument to locale format_string can be used to make the conversion use monetary thousands separators and grouping strings Contributed by Garvit in bpo 10379 The locale getpreferredencoding function now always returns UTF 8 on Android or when in the forced UTF 8 mode logging Logger instances can now be pickled Contributed by Vinay Sajip in bpo 30520 The new StreamHandler setStream method can be used to replace the logger stream after handler creation Contributed by Vinay Sajip in bpo 30522 It is now possible to specify keyword arguments to handler constructors in configuration passed to logging config fileConfig Contributed by Preston Landers in bpo 31080 math The new math remainder function implements the IEEE 754 style remainder operation Contributed by Mark Dickinson in bpo 29962 mimetypes The MIME type of bmp has been changed from image x ms bmp to image bmp Contributed by Nitish Chandra in bpo 22589 msilib The new Database Close method can be used to close the MSI database Contributed by Berker Peksag in bpo 20486 multiprocessing The new Process close method explicitly closes the process object and releases all resources associated with it ValueError is raised if the underlying process is still running Contributed by Antoine Pitrou in bpo 30596 The new Process kill method can be used to terminate the process using the SIGKILL signal on Unix Contributed by Vitor Pereira in bpo 30794 Non daemonic threads created by Process are now joined on process exit Contributed by Antoine Pitrou in bpo 18966 os os fwalk now
en
null
2,349
accepts the path argument as bytes Contributed by Serhiy Storchaka in bpo 28682 os scandir gained support for file descriptors Contributed by Serhiy Storchaka in bpo 25996 The new register_at_fork function allows registering Python callbacks to be executed at process fork Contributed by Antoine Pitrou in bpo 16500 Added os preadv combine the functionality of os readv and os pread and os pwritev functions combine the functionality of os writev and os pwrite Contributed by Pablo Galindo in bpo 31368 The mode argument of os makedirs no longer affects the file permission bits of newly created intermediate level directories Contributed by Serhiy Storchaka in bpo 19930 os dup2 now returns the new file descriptor Previously None was always returned Contributed by Benjamin Peterson in bpo 32441 The structure returned by os stat now contains the st_fstype attribute on Solaris and its derivatives Contributed by Jesús Cea Avión in bpo 32659 pathlib The new Path is_mount method is now available on POSIX systems and can be used to determine whether a path is a mount point Contributed by Cooper Ry Lees in bpo 30897 pdb pdb set_trace now takes an optional header keyword only argument If given it is printed to the console just before debugging begins Contributed by Barry Warsaw in bpo 31389 pdb command line now accepts m module_name as an alternative to script file Contributed by Mario Corchero in bpo 32206 py_compile py_compile compile and by extension compileall now respects the SOURCE_DATE_EPOCH environment variable by unconditionally creating pyc files for hash based validation This allows for guaranteeing reproducible builds of pyc files when they are created eagerly Contributed by Bernhard M Wiedemann in bpo 29708 pydoc The pydoc server can now bind to an arbitrary hostname specified by the new n command line argument Contributed by Feanil Patel in bpo 31128 queue The new SimpleQueue class is an unbounded FIFO queue Contributed by Antoine Pitrou in bpo 14976 re The flags re ASCII re LOCALE and re UNICODE can be set within the scope of a group Contributed by Serhiy Storchaka in bpo 31690 re split now supports splitting on a pattern like r b or that matches an empty string Contributed by Serhiy Storchaka in bpo 25054 Regular expressions compiled with the re LOCALE flag no longer depend on the locale at compile time Locale settings are applied only when the compiled regular expression is used Contributed by Serhiy Storchaka in bpo 30215 FutureWarning is now emitted if a regular expression contains character set constructs that will change semantically in the future such as nested sets and set operations Contributed by Serhiy Storchaka in bpo 30349 Compiled regular expression and match objects can now be copied using copy copy and copy deepcopy Contributed by Serhiy Storchaka in bpo 10076 signal The new warn_on_full_buffer argument to the signal set_wakeup_fd function makes it possible to specify whether Python prints a warning on stderr when the wakeup buffer overflows Contributed by Nathaniel J Smith in bpo 30050 socket The new socket getblocking method returns True if the socket is in blocking mode and False otherwise Contributed by Yury Selivanov in bpo 32373 The new socket close function closes the passed socket file descriptor This function should be used instead of os close for better compatibility across platforms Contributed by Christian Heimes in bpo 32454 The socket module now exposes the socket TCP_CONGESTION Linux 2 6 13 socket TCP_USER_TIMEOUT Linux 2 6 37 and socket TCP_NOTSENT_LOWAT Linux 3 12 constants Contributed by Omar Sandoval in bpo 26273 and Nathaniel J Smith in bpo 29728 Support for socket AF_VSOCK sockets has been added to allow communication between virtual machines and their hosts Contributed by Cathy Avery in bpo 27584 Sockets now auto detect family type and protocol from file descriptor by default Contributed by Christian Heimes in bpo 28134 socketserver socketserver ThreadingMixIn server_close now waits until all non daemon threads complete socketserver ForkingMixIn server_close now waits until all child
en
null
2,350
processes complete Add a new socketserver ForkingMixIn block_on_close class attribute to socketserver ForkingMixIn and socketserver ThreadingMixIn classes Set the class attribute to False to get the pre 3 7 behaviour sqlite3 sqlite3 Connection now exposes the backup method when the underlying SQLite library is at version 3 6 11 or higher Contributed by Lele Gaifax in bpo 27645 The database argument of sqlite3 connect now accepts any path like object instead of just a string Contributed by Anders Lorentsen in bpo 31843 ssl The ssl module now uses OpenSSL s builtin API instead of match_hostname to check a host name or an IP address Values are validated during TLS handshake Any certificate validation error including failing the host name check now raises SSLCertVerificationError and aborts the handshake with a proper TLS Alert message The new exception contains additional information Host name validation can be customized with SSLContext hostname_checks_common_name Contributed by Christian Heimes in bpo 31399 Note The improved host name check requires a libssl implementation compatible with OpenSSL 1 0 2 or 1 1 Consequently OpenSSL 0 9 8 and 1 0 1 are no longer supported see Platform Support Removals for more details The ssl module is mostly compatible with LibreSSL 2 7 2 and newer The ssl module no longer sends IP addresses in SNI TLS extension Contributed by Christian Heimes in bpo 32185 match_hostname no longer supports partial wildcards like www example org Contributed by Mandeep Singh in bpo 23033 and Christian Heimes in bpo 31399 The default cipher suite selection of the ssl module now uses a blacklist approach rather than a hard coded whitelist Python no longer re enables ciphers that have been blocked by OpenSSL security updates Default cipher suite selection can be configured at compile time Contributed by Christian Heimes in bpo 31429 Validation of server certificates containing internationalized domain names IDNs is now supported As part of this change the SSLSocket server_hostname attribute now stores the expected hostname in A label form xn pythn mua org rather than the U label form pythön org Contributed by Nathaniel J Smith and Christian Heimes in bpo 28414 The ssl module has preliminary and experimental support for TLS 1 3 and OpenSSL 1 1 1 At the time of Python 3 7 0 release OpenSSL 1 1 1 is still under development and TLS 1 3 hasn t been finalized yet The TLS 1 3 handshake and protocol behaves slightly differently than TLS 1 2 and earlier see TLS 1 3 Contributed by Christian Heimes in bpo 32947 bpo 20995 bpo 29136 bpo 30622 and bpo 33618 SSLSocket and SSLObject no longer have a public constructor Direct instantiation was never a documented and supported feature Instances must be created with SSLContext methods wrap_socket and wrap_bio Contributed by Christian Heimes in bpo 32951 OpenSSL 1 1 APIs for setting the minimum and maximum TLS protocol version are available as SSLContext minimum_version and SSLContext maximum_version Supported protocols are indicated by several new flags such as HAS_TLSv1_1 Contributed by Christian Heimes in bpo 32609 Added ssl SSLContext post_handshake_auth to enable and ssl SSLSocket verify_client_post_handshake to initiate TLS 1 3 post handshake authentication Contributed by Christian Heimes in gh 78851 string string Template now lets you to optionally modify the regular expression pattern for braced placeholders and non braced placeholders separately Contributed by Barry Warsaw in bpo 1198569 subprocess The subprocess run function accepts the new capture_output keyword argument When true stdout and stderr will be captured This is equivalent to passing subprocess PIPE as stdout and stderr arguments Contributed by Bo Bayles in bpo 32102 The subprocess run function and the subprocess Popen constructor now accept the text keyword argument as an alias to universal_newlines Contributed by Andrew Clegg in bpo 31756 On Windows the default for close_fds was changed from False to True when redirecting the standard handles It s now possible to set close_fds to true when redirecting the s
en
null
2,351
tandard handles See subprocess Popen This means that close_fds now defaults to True on all supported platforms Contributed by Segev Finer in bpo 19764 The subprocess module is now more graceful when handling KeyboardInterrupt during subprocess call subprocess run or in a Popen context manager It now waits a short amount of time for the child to exit before continuing the handling of the KeyboardInterrupt exception Contributed by Gregory P Smith in bpo 25942 sys The new sys breakpointhook hook function is called by the built in breakpoint Contributed by Barry Warsaw in bpo 31353 On Android the new sys getandroidapilevel returns the build time Android API version Contributed by Victor Stinner in bpo 28740 The new sys get_coroutine_origin_tracking_depth function returns the current coroutine origin tracking depth as set by the new sys set_coroutine_origin_tracking_depth asyncio has been converted to use this new API instead of the deprecated sys set_coroutine_wrapper Contributed by Nathaniel J Smith in bpo 32591 time PEP 564 adds six new functions with nanosecond resolution to the time module time clock_gettime_ns time clock_settime_ns time monotonic_ns time perf_counter_ns time process_time_ns time time_ns New clock identifiers have been added time CLOCK_BOOTTIME Linux Identical to time CLOCK_MONOTONIC except it also includes any time that the system is suspended time CLOCK_PROF FreeBSD NetBSD and OpenBSD High resolution per process CPU timer time CLOCK_UPTIME FreeBSD OpenBSD Time whose absolute value is the time the system has been running and not suspended providing accurate uptime measurement The new time thread_time and time thread_time_ns functions can be used to get per thread CPU time measurements Contributed by Antoine Pitrou in bpo 32025 The new time pthread_getcpuclockid function returns the clock ID of the thread specific CPU time clock tkinter The new tkinter ttk Spinbox class is now available Contributed by Alan Moore in bpo 32585 tracemalloc tracemalloc Traceback behaves more like regular tracebacks sorting the frames from oldest to most recent Traceback format now accepts negative limit truncating the result to the abs limit oldest frames To get the old behaviour use the new most_recent_first argument to Traceback format Contributed by Jesse Bakker in bpo 32121 types The new WrapperDescriptorType MethodWrapperType MethodDescriptorType and ClassMethodDescriptorType classes are now available Contributed by Manuel Krebber and Guido van Rossum in bpo 29377 and Serhiy Storchaka in bpo 32265 The new types resolve_bases function resolves MRO entries dynamically as specified by PEP 560 Contributed by Ivan Levkivskyi in bpo 32717 unicodedata The internal unicodedata database has been upgraded to use Unicode 11 Contributed by Benjamin Peterson unittest The new k command line option allows filtering tests by a name substring or a Unix shell like pattern For example python m unittest k foo runs foo_tests SomeTest test_something bar_tests SomeTest test_foo but not bar_tests FooTest test_something Contributed by Jonas Haag in bpo 32071 unittest mock The sentinel attributes now preserve their identity when they are copied or pickled Contributed by Serhiy Storchaka in bpo 20804 The new seal function allows sealing Mock instances which will disallow further creation of attribute mocks The seal is applied recursively to all attributes that are themselves mocks Contributed by Mario Corchero in bpo 30541 urllib parse urllib parse quote has been updated from RFC 2396 to RFC 3986 adding to the set of characters that are never quoted by default Contributed by Christian Theune and Ratnadeep Debnath in bpo 16285 uu The uu encode function now accepts an optional backtick keyword argument When it s true zeros are represented by instead of spaces Contributed by Xiang Zhang in bpo 30103 uuid The new UUID is_safe attribute relays information from the platform about whether generated UUIDs are generated with a multiprocessing safe method Contributed by Barry Warsaw in bpo 22807 uuid getnode now prefers universally administered MAC address
en
null
2,352
es over locally administered MAC addresses This makes a better guarantee for global uniqueness of UUIDs returned from uuid uuid1 If only locally administered MAC addresses are available the first such one found is returned Contributed by Barry Warsaw in bpo 32107 warnings The initialization of the default warnings filters has changed as follows warnings enabled via command line options including those for b and the new CPython specific X dev option are always passed to the warnings machinery via the sys warnoptions attribute warnings filters enabled via the command line or the environment now have the following order of precedence the BytesWarning filter for b or bb any filters specified with the W option any filters specified with the PYTHONWARNINGS environment variable any other CPython specific filters e g the default filter added for the new X dev mode any implicit filters defined directly by the warnings machinery in CPython debug builds all warnings are now displayed by default the implicit filter list is empty Contributed by Nick Coghlan and Victor Stinner in bpo 20361 bpo 32043 and bpo 32230 Deprecation warnings are once again shown by default in single file scripts and at the interactive prompt See PEP 565 Show DeprecationWarning in __main__ for details Contributed by Nick Coghlan in bpo 31975 xml As mitigation against DTD and external entity retrieval the xml dom minidom and xml sax modules no longer process external entities by default Contributed by Christian Heimes in gh 61441 xml etree ElementPath predicates in the find methods can now compare text of the current node with text not only text in children Predicates also allow adding spaces for better readability Contributed by Stefan Behnel in bpo 31648 xmlrpc server SimpleXMLRPCDispatcher register_function can now be used as a decorator Contributed by Xiang Zhang in bpo 7769 zipapp Function create_archive now accepts an optional filter argument to allow the user to select which files should be included in the archive Contributed by Irmen de Jong in bpo 31072 Function create_archive now accepts an optional compressed argument to generate a compressed archive A command line option compress has also been added to support compression Contributed by Zhiming Wang in bpo 31638 zipfile ZipFile now accepts the new compresslevel parameter to control the compression level Contributed by Bo Bayles in bpo 21417 Subdirectories in archives created by ZipFile are now stored in alphabetical order Contributed by Bernhard M Wiedemann in bpo 30693 C API Changes A new API for thread local storage has been implemented See PEP 539 New C API for Thread Local Storage for an overview and Thread Specific Storage TSS API for a complete reference Contributed by Masayuki Yamamoto in bpo 25658 The new context variables functionality exposes a number of new C APIs The new PyImport_GetModule function returns the previously imported module with the given name Contributed by Eric Snow in bpo 28411 The new Py_RETURN_RICHCOMPARE macro eases writing rich comparison functions Contributed by Petr Victorin in bpo 23699 The new Py_UNREACHABLE macro can be used to mark unreachable code paths Contributed by Barry Warsaw in bpo 31338 The tracemalloc now exposes a C API through the new PyTraceMalloc_Track and PyTraceMalloc_Untrack functions Contributed by Victor Stinner in bpo 30054 The new import__find__load__start and import__find__load__done static markers can be used to trace module imports Contributed by Christian Heimes in bpo 31574 The fields name and doc of structures PyMemberDef PyGetSetDef PyStructSequence_Field PyStructSequence_Desc and wrapperbase are now of type const char rather of char Contributed by Serhiy Storchaka in bpo 28761 The result of PyUnicode_AsUTF8AndSize and PyUnicode_AsUTF8 is now of type const char rather of char Contributed by Serhiy Storchaka in bpo 28769 The result of PyMapping_Keys PyMapping_Values and PyMapping_Items is now always a list rather than a list or a tuple Contributed by Oren Milman in bpo 28280 Added functions PySlice_Unpack and PySlice_AdjustIndices Contr
en
null
2,353
ibuted by Serhiy Storchaka in bpo 27867 PyOS_AfterFork is deprecated in favour of the new functions PyOS_BeforeFork PyOS_AfterFork_Parent and PyOS_AfterFork_Child Contributed by Antoine Pitrou in bpo 16500 The PyExc_RecursionErrorInst singleton that was part of the public API has been removed as its members being never cleared may cause a segfault during finalization of the interpreter Contributed by Xavier de Gaye in bpo 22898 and bpo 30697 Added C API support for timezones with timezone constructors PyTimeZone_FromOffset and PyTimeZone_FromOffsetAndName and access to the UTC singleton with PyDateTime_TimeZone_UTC Contributed by Paul Ganssle in bpo 10381 The type of results of PyThread_start_new_thread and PyThread_get_thread_ident and the id parameter of PyThreadState_SetAsyncExc changed from long to unsigned long Contributed by Serhiy Storchaka in bpo 6532 PyUnicode_AsWideCharString now raises a ValueError if the second argument is NULL and the wchar_t string contains null characters Contributed by Serhiy Storchaka in bpo 30708 Changes to the startup sequence and the management of dynamic memory allocators mean that the long documented requirement to call Py_Initialize before calling most C API functions is now relied on more heavily and failing to abide by it may lead to segfaults in embedding applications See the Porting to Python 3 7 section in this document and the Before Python Initialization section in the C API documentation for more details The new PyInterpreterState_GetID returns the unique ID for a given interpreter Contributed by Eric Snow in bpo 29102 Py_DecodeLocale Py_EncodeLocale now use the UTF 8 encoding when the UTF 8 mode is enabled Contributed by Victor Stinner in bpo 29240 PyUnicode_DecodeLocaleAndSize and PyUnicode_EncodeLocale now use the current locale encoding for surrogateescape error handler Contributed by Victor Stinner in bpo 29240 The start and end parameters of PyUnicode_FindChar are now adjusted to behave like string slices Contributed by Xiang Zhang in bpo 28822 Build Changes Support for building without threads has been removed The threading module is now always available Contributed by Antoine Pitrou in bpo 31370 A full copy of libffi is no longer bundled for use when building the _ctypes module on non OSX UNIX platforms An installed copy of libffi is now required when building _ctypes on such platforms Contributed by Zachary Ware in bpo 27979 The Windows build process no longer depends on Subversion to pull in external sources a Python script is used to download zipfiles from GitHub instead If Python 3 6 is not found on the system via py 3 6 NuGet is used to download a copy of 32 bit Python for this purpose Contributed by Zachary Ware in bpo 30450 The ssl module requires OpenSSL 1 0 2 or 1 1 compatible libssl OpenSSL 1 0 1 has reached end of lifetime on 2016 12 31 and is no longer supported LibreSSL is temporarily not supported as well LibreSSL releases up to version 2 6 4 are missing required OpenSSL 1 0 2 APIs Optimizations The overhead of calling many methods of various standard library classes implemented in C has been significantly reduced by porting more code to use the METH_FASTCALL convention Contributed by Victor Stinner in bpo 29300 bpo 29507 bpo 29452 and bpo 29286 Various optimizations have reduced Python startup time by 10 on Linux and up to 30 on macOS Contributed by Victor Stinner INADA Naoki in bpo 29585 and Ivan Levkivskyi in bpo 31333 Method calls are now up to 20 faster due to the bytecode changes which avoid creating bound method instances Contributed by Yury Selivanov and INADA Naoki in bpo 26110 The asyncio module received a number of notable optimizations for commonly used functions The asyncio get_event_loop function has been reimplemented in C to make it up to 15 times faster Contributed by Yury Selivanov in bpo 32296 asyncio Future callback management has been optimized Contributed by Yury Selivanov in bpo 32348 asyncio gather is now up to 15 faster Contributed by Yury Selivanov in bpo 32355 asyncio sleep is now up to 2 times faster when the delay argument
en
null
2,354
is zero or negative Contributed by Andrew Svetlov in bpo 32351 The performance overhead of asyncio debug mode has been reduced Contributed by Antoine Pitrou in bpo 31970 As a result of PEP 560 work the import time of typing has been reduced by a factor of 7 and many typing operations are now faster Contributed by Ivan Levkivskyi in bpo 32226 sorted and list sort have been optimized for common cases to be up to 40 75 faster Contributed by Elliot Gorokhovsky in bpo 28685 dict copy is now up to 5 5 times faster Contributed by Yury Selivanov in bpo 31179 hasattr and getattr are now about 4 times faster when name is not found and obj does not override object __getattr__ or object __getattribute__ Contributed by INADA Naoki in bpo 32544 Searching for certain Unicode characters like Ukrainian capital Є in a string was up to 25 times slower than searching for other characters It is now only 3 times slower in the worst case Contributed by Serhiy Storchaka in bpo 24821 The collections namedtuple factory has been reimplemented to make the creation of named tuples 4 to 6 times faster Contributed by Jelle Zijlstra with further improvements by INADA Naoki Serhiy Storchaka and Raymond Hettinger in bpo 28638 date fromordinal and date fromtimestamp are now up to 30 faster in the common case Contributed by Paul Ganssle in bpo 32403 The os fwalk function is now up to 2 times faster thanks to the use of os scandir Contributed by Serhiy Storchaka in bpo 25996 The speed of the shutil rmtree function has been improved by 20 40 thanks to the use of the os scandir function Contributed by Serhiy Storchaka in bpo 28564 Optimized case insensitive matching and searching of regular expressions Searching some patterns can now be up to 20 times faster Contributed by Serhiy Storchaka in bpo 30285 re compile now converts flags parameter to int object if it is RegexFlag It is now as fast as Python 3 5 and faster than Python 3 6 by about 10 depending on the pattern Contributed by INADA Naoki in bpo 31671 The modify methods of classes selectors EpollSelector selectors PollSelector and selectors DevpollSelector may be around 10 faster under heavy loads Contributed by Giampaolo Rodola in bpo 30014 Constant folding has been moved from the peephole optimizer to the new AST optimizer which is able perform optimizations more consistently Contributed by Eugene Toder and INADA Naoki in bpo 29469 and bpo 11549 Most functions and methods in abc have been rewritten in C This makes creation of abstract base classes and calling isinstance and issubclass on them 1 5x faster This also reduces Python start up time by up to 10 Contributed by Ivan Levkivskyi and INADA Naoki in bpo 31333 Significant speed improvements to alternate constructors for datetime date and datetime datetime by using fast path constructors when not constructing subclasses Contributed by Paul Ganssle in bpo 32403 The speed of comparison of array array instances has been improved considerably in certain cases It is now from 10x to 70x faster when comparing arrays holding values of the same integer type Contributed by Adrian Wielgosik in bpo 24700 The math erf and math erfc functions now use the faster C library implementation on most platforms Contributed by Serhiy Storchaka in bpo 26121 Other CPython Implementation Changes Trace hooks may now opt out of receiving the line and opt into receiving the opcode events from the interpreter by setting the corresponding new f_trace_lines and f_trace_opcodes attributes on the frame being traced Contributed by Nick Coghlan in bpo 31344 Fixed some consistency problems with namespace package module attributes Namespace module objects now have an __file__ that is set to None previously unset and their __spec__ origin is also set to None previously the string namespace See bpo 32305 Also the namespace module object s __spec__ loader is set to the same value as __loader__ previously the former was set to None See bpo 32303 The locals dictionary now displays in the lexical order that variables were defined Previously the order was undefined Contributed by Raymond Hetti
en
null
2,355
nger in bpo 32690 The distutils upload command no longer tries to change CR end of line characters to CRLF This fixes a corruption issue with sdists that ended with a byte equivalent to CR Contributed by Bo Bayles in bpo 32304 Deprecated Python Behavior Yield expressions both yield and yield from clauses are now deprecated in comprehensions and generator expressions aside from the iterable expression in the leftmost for clause This ensures that comprehensions always immediately return a container of the appropriate type rather than potentially returning a generator iterator object while generator expressions won t attempt to interleave their implicit output with the output from any explicit yield expressions In Python 3 7 such expressions emit DeprecationWarning when compiled in Python 3 8 this will be a SyntaxError Contributed by Serhiy Storchaka in bpo 10544 Returning a subclass of complex from object __complex__ is deprecated and will be an error in future Python versions This makes __complex__ consistent with object __int__ and object __float__ Contributed by Serhiy Storchaka in bpo 28894 Deprecated Python modules functions and methods aifc aifc openfp has been deprecated and will be removed in Python 3 9 Use aifc open instead Contributed by Brian Curtin in bpo 31985 asyncio Support for directly await ing instances of asyncio Lock and other asyncio synchronization primitives has been deprecated An asynchronous context manager must be used in order to acquire and release the synchronization resource Contributed by Andrew Svetlov in bpo 32253 The asyncio Task current_task and asyncio Task all_tasks methods have been deprecated Contributed by Andrew Svetlov in bpo 32250 collections In Python 3 8 the abstract base classes in collections abc will no longer be exposed in the regular collections module This will help create a clearer distinction between the concrete classes and the abstract base classes Contributed by Serhiy Storchaka in bpo 25988 dbm dbm dumb now supports reading read only files and no longer writes the index file when it is not changed A deprecation warning is now emitted if the index file is missing and recreated in the r and w modes this will be an error in future Python releases Contributed by Serhiy Storchaka in bpo 28847 enum In Python 3 8 attempting to check for non Enum objects in Enum classes will raise a TypeError e g 1 in Color similarly attempting to check for non Flag objects in a Flag member will raise TypeError e g 1 in Perm RW currently both operations return False instead Contributed by Ethan Furman in bpo 33217 gettext Using non integer value for selecting a plural form in gettext is now deprecated It never correctly worked Contributed by Serhiy Storchaka in bpo 28692 importlib Methods MetaPathFinder find_module replaced by MetaPathFinder find_spec and PathEntryFinder find_loader replaced by PathEntryFinder find_spec both deprecated in Python 3 4 now emit DeprecationWarning Contributed by Matthias Bussonnier in bpo 29576 The importlib abc ResourceLoader ABC has been deprecated in favour of importlib abc ResourceReader locale locale format has been deprecated use locale format_string instead Contributed by Garvit in bpo 10379 macpath The macpath is now deprecated and will be removed in Python 3 8 Contributed by Chi Hsuan Yen in bpo 9850 threading dummy_threading and _dummy_thread have been deprecated It is no longer possible to build Python with threading disabled Use threading instead Contributed by Antoine Pitrou in bpo 31370 socket The silent argument value truncation in socket htons and socket ntohs has been deprecated In future versions of Python if the passed argument is larger than 16 bits an exception will be raised Contributed by Oren Milman in bpo 28332 ssl ssl wrap_socket is deprecated Use ssl SSLContext wrap_socket instead Contributed by Christian Heimes in bpo 28124 sunau sunau openfp has been deprecated and will be removed in Python 3 9 Use sunau open instead Contributed by Brian Curtin in bpo 31985 sys Deprecated sys set_coroutine_wrapper and sys get_coroutine_wrapper The un
en
null
2,356
documented sys callstats function has been deprecated and will be removed in a future Python version Contributed by Victor Stinner in bpo 28799 wave wave openfp has been deprecated and will be removed in Python 3 9 Use wave open instead Contributed by Brian Curtin in bpo 31985 Deprecated functions and types of the C API Function PySlice_GetIndicesEx is deprecated and replaced with a macro if Py_LIMITED_API is not set or set to a value in the range between 0x03050400 and 0x03060000 not inclusive or is 0x03060100 or higher Contributed by Serhiy Storchaka in bpo 27867 PyOS_AfterFork has been deprecated Use PyOS_BeforeFork PyOS_AfterFork_Parent or PyOS_AfterFork_Child instead Contributed by Antoine Pitrou in bpo 16500 Platform Support Removals FreeBSD 9 and older are no longer officially supported For full Unicode support including within extension modules nix platforms are now expected to provide at least one of C UTF 8 full locale C utf8 full locale or UTF 8 LC_CTYPE only locale as an alternative to the legacy ASCII based C locale OpenSSL 0 9 8 and 1 0 1 are no longer supported which means building CPython 3 7 with SSL TLS support on older platforms still using these versions requires custom build options that link to a more recent version of OpenSSL Notably this issue affects the Debian 8 aka jessie and Ubuntu 14 04 aka Trusty LTS Linux distributions as they still use OpenSSL 1 0 1 by default Debian 9 stretch and Ubuntu 16 04 xenial as well as recent releases of other LTS Linux releases e g RHEL CentOS 7 5 SLES 12 SP3 use OpenSSL 1 0 2 or later and remain supported in the default build configuration CPython s own CI configuration file provides an example of using the SSL compatibility testing infrastructure in CPython s test suite to build and link against OpenSSL 1 1 0 rather than an outdated system provided OpenSSL API and Feature Removals The following features and APIs have been removed from Python 3 7 The os stat_float_times function has been removed It was introduced in Python 2 3 for backward compatibility with Python 2 2 and was deprecated since Python 3 1 Unknown escapes consisting of and an ASCII letter in replacement templates for re sub were deprecated in Python 3 5 and will now cause an error Removed support of the exclude argument in tarfile TarFile add It was deprecated in Python 2 7 and 3 2 Use the filter argument instead The ntpath splitunc function was deprecated in Python 3 1 and has now been removed Use splitdrive instead collections namedtuple no longer supports the verbose parameter or _source attribute which showed the generated source code for the named tuple class This was part of an optimization designed to speed up class creation Contributed by Jelle Zijlstra with further improvements by INADA Naoki Serhiy Storchaka and Raymond Hettinger in bpo 28638 Functions bool float list and tuple no longer take keyword arguments The first argument of int can now be passed only as positional argument Removed previously deprecated in Python 2 4 classes Plist Dict and _InternalDict in the plistlib module Dict values in the result of functions readPlist and readPlistFromBytes are now normal dicts You no longer can use attribute access to access items of these dictionaries The asyncio windows_utils socketpair function has been removed Use the socket socketpair function instead it is available on all platforms since Python 3 5 asyncio windows_utils socketpair was just an alias to socket socketpair on Python 3 5 and newer asyncio no longer exports the selectors and _overlapped modules as asyncio selectors and asyncio _overlapped Replace from asyncio import selectors with import selectors Direct instantiation of ssl SSLSocket and ssl SSLObject objects is now prohibited The constructors were never documented tested or designed as public constructors Users were supposed to use ssl wrap_socket or ssl SSLContext Contributed by Christian Heimes in bpo 32951 The unused distutils install_misc command has been removed Contributed by Eric N Vander Weele in bpo 29218 Module Removals The fpectl module has been removed It was
en
null
2,357
never enabled by default never worked correctly on x86 64 and it changed the Python ABI in ways that caused unexpected breakage of C extensions Contributed by Nathaniel J Smith in bpo 29137 Windows only Changes The python launcher py exe can accept 32 64 bit specifiers without having to specify a minor version as well So py 3 32 and py 3 64 become valid as well as py 3 7 32 also the m 64 and m n 64 forms are now accepted to force 64 bit python even if 32 bit would have otherwise been used If the specified version is not available py exe will error exit Contributed by Steve Barnes in bpo 30291 The launcher can be run as py 0 to produce a list of the installed pythons with default marked with an asterisk Running py 0p will include the paths If py is run with a version specifier that cannot be matched it will also print the short form list of available specifiers Contributed by Steve Barnes in bpo 30362 Porting to Python 3 7 This section lists previously described changes and other bugfixes that may require changes to your code Changes in Python Behavior async and await names are now reserved keywords Code using these names as identifiers will now raise a SyntaxError Contributed by Jelle Zijlstra in bpo 30406 PEP 479 is enabled for all code in Python 3 7 meaning that StopIteration exceptions raised directly or indirectly in coroutines and generators are transformed into RuntimeError exceptions Contributed by Yury Selivanov in bpo 32670 object __aiter__ methods can no longer be declared as asynchronous Contributed by Yury Selivanov in bpo 31709 Due to an oversight earlier Python versions erroneously accepted the following syntax f 1 for x in 1 class C 1 for x in 1 pass Python 3 7 now correctly raises a SyntaxError as a generator expression always needs to be directly inside a set of parentheses and cannot have a comma on either side and the duplication of the parentheses can be omitted only on calls Contributed by Serhiy Storchaka in bpo 32012 and bpo 32023 When using the m switch the initial working directory is now added to sys path rather than an empty string which dynamically denoted the current working directory at the time of each import Any programs that are checking for the empty string or otherwise relying on the previous behaviour will need to be updated accordingly e g by also checking for os getcwd or os path dirname __main__ __file__ depending on why the code was checking for the empty string in the first place Changes in the Python API socketserver ThreadingMixIn server_close now waits until all non daemon threads complete Set the new socketserver ThreadingMixIn block_on_close class attribute to False to get the pre 3 7 behaviour Contributed by Victor Stinner in bpo 31233 and bpo 33540 socketserver ForkingMixIn server_close now waits until all child processes complete Set the new socketserver ForkingMixIn block_on_close class attribute to False to get the pre 3 7 behaviour Contributed by Victor Stinner in bpo 31151 and bpo 33540 The locale localeconv function now temporarily sets the LC_CTYPE locale to the value of LC_NUMERIC in some cases Contributed by Victor Stinner in bpo 31900 pkgutil walk_packages now raises a ValueError if path is a string Previously an empty list was returned Contributed by Sanyam Khurana in bpo 24744 A format string argument for string Formatter format is now positional only Passing it as a keyword argument was deprecated in Python 3 5 Contributed by Serhiy Storchaka in bpo 29193 Attributes key value and coded_value of class http cookies Morsel are now read only Assigning to them was deprecated in Python 3 5 Use the set method for setting them Contributed by Serhiy Storchaka in bpo 29192 The mode argument of os makedirs no longer affects the file permission bits of newly created intermediate level directories To set their file permission bits you can set the umask before invoking makedirs Contributed by Serhiy Storchaka in bpo 19930 The struct Struct format type is now str instead of bytes Contributed by Victor Stinner in bpo 21071 parse_multipart now accepts the encoding and errors a
en
null
2,358
rguments and returns the same results as FieldStorage for non file fields the value associated to a key is a list of strings not bytes Contributed by Pierre Quentel in bpo 29979 Due to internal changes in socket calling socket fromshare on a socket created by socket share in older Python versions is not supported repr for BaseException has changed to not include the trailing comma Most exceptions are affected by this change Contributed by Serhiy Storchaka in bpo 30399 repr for datetime timedelta has changed to include the keyword arguments in the output Contributed by Utkarsh Upadhyay in bpo 30302 Because shutil rmtree is now implemented using the os scandir function the user specified handler onerror is now called with the first argument os scandir instead of os listdir when listing the directory is failed Support for nested sets and set operations in regular expressions as in Unicode Technical Standard 18 might be added in the future This would change the syntax To facilitate this future change a FutureWarning will be raised in ambiguous cases for the time being That include sets starting with a literal or containing literal character sequences and To avoid a warning escape them with a backslash Contributed by Serhiy Storchaka in bpo 30349 The result of splitting a string on a regular expression that could match an empty string has been changed For example splitting on r s will now split not only on whitespaces as it did previously but also on empty strings before all non whitespace characters and just before the end of the string The previous behavior can be restored by changing the pattern to r s A FutureWarning was emitted for such patterns since Python 3 5 For patterns that match both empty and non empty strings the result of searching for all matches may also be changed in other cases For example in the string a n n the pattern r m s will not only match empty strings at positions 2 and 3 but also the string n at positions 2 3 To match only blank lines the pattern should be rewritten as r m S n re sub now replaces empty matches adjacent to a previous non empty match For example re sub x abxd returns now a b d instead of a b d the first minus between b and d replaces x and the second minus replaces an empty string between x and d Contributed by Serhiy Storchaka in bpo 25054 and bpo 32308 Change re escape to only escape regex special characters instead of escaping all characters other than ASCII letters numbers and _ Contributed by Serhiy Storchaka in bpo 29995 tracemalloc Traceback frames are now sorted from oldest to most recent to be more consistent with traceback Contributed by Jesse Bakker in bpo 32121 On OSes that support socket SOCK_NONBLOCK or socket SOCK_CLOEXEC bit flags the socket type no longer has them applied Therefore checks like if sock type socket SOCK_STREAM work as expected on all platforms Contributed by Yury Selivanov in bpo 32331 On Windows the default for the close_fds argument of subprocess Popen was changed from False to True when redirecting the standard handles If you previously depended on handles being inherited when using subprocess Popen with standard io redirection you will have to pass close_fds False to preserve the previous behaviour or use STARTUPINFO lpAttributeList importlib machinery PathFinder invalidate_caches which implicitly affects importlib invalidate_caches now deletes entries in sys path_importer_cache which are set to None Contributed by Brett Cannon in bpo 33169 In asyncio loop sock_recv loop sock_sendall loop sock_accept loop getaddrinfo loop getnameinfo have been changed to be proper coroutine methods to match their documentation Previously these methods returned asyncio Future instances Contributed by Yury Selivanov in bpo 32327 asyncio Server sockets now returns a copy of the internal list of server sockets instead of returning it directly Contributed by Yury Selivanov in bpo 32662 Struct format is now a str instance instead of a bytes instance Contributed by Victor Stinner in bpo 21071 argparse subparsers can now be made mandatory by passing required True to Argum
en
null
2,359
entParser add_subparsers Contributed by Anthony Sottile in bpo 26510 ast literal_eval is now stricter Addition and subtraction of arbitrary numbers are no longer allowed Contributed by Serhiy Storchaka in bpo 31778 Calendar itermonthdates will now consistently raise an exception when a date falls outside of the 0001 01 01 through 9999 12 31 range To support applications that cannot tolerate such exceptions the new Calendar itermonthdays3 and Calendar itermonthdays4 can be used The new methods return tuples and are not restricted by the range supported by datetime date Contributed by Alexander Belopolsky in bpo 28292 collections ChainMap now preserves the order of the underlying mappings Contributed by Raymond Hettinger in bpo 32792 The submit method of concurrent futures ThreadPoolExecutor and concurrent futures ProcessPoolExecutor now raises a RuntimeError if called during interpreter shutdown Contributed by Mark Nemec in bpo 33097 The configparser ConfigParser constructor now uses read_dict to process the default values making its behavior consistent with the rest of the parser Non string keys and values in the defaults dictionary are now being implicitly converted to strings Contributed by James Tocknell in bpo 23835 Several undocumented internal imports were removed One example is that os errno is no longer available use import errno directly instead Note that such undocumented internal imports may be removed any time without notice even in micro version releases Changes in the C API The function PySlice_GetIndicesEx is considered unsafe for resizable sequences If the slice indices are not instances of int but objects that implement the __index__ method the sequence can be resized after passing its length to PySlice_GetIndicesEx This can lead to returning indices out of the length of the sequence For avoiding possible problems use new functions PySlice_Unpack and PySlice_AdjustIndices Contributed by Serhiy Storchaka in bpo 27867 CPython bytecode changes There are two new opcodes LOAD_METHOD and CALL_METHOD Contributed by Yury Selivanov and INADA Naoki in bpo 26110 The STORE_ANNOTATION opcode has been removed Contributed by Mark Shannon in bpo 32550 Windows only Changes The file used to override sys path is now called python executable _pth instead of sys path See Finding modules for more information Contributed by Steve Dower in bpo 28137 Other CPython implementation changes In preparation for potential future changes to the public CPython runtime initialization API see PEP 432 for an initial but somewhat outdated draft CPython s internal startup and configuration management logic has been significantly refactored While these updates are intended to be entirely transparent to both embedding applications and users of the regular CPython CLI they re being mentioned here as the refactoring changes the internal order of various operations during interpreter startup and hence may uncover previously latent defects either in embedding applications or in CPython itself Initially contributed by Nick Coghlan and Eric Snow as part of bpo 22257 and further updated by Nick Eric and Victor Stinner in a number of other issues Some known details affected PySys_AddWarnOptionUnicode is not currently usable by embedding applications due to the requirement to create a Unicode object prior to calling Py_Initialize Use PySys_AddWarnOption instead warnings filters added by an embedding application with PySys_AddWarnOption should now more consistently take precedence over the default filters set by the interpreter Due to changes in the way the default warnings filters are configured setting Py_BytesWarningFlag to a value greater than one is no longer sufficient to both emit BytesWarning messages and have them converted to exceptions Instead the flag must be set to cause the warnings to be emitted in the first place and an explicit error BytesWarning warnings filter added to convert them to exceptions Due to a change in the way docstrings are handled by the compiler the implicit return None in a function body consisting solely of a docstring
en
null
2,360
is now marked as occurring on the same line as the docstring not on the function s header line The current exception state has been moved from the frame object to the co routine This simplified the interpreter and fixed a couple of obscure bugs caused by having swap exception state when entering or exiting a generator Contributed by Mark Shannon in bpo 25612 Notable changes in Python 3 7 1 Starting in 3 7 1 Py_Initialize now consistently reads and respects all of the same environment settings as Py_Main in earlier Python versions it respected an ill defined subset of those environment variables while in Python 3 7 0 it didn t read any of them due to bpo 34247 If this behavior is unwanted set Py_IgnoreEnvironmentFlag to 1 before calling Py_Initialize In 3 7 1 the C API for Context Variables was updated to use PyObject pointers See also bpo 34762 In 3 7 1 the tokenize module now implicitly emits a NEWLINE token when provided with input that does not have a trailing new line This behavior now matches what the C tokenizer does internally Contributed by Ammar Askar in bpo 33899 Notable changes in Python 3 7 2 In 3 7 2 venv on Windows no longer copies the original binaries but creates redirector scripts named python exe and pythonw exe instead This resolves a long standing issue where all virtual environments would have to be upgraded or recreated with each Python update However note that this release will still require recreation of virtual environments in order to get the new scripts Notable changes in Python 3 7 6 Due to significant security concerns the reuse_address parameter of asyncio loop create_datagram_endpoint is no longer supported This is because of the behavior of the socket option SO_REUSEADDR in UDP For more details see the documentation for loop create_datagram_endpoint Contributed by Kyle Stanley Antoine Pitrou and Yury Selivanov in bpo 37228 Notable changes in Python 3 7 10 Earlier Python versions allowed using both and as query parameter separators in urllib parse parse_qs and urllib parse parse_qsl Due to security concerns and to conform with newer W3C recommendations this has been changed to allow only a single separator key with as the default This change also affects cgi parse and cgi parse_multipart as they use the affected functions internally For more details please see their respective documentation Contributed by Adam Goldschmidt Senthil Kumaran and Ken Jin in bpo 42967 Notable changes in Python 3 7 11 A security fix alters the ftplib FTP behavior to not trust the IPv4 address sent from the remote server when setting up a passive data channel We reuse the ftp server IP address instead For unusual code requiring the old behavior set a trust_server_pasv_ipv4_address attribute on your FTP instance to True See gh 87451 The presence of newline or tab characters in parts of a URL allows for some forms of attacks Following the WHATWG specification that updates RFC 3986 ASCII newline n r and tab t characters are stripped from the URL by the parser urllib parse preventing such attacks The removal characters are controlled by a new module level variable urllib parse _UNSAFE_URL_BYTES_TO_REMOVE See gh 88048 Notable security feature in 3 7 14 Converting between int and str in bases other than 2 binary 4 8 octal 16 hexadecimal or 32 such as base 10 decimal now raises a ValueError if the number of digits in string form is above a limit to avoid potential denial of service attacks due to the algorithmic complexity This is a mitigation for CVE 2020 10735 This limit can be configured or disabled by environment variable command line flag or sys APIs See the integer string conversion length limitation documentation The default limit is 4300 digits in string form
en
null
2,361
getopt C style parser for command line options Source code Lib getopt py Note The getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt function Users who are unfamiliar with the C getopt function or who would like to write less code and get better help and error messages should consider using the argparse module instead This module helps scripts to parse the command line arguments in sys argv It supports the same conventions as the Unix getopt function including the special meanings of arguments of the form and Long options similar to those supported by GNU software may be used as well via an optional third argument This module provides two functions and an exception getopt getopt args shortopts longopts Parses command line options and parameter list args is the argument list to be parsed without the leading reference to the running program Typically this means sys argv 1 shortopts is the string of option letters that the script wants to recognize with options that require an argument followed by a colon i e the same format that Unix getopt uses Note Unlike GNU getopt after a non option argument all further arguments are considered also non options This is similar to the way non GNU Unix systems work longopts if specified must be a list of strings with the names of the long options which should be supported The leading characters should not be included in the option name Long options which require an argument should be followed by an equal sign Optional arguments are not supported To accept only long options shortopts should be an empty string Long options on the command line can be recognized so long as they provide a prefix of the option name that matches exactly one of the accepted options For example if longopts is foo frob the option fo will match as foo but f will not match uniquely so GetoptError will be raised The return value consists of two elements the first is a list of option value pairs the second is the list of program arguments left after the option list was stripped this is a trailing slice of args Each option and value pair returned has the option as its first element prefixed with a hyphen for short options e g x or two hyphens for long options e g long option and the option argument as its second element or an empty string if the option has no argument The options occur in the list in the same order in which they were found thus allowing multiple occurrences Long and short options may be mixed getopt gnu_getopt args shortopts longopts This function works like getopt except that GNU style scanning mode is used by default This means that option and non option arguments may be intermixed The getopt function stops processing options as soon as a non option argument is encountered If the first character of the option string is or if the environment variable POSIXLY_CORRECT is set then option processing stops as soon as a non option argument is encountered exception getopt GetoptError This is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none The argument to the exception is a string indicating the cause of the error For long options an argument given to an option which does not require one will also cause this exception to be raised The attributes msg and opt give the error message and related option if there is no specific option to which the exception relates opt is an empty string exception getopt error Alias for GetoptError for backward compatibility An example using only Unix style options import getopt args a b cfoo d bar a1 a2 split args a b cfoo d bar a1 a2 optlist args getopt getopt args abc d optlist a b c foo d bar args a1 a2 Using long option names is equally easy s condition foo testing output file abc def x a1 a2 args s split args condition foo testing output file abc def x a1 a2 optlist args getopt getopt args x condition output file testing optlist condition foo testing output file abc def x args a1 a2 In a script typical usage is something like this import getopt
en
null
2,362
sys def main try opts args getopt getopt sys argv 1 ho v help output except getopt GetoptError as err print help information and exit print err will print something like option a not recognized usage sys exit 2 output None verbose False for o a in opts if o v verbose True elif o in h help usage sys exit elif o in o output output a else assert False unhandled option if __name__ __main__ main Note that an equivalent command line interface could be produced with less code and more informative help and error messages by using the argparse module import argparse if __name__ __main__ parser argparse ArgumentParser parser add_argument o output parser add_argument v dest verbose action store_true args parser parse_args do something with args output do something with args verbose See also Module argparse Alternative command line option and argument parsing library
en
null
2,363
html HyperText Markup Language support Source code Lib html __init__ py This module defines utilities to manipulate HTML html escape s quote True Convert the characters and in string s to HTML safe sequences Use this if you need to display text that might contain such characters in HTML If the optional flag quote is true the characters and are also translated this helps for inclusion in an HTML attribute value delimited by quotes as in a href New in version 3 2 html unescape s Convert all named and numeric character references e g gt 62 x3e in the string s to the corresponding Unicode characters This function uses the rules defined by the HTML 5 standard for both valid and invalid character references and the list of HTML 5 named character references New in version 3 4 Submodules in the html package are html parser HTML XHTML parser with lenient parsing mode html entities HTML entity definitions
en
null
2,364
ipaddress IPv4 IPv6 manipulation library Source code Lib ipaddress py ipaddress provides the capabilities to create manipulate and operate on IPv4 and IPv6 addresses and networks The functions and classes in this module make it straightforward to handle various tasks related to IP addresses including checking whether or not two hosts are on the same subnet iterating over all hosts in a particular subnet checking whether or not a string represents a valid IP address or network definition and so on This is the full module API reference for an overview and introduction see An introduction to the ipaddress module New in version 3 3 Convenience factory functions The ipaddress module provides factory functions to conveniently create IP addresses networks and interfaces ipaddress ip_address address Return an IPv4Address or IPv6Address object depending on the IP address passed as argument Either IPv4 or IPv6 addresses may be supplied integers less than 2 32 will be considered to be IPv4 by default A ValueError is raised if address does not represent a valid IPv4 or IPv6 address ipaddress ip_address 192 168 0 1 IPv4Address 192 168 0 1 ipaddress ip_address 2001 db8 IPv6Address 2001 db8 ipaddress ip_network address strict True Return an IPv4Network or IPv6Network object depending on the IP address passed as argument address is a string or integer representing the IP network Either IPv4 or IPv6 networks may be supplied integers less than 2 32 will be considered to be IPv4 by default strict is passed to IPv4Network or IPv6Network constructor A ValueError is raised if address does not represent a valid IPv4 or IPv6 address or if the network has host bits set ipaddress ip_network 192 168 0 0 28 IPv4Network 192 168 0 0 28 ipaddress ip_interface address Return an IPv4Interface or IPv6Interface object depending on the IP address passed as argument address is a string or integer representing the IP address Either IPv4 or IPv6 addresses may be supplied integers less than 2 32 will be considered to be IPv4 by default A ValueError is raised if address does not represent a valid IPv4 or IPv6 address One downside of these convenience functions is that the need to handle both IPv4 and IPv6 formats means that error messages provide minimal information on the precise error as the functions don t know whether the IPv4 or IPv6 format was intended More detailed error reporting can be obtained by calling the appropriate version specific class constructors directly IP Addresses Address objects The IPv4Address and IPv6Address objects share a lot of common attributes Some attributes that are only meaningful for IPv6 addresses are also implemented by IPv4Address objects in order to make it easier to write code that handles both IP versions correctly Address objects are hashable so they can be used as keys in dictionaries class ipaddress IPv4Address address Construct an IPv4 address An AddressValueError is raised if address is not a valid IPv4 address The following constitutes a valid IPv4 address 1 A string in decimal dot notation consisting of four decimal integers in the inclusive range 0 255 separated by dots e g 192 168 0 1 Each integer represents an octet byte in the address Leading zeroes are not tolerated to prevent confusion with octal notation 2 An integer that fits into 32 bits 3 An integer packed into a bytes object of length 4 most significant octet first ipaddress IPv4Address 192 168 0 1 IPv4Address 192 168 0 1 ipaddress IPv4Address 3232235521 IPv4Address 192 168 0 1 ipaddress IPv4Address b xC0 xA8 x00 x01 IPv4Address 192 168 0 1 Changed in version 3 8 Leading zeros are tolerated even in ambiguous cases that look like octal notation Changed in version 3 9 5 Leading zeros are no longer tolerated and are treated as an error IPv4 address strings are now parsed as strict as glibc inet_pton version The appropriate version number 4 for IPv4 6 for IPv6 max_prefixlen The total number of bits in the address representation for this version 32 for IPv4 128 for IPv6 The prefix defines the number of leading bits in an address that are compared to determin
en
null
2,365
e whether or not an address is part of a network compressed exploded The string representation in dotted decimal notation Leading zeroes are never included in the representation As IPv4 does not define a shorthand notation for addresses with octets set to zero these two attributes are always the same as str addr for IPv4 addresses Exposing these attributes makes it easier to write display code that can handle both IPv4 and IPv6 addresses packed The binary representation of this address a bytes object of the appropriate length most significant octet first This is 4 bytes for IPv4 and 16 bytes for IPv6 reverse_pointer The name of the reverse DNS PTR record for the IP address e g ipaddress ip_address 127 0 0 1 reverse_pointer 1 0 0 127 in addr arpa ipaddress ip_address 2001 db8 1 reverse_pointer 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 b d 0 1 0 0 2 ip6 arpa This is the name that could be used for performing a PTR lookup not the resolved hostname itself New in version 3 5 is_multicast True if the address is reserved for multicast use See RFC 3171 for IPv4 or RFC 2373 for IPv6 is_private True if the address is allocated for private networks See iana ipv4 special registry for IPv4 or iana ipv6 special registry for IPv6 is_global True if the address is allocated for public networks See iana ipv4 special registry for IPv4 or iana ipv6 special registry for IPv6 New in version 3 4 is_unspecified True if the address is unspecified See RFC 5735 for IPv4 or RFC 2373 for IPv6 is_reserved True if the address is otherwise IETF reserved is_loopback True if this is a loopback address See RFC 3330 for IPv4 or RFC 2373 for IPv6 is_link_local True if the address is reserved for link local usage See RFC 3927 IPv4Address __format__ fmt Returns a string representation of the IP address controlled by an explicit format string fmt can be one of the following s the default option equivalent to str b for a zero padded binary string X or x for an uppercase or lowercase hexadecimal representation or n which is equivalent to b for IPv4 addresses and x for IPv6 For binary and hexadecimal representations the form specifier and the grouping option _ are available __format__ is used by format str format and f strings format ipaddress IPv4Address 192 168 0 1 192 168 0 1 b format ipaddress IPv4Address 192 168 0 1 0b11000000101010000000000000000001 f ipaddress IPv6Address 2001 db8 1000 s 2001 db8 1000 format ipaddress IPv6Address 2001 db8 1000 _X 2001_0DB8_0000_0000_0000_0000_0000_1000 _n format ipaddress IPv6Address 2001 db8 1000 0x2001_0db8_0000_0000_0000_0000_0000_1000 New in version 3 9 class ipaddress IPv6Address address Construct an IPv6 address An AddressValueError is raised if address is not a valid IPv6 address The following constitutes a valid IPv6 address 1 A string consisting of eight groups of four hexadecimal digits each group representing 16 bits The groups are separated by colons This describes an exploded longhand notation The string can also be compressed shorthand notation by various means See RFC 4291 for details For example 0000 0000 0000 0000 0000 0abc 0007 0def can be compressed to abc 7 def Optionally the string may also have a scope zone ID expressed with a suffix scope_id If present the scope ID must be non empty and may not contain See RFC 4007 for details For example fe80 1234 1 might identify address fe80 1234 on the first link of the node 2 An integer that fits into 128 bits 3 An integer packed into a bytes object of length 16 big endian ipaddress IPv6Address 2001 db8 1000 IPv6Address 2001 db8 1000 ipaddress IPv6Address ff02 5678 1 IPv6Address ff02 5678 1 compressed The short form of the address representation with leading zeroes in groups omitted and the longest sequence of groups consisting entirely of zeroes collapsed to a single empty group This is also the value returned by str addr for IPv6 addresses exploded The long form of the address representation with all leading zeroes and groups consisting entirely of zeroes included For the following attributes and methods see the corresponding documentation of the IPv4A
en
null
2,366
ddress class packed reverse_pointer version max_prefixlen is_multicast is_private is_global is_unspecified is_reserved is_loopback is_link_local New in version 3 4 is_global is_site_local True if the address is reserved for site local usage Note that the site local address space has been deprecated by RFC 3879 Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193 ipv4_mapped For addresses that appear to be IPv4 mapped addresses starting with FFFF 96 this property will report the embedded IPv4 address For any other address this property will be None scope_id For scoped addresses as defined by RFC 4007 this property identifies the particular zone of the address s scope that the address belongs to as a string When no scope zone is specified this property will be None sixtofour For addresses that appear to be 6to4 addresses starting with 2002 16 as defined by RFC 3056 this property will report the embedded IPv4 address For any other address this property will be None teredo For addresses that appear to be Teredo addresses starting with 2001 32 as defined by RFC 4380 this property will report the embedded server client IP address pair For any other address this property will be None IPv6Address __format__ fmt Refer to the corresponding method documentation in IPv4Address New in version 3 9 Conversion to Strings and Integers To interoperate with networking interfaces such as the socket module addresses must be converted to strings or integers This is handled using the str and int builtin functions str ipaddress IPv4Address 192 168 0 1 192 168 0 1 int ipaddress IPv4Address 192 168 0 1 3232235521 str ipaddress IPv6Address 1 1 int ipaddress IPv6Address 1 1 Note that IPv6 scoped addresses are converted to integers without scope zone ID Operators Address objects support some operators Unless stated otherwise operators can only be applied between compatible objects i e IPv4 with IPv4 IPv6 with IPv6 Comparison operators Address objects can be compared with the usual set of comparison operators Same IPv6 addresses with different scope zone IDs are not equal Some examples IPv4Address 127 0 0 2 IPv4Address 127 0 0 1 True IPv4Address 127 0 0 2 IPv4Address 127 0 0 1 False IPv4Address 127 0 0 2 IPv4Address 127 0 0 1 True IPv6Address fe80 1234 IPv6Address fe80 1234 1 False IPv6Address fe80 1234 1 IPv6Address fe80 1234 2 True Arithmetic operators Integers can be added to or subtracted from address objects Some examples IPv4Address 127 0 0 2 3 IPv4Address 127 0 0 5 IPv4Address 127 0 0 2 3 IPv4Address 126 255 255 255 IPv4Address 255 255 255 255 1 Traceback most recent call last File stdin line 1 in module ipaddress AddressValueError 4294967296 2 32 is not permitted as an IPv4 address IP Network definitions The IPv4Network and IPv6Network objects provide a mechanism for defining and inspecting IP network definitions A network definition consists of a mask and a network address and as such defines a range of IP addresses that equal the network address when masked binary AND with the mask For example a network definition with the mask 255 255 255 0 and the network address 192 168 1 0 consists of IP addresses in the inclusive range 192 168 1 0 to 192 168 1 255 Prefix net mask and host mask There are several equivalent ways to specify IP network masks A prefix nbits is a notation that denotes how many high order bits are set in the network mask A net mask is an IP address with some number of high order bits set Thus the prefix 24 is equivalent to the net mask 255 255 255 0 in IPv4 or ffff ff00 in IPv6 In addition a host mask is the logical inverse of a net mask and is sometimes used for example in Cisco access control lists to denote a network mask The host mask equivalent to 24 in IPv4 is 0 0 0 255 Network objects All attributes implemented by address objects are implemented by network objects as well In addition network objects implement additional attributes All of these are common between IPv4Network and IPv6Network so to avoid duplication they are only documented for IPv4Network Network objects
en
null
2,367
are hashable so they can be used as keys in dictionaries class ipaddress IPv4Network address strict True Construct an IPv4 network definition address can be one of the following 1 A string consisting of an IP address and an optional mask separated by a slash The IP address is the network address and the mask can be either a single number which means it s a prefix or a string representation of an IPv4 address If it s the latter the mask is interpreted as a net mask if it starts with a non zero field or as a host mask if it starts with a zero field with the single exception of an all zero mask which is treated as a net mask If no mask is provided it s considered to be 32 For example the following address specifications are equivalent 192 168 1 0 24 192 168 1 0 255 255 255 0 and 192 168 1 0 0 0 0 255 2 An integer that fits into 32 bits This is equivalent to a single address network with the network address being address and the mask being 32 3 An integer packed into a bytes object of length 4 big endian The interpretation is similar to an integer address 4 A two tuple of an address description and a netmask where the address description is either a string a 32 bits integer a 4 bytes packed integer or an existing IPv4Address object and the netmask is either an integer representing the prefix length e g 24 or a string representing the prefix mask e g 255 255 255 0 An AddressValueError is raised if address is not a valid IPv4 address A NetmaskValueError is raised if the mask is not valid for an IPv4 address If strict is True and host bits are set in the supplied address then ValueError is raised Otherwise the host bits are masked out to determine the appropriate network address Unless stated otherwise all network methods accepting other network address objects will raise TypeError if the argument s IP version is incompatible to self Changed in version 3 5 Added the two tuple form for the address constructor parameter version max_prefixlen Refer to the corresponding attribute documentation in IPv4Address is_multicast is_private is_unspecified is_reserved is_loopback is_link_local These attributes are true for the network as a whole if they are true for both the network address and the broadcast address network_address The network address for the network The network address and the prefix length together uniquely define a network broadcast_address The broadcast address for the network Packets sent to the broadcast address should be received by every host on the network hostmask The host mask as an IPv4Address object netmask The net mask as an IPv4Address object with_prefixlen compressed exploded A string representation of the network with the mask in prefix notation with_prefixlen and compressed are always the same as str network exploded uses the exploded form the network address with_netmask A string representation of the network with the mask in net mask notation with_hostmask A string representation of the network with the mask in host mask notation num_addresses The total number of addresses in the network prefixlen Length of the network prefix in bits hosts Returns an iterator over the usable hosts in the network The usable hosts are all the IP addresses that belong to the network except the network address itself and the network broadcast address For networks with a mask length of 31 the network address and network broadcast address are also included in the result Networks with a mask of 32 will return a list containing the single host address list ip_network 192 0 2 0 29 hosts IPv4Address 192 0 2 1 IPv4Address 192 0 2 2 IPv4Address 192 0 2 3 IPv4Address 192 0 2 4 IPv4Address 192 0 2 5 IPv4Address 192 0 2 6 list ip_network 192 0 2 0 31 hosts IPv4Address 192 0 2 0 IPv4Address 192 0 2 1 list ip_network 192 0 2 1 32 hosts IPv4Address 192 0 2 1 overlaps other True if this network is partly or wholly contained in other or other is wholly contained in this network address_exclude network Computes the network definitions resulting from removing the given network from this one Returns an iterator of network objects Raises ValueE
en
null
2,368
rror if network is not completely contained in this network n1 ip_network 192 0 2 0 28 n2 ip_network 192 0 2 1 32 list n1 address_exclude n2 IPv4Network 192 0 2 8 29 IPv4Network 192 0 2 4 30 IPv4Network 192 0 2 2 31 IPv4Network 192 0 2 0 32 subnets prefixlen_diff 1 new_prefix None The subnets that join to make the current network definition depending on the argument values prefixlen_diff is the amount our prefix length should be increased by new_prefix is the desired new prefix of the subnets it must be larger than our prefix One and only one of prefixlen_diff and new_prefix must be set Returns an iterator of network objects list ip_network 192 0 2 0 24 subnets IPv4Network 192 0 2 0 25 IPv4Network 192 0 2 128 25 list ip_network 192 0 2 0 24 subnets prefixlen_diff 2 IPv4Network 192 0 2 0 26 IPv4Network 192 0 2 64 26 IPv4Network 192 0 2 128 26 IPv4Network 192 0 2 192 26 list ip_network 192 0 2 0 24 subnets new_prefix 26 IPv4Network 192 0 2 0 26 IPv4Network 192 0 2 64 26 IPv4Network 192 0 2 128 26 IPv4Network 192 0 2 192 26 list ip_network 192 0 2 0 24 subnets new_prefix 23 Traceback most recent call last File stdin line 1 in module raise ValueError new prefix must be longer ValueError new prefix must be longer list ip_network 192 0 2 0 24 subnets new_prefix 25 IPv4Network 192 0 2 0 25 IPv4Network 192 0 2 128 25 supernet prefixlen_diff 1 new_prefix None The supernet containing this network definition depending on the argument values prefixlen_diff is the amount our prefix length should be decreased by new_prefix is the desired new prefix of the supernet it must be smaller than our prefix One and only one of prefixlen_diff and new_prefix must be set Returns a single network object ip_network 192 0 2 0 24 supernet IPv4Network 192 0 2 0 23 ip_network 192 0 2 0 24 supernet prefixlen_diff 2 IPv4Network 192 0 0 0 22 ip_network 192 0 2 0 24 supernet new_prefix 20 IPv4Network 192 0 0 0 20 subnet_of other Return True if this network is a subnet of other a ip_network 192 168 1 0 24 b ip_network 192 168 1 128 30 b subnet_of a True New in version 3 7 supernet_of other Return True if this network is a supernet of other a ip_network 192 168 1 0 24 b ip_network 192 168 1 128 30 a supernet_of b True New in version 3 7 compare_networks other Compare this network to other In this comparison only the network addresses are considered host bits aren t Returns either 1 0 or 1 ip_network 192 0 2 1 32 compare_networks ip_network 192 0 2 2 32 1 ip_network 192 0 2 1 32 compare_networks ip_network 192 0 2 0 32 1 ip_network 192 0 2 1 32 compare_networks ip_network 192 0 2 1 32 0 Deprecated since version 3 7 It uses the same ordering and comparison algorithm as and class ipaddress IPv6Network address strict True Construct an IPv6 network definition address can be one of the following 1 A string consisting of an IP address and an optional prefix length separated by a slash The IP address is the network address and the prefix length must be a single number the prefix If no prefix length is provided it s considered to be 128 Note that currently expanded netmasks are not supported That means 2001 db00 0 24 is a valid argument while 2001 db00 0 ffff ff00 is not 2 An integer that fits into 128 bits This is equivalent to a single address network with the network address being address and the mask being 128 3 An integer packed into a bytes object of length 16 big endian The interpretation is similar to an integer address 4 A two tuple of an address description and a netmask where the address description is either a string a 128 bits integer a 16 bytes packed integer or an existing IPv6Address object and the netmask is an integer representing the prefix length An AddressValueError is raised if address is not a valid IPv6 address A NetmaskValueError is raised if the mask is not valid for an IPv6 address If strict is True and host bits are set in the supplied address then ValueError is raised Otherwise the host bits are masked out to determine the appropriate network address Changed in version 3 5 Added the two tuple form for the address constructor parameter ver
en
null
2,369
sion max_prefixlen is_multicast is_private is_unspecified is_reserved is_loopback is_link_local network_address broadcast_address hostmask netmask with_prefixlen compressed exploded with_netmask with_hostmask num_addresses prefixlen hosts Returns an iterator over the usable hosts in the network The usable hosts are all the IP addresses that belong to the network except the Subnet Router anycast address For networks with a mask length of 127 the Subnet Router anycast address is also included in the result Networks with a mask of 128 will return a list containing the single host address overlaps other address_exclude network subnets prefixlen_diff 1 new_prefix None supernet prefixlen_diff 1 new_prefix None subnet_of other supernet_of other compare_networks other Refer to the corresponding attribute documentation in IPv4Network is_site_local These attribute is true for the network as a whole if it is true for both the network address and the broadcast address Operators Network objects support some operators Unless stated otherwise operators can only be applied between compatible objects i e IPv4 with IPv4 IPv6 with IPv6 Logical operators Network objects can be compared with the usual set of logical operators Network objects are ordered first by network address then by net mask Iteration Network objects can be iterated to list all the addresses belonging to the network For iteration all hosts are returned including unusable hosts for usable hosts use the hosts method An example for addr in IPv4Network 192 0 2 0 28 addr IPv4Address 192 0 2 0 IPv4Address 192 0 2 1 IPv4Address 192 0 2 2 IPv4Address 192 0 2 3 IPv4Address 192 0 2 4 IPv4Address 192 0 2 5 IPv4Address 192 0 2 6 IPv4Address 192 0 2 7 IPv4Address 192 0 2 8 IPv4Address 192 0 2 9 IPv4Address 192 0 2 10 IPv4Address 192 0 2 11 IPv4Address 192 0 2 12 IPv4Address 192 0 2 13 IPv4Address 192 0 2 14 IPv4Address 192 0 2 15 Networks as containers of addresses Network objects can act as containers of addresses Some examples IPv4Network 192 0 2 0 28 0 IPv4Address 192 0 2 0 IPv4Network 192 0 2 0 28 15 IPv4Address 192 0 2 15 IPv4Address 192 0 2 6 in IPv4Network 192 0 2 0 28 True IPv4Address 192 0 3 6 in IPv4Network 192 0 2 0 28 False Interface objects Interface objects are hashable so they can be used as keys in dictionaries class ipaddress IPv4Interface address Construct an IPv4 interface The meaning of address is as in the constructor of IPv4Network except that arbitrary host addresses are always accepted IPv4Interface is a subclass of IPv4Address so it inherits all the attributes from that class In addition the following attributes are available ip The address IPv4Address without network information interface IPv4Interface 192 0 2 5 24 interface ip IPv4Address 192 0 2 5 network The network IPv4Network this interface belongs to interface IPv4Interface 192 0 2 5 24 interface network IPv4Network 192 0 2 0 24 with_prefixlen A string representation of the interface with the mask in prefix notation interface IPv4Interface 192 0 2 5 24 interface with_prefixlen 192 0 2 5 24 with_netmask A string representation of the interface with the network as a net mask interface IPv4Interface 192 0 2 5 24 interface with_netmask 192 0 2 5 255 255 255 0 with_hostmask A string representation of the interface with the network as a host mask interface IPv4Interface 192 0 2 5 24 interface with_hostmask 192 0 2 5 0 0 0 255 class ipaddress IPv6Interface address Construct an IPv6 interface The meaning of address is as in the constructor of IPv6Network except that arbitrary host addresses are always accepted IPv6Interface is a subclass of IPv6Address so it inherits all the attributes from that class In addition the following attributes are available ip network with_prefixlen with_netmask with_hostmask Refer to the corresponding attribute documentation in IPv4Interface Operators Interface objects support some operators Unless stated otherwise operators can only be applied between compatible objects i e IPv4 with IPv4 IPv6 with IPv6 Logical operators Interface objects can be compared with the usual set of logic
en
null
2,370
al operators For equality comparison and both the IP address and network must be the same for the objects to be equal An interface will not compare equal to any address or network object For ordering etc the rules are different Interface and address objects with the same IP version can be compared and the address objects will always sort before the interface objects Two interface objects are first compared by their networks and if those are the same then by their IP addresses Other Module Level Functions The module also provides the following module level functions ipaddress v4_int_to_packed address Represent an address as 4 packed bytes in network big endian order address is an integer representation of an IPv4 IP address A ValueError is raised if the integer is negative or too large to be an IPv4 IP address ipaddress ip_address 3221225985 IPv4Address 192 0 2 1 ipaddress v4_int_to_packed 3221225985 b xc0 x00 x02 x01 ipaddress v6_int_to_packed address Represent an address as 16 packed bytes in network big endian order address is an integer representation of an IPv6 IP address A ValueError is raised if the integer is negative or too large to be an IPv6 IP address ipaddress summarize_address_range first last Return an iterator of the summarized network range given the first and last IP addresses first is the first IPv4Address or IPv6Address in the range and last is the last IPv4Address or IPv6Address in the range A TypeError is raised if first or last are not IP addresses or are not of the same version A ValueError is raised if last is not greater than first or if first address version is not 4 or 6 ipaddr for ipaddr in ipaddress summarize_address_range ipaddress IPv4Address 192 0 2 0 ipaddress IPv4Address 192 0 2 130 IPv4Network 192 0 2 0 25 IPv4Network 192 0 2 128 31 IPv4Network 192 0 2 130 32 ipaddress collapse_addresses addresses Return an iterator of the collapsed IPv4Network or IPv6Network objects addresses is an iterator of IPv4Network or IPv6Network objects A TypeError is raised if addresses contains mixed version objects ipaddr for ipaddr in ipaddress collapse_addresses ipaddress IPv4Network 192 0 2 0 25 ipaddress IPv4Network 192 0 2 128 25 IPv4Network 192 0 2 0 24 ipaddress get_mixed_type_key obj Return a key suitable for sorting between networks and addresses Address and Network objects are not sortable by default they re fundamentally different so the expression IPv4Address 192 0 2 0 IPv4Network 192 0 2 0 24 doesn t make sense There are some times however where you may wish to have ipaddress sort these anyway If you need to do this you can use this function as the key argument to sorted obj is either a network or address object Custom Exceptions To support more specific error reporting from class constructors the module defines the following exceptions exception ipaddress AddressValueError ValueError Any value error related to the address exception ipaddress NetmaskValueError ValueError Any value error related to the net mask
en
null
2,371
array Efficient arrays of numeric values This module defines an object type which can compactly represent an array of basic values characters integers floating point numbers Arrays are sequence types and behave very much like lists except that the type of objects stored in them is constrained The type is specified at object creation time by using a type code which is a single character The following type codes are defined Type code C Type Python Type Minimum size in bytes Notes b signed char int 1 B unsigned char int 1 u wchar_t Unicode character 2 1 h signed short int 2 H unsigned short int 2 i signed int int 2 I unsigned int int 2 l signed long int 4 L unsigned long int 4 q signed long long int 8 Q unsigned long long int 8 f float float 4 d double float 8 Notes 1 It can be 16 bits or 32 bits depending on the platform Changed in version 3 9 array u now uses wchar_t as C type instead of deprecated Py_UNICODE This change doesn t affect its behavior because Py_UNICODE is alias of wchar_t since Python 3 3 Deprecated since version 3 3 will be removed in version 4 0 The actual representation of values is determined by the machine architecture strictly speaking by the C implementation The actual size can be accessed through the array itemsize attribute The module defines the following item array typecodes A string with all available type codes The module defines the following type class array array typecode initializer A new array whose items are restricted by typecode and initialized from the optional initializer value which must be a bytes or bytearray object a Unicode string or iterable over elements of the appropriate type If given a bytes or bytearray object the initializer is passed to the new array s frombytes method if given a Unicode string the initializer is passed to the fromunicode method otherwise the initializer s iterator is passed to the extend method to add initial items to the array Array objects support the ordinary sequence operations of indexing slicing concatenation and multiplication When using slice assignment the assigned value must be an array object with the same type code in all other cases TypeError is raised Array objects also implement the buffer interface and may be used wherever bytes like objects are supported Raises an auditing event array __new__ with arguments typecode initializer typecode The typecode character used to create the array itemsize The length in bytes of one array item in the internal representation append x Append a new item with value x to the end of the array buffer_info Return a tuple address length giving the current memory address and the length in elements of the buffer used to hold array s contents The size of the memory buffer in bytes can be computed as array buffer_info 1 array itemsize This is occasionally useful when working with low level and inherently unsafe I O interfaces that require memory addresses such as certain ioctl operations The returned numbers are valid as long as the array exists and no length changing operations are applied to it Note When using array objects from code written in C or C the only way to effectively make use of this information it makes more sense to use the buffer interface supported by array objects This method is maintained for backward compatibility and should be avoided in new code The buffer interface is documented in Buffer Protocol byteswap Byteswap all items of the array This is only supported for values which are 1 2 4 or 8 bytes in size for other types of values RuntimeError is raised It is useful when reading data from a file written on a machine with a different byte order count x Return the number of occurrences of x in the array extend iterable Append items from iterable to the end of the array If iterable is another array it must have exactly the same type code if not TypeError will be raised If iterable is not an array it must be iterable and its elements must be the right type to be appended to the array frombytes buffer Appends items from the bytes like object interpreting its content as an array of machine values
en
null
2,372
as if it had been read from a file using the fromfile method New in version 3 2 fromstring is renamed to frombytes for clarity fromfile f n Read n items as machine values from the file object f and append them to the end of the array If less than n items are available EOFError is raised but the items that were available are still inserted into the array fromlist list Append items from the list This is equivalent to for x in list a append x except that if there is a type error the array is unchanged fromunicode s Extends this array with data from the given Unicode string The array must have type code u otherwise a ValueError is raised Use array frombytes unicodestring encode enc to append Unicode data to an array of some other type index x start stop Return the smallest i such that i is the index of the first occurrence of x in the array The optional arguments start and stop can be specified to search for x within a subsection of the array Raise ValueError if x is not found Changed in version 3 10 Added optional start and stop parameters insert i x Insert a new item with value x in the array before position i Negative values are treated as being relative to the end of the array pop i Removes the item with the index i from the array and returns it The optional argument defaults to 1 so that by default the last item is removed and returned remove x Remove the first occurrence of x from the array reverse Reverse the order of the items in the array tobytes Convert the array to an array of machine values and return the bytes representation the same sequence of bytes that would be written to a file by the tofile method New in version 3 2 tostring is renamed to tobytes for clarity tofile f Write all items as machine values to the file object f tolist Convert the array to an ordinary list with the same items tounicode Convert the array to a Unicode string The array must have a type u otherwise a ValueError is raised Use array tobytes decode enc to obtain a Unicode string from an array of some other type The string representation of array objects has the form array typecode initializer The initializer is omitted if the array is empty otherwise it is a Unicode string if the typecode is u otherwise it is a list of numbers The string representation is guaranteed to be able to be converted back to an array with the same type and value using eval so long as the array class has been imported using from array import array Variables inf and nan must also be defined if it contains corresponding floating point values Examples array l array u hello u2641 array l 1 2 3 4 5 array d 1 0 2 0 3 14 inf nan See also Module struct Packing and unpacking of heterogeneous binary data Module xdrlib Packing and unpacking of External Data Representation XDR data as used in some remote procedure call systems NumPy The NumPy package defines another array type
en
null
2,373
mailbox Manipulate mailboxes in various formats Source code Lib mailbox py This module defines two classes Mailbox and Message for accessing and manipulating on disk mailboxes and the messages they contain Mailbox offers a dictionary like mapping from keys to messages Message extends the email message module s Message class with format specific state and behavior Supported mailbox formats are Maildir mbox MH Babyl and MMDF See also Module email Represent and manipulate messages Mailbox objects class mailbox Mailbox A mailbox which may be inspected and modified The Mailbox class defines an interface and is not intended to be instantiated Instead format specific subclasses should inherit from Mailbox and your code should instantiate a particular subclass The Mailbox interface is dictionary like with small keys corresponding to messages Keys are issued by the Mailbox instance with which they will be used and are only meaningful to that Mailbox instance A key continues to identify a message even if the corresponding message is modified such as by replacing it with another message Messages may be added to a Mailbox instance using the set like method add and removed using a del statement or the set like methods remove and discard Mailbox interface semantics differ from dictionary semantics in some noteworthy ways Each time a message is requested a new representation typically a Message instance is generated based upon the current state of the mailbox Similarly when a message is added to a Mailbox instance the provided message representation s contents are copied In neither case is a reference to the message representation kept by the Mailbox instance The default Mailbox iterator iterates over message representations not keys as the default dictionary iterator does Moreover modification of a mailbox during iteration is safe and well defined Messages added to the mailbox after an iterator is created will not be seen by the iterator Messages removed from the mailbox before the iterator yields them will be silently skipped though using a key from an iterator may result in a KeyError exception if the corresponding message is subsequently removed Warning Be very cautious when modifying mailboxes that might be simultaneously changed by some other process The safest mailbox format to use for such tasks is Maildir try to avoid using single file formats such as mbox for concurrent writing If you re modifying a mailbox you must lock it by calling the lock and unlock methods before reading any messages in the file or making any changes by adding or deleting a message Failing to lock the mailbox runs the risk of losing messages or corrupting the entire mailbox Mailbox instances have the following methods add message Add message to the mailbox and return the key that has been assigned to it Parameter message may be a Message instance an email message Message instance a string a byte string or a file like object which should be open in binary mode If message is an instance of the appropriate format specific Message subclass e g if it s an mboxMessage instance and this is an mbox instance its format specific information is used Otherwise reasonable defaults for format specific information are used Changed in version 3 2 Support for binary input was added remove key __delitem__ key discard key Delete the message corresponding to key from the mailbox If no such message exists a KeyError exception is raised if the method was called as remove or __delitem__ but no exception is raised if the method was called as discard The behavior of discard may be preferred if the underlying mailbox format supports concurrent modification by other processes __setitem__ key message Replace the message corresponding to key with message Raise a KeyError exception if no message already corresponds to key As with add parameter message may be a Message instance an email message Message instance a string a byte string or a file like object which should be open in binary mode If message is an instance of the appropriate format specific Message subclass e g if it s an m
en
null
2,374
boxMessage instance and this is an mbox instance its format specific information is used Otherwise the format specific information of the message that currently corresponds to key is left unchanged iterkeys Return an iterator over all keys keys The same as iterkeys except that a list is returned rather than an iterator itervalues __iter__ Return an iterator over representations of all messages The messages are represented as instances of the appropriate format specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized Note The behavior of __iter__ is unlike that of dictionaries which iterate over keys values The same as itervalues except that a list is returned rather than an iterator iteritems Return an iterator over key message pairs where key is a key and message is a message representation The messages are represented as instances of the appropriate format specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized items The same as iteritems except that a list of pairs is returned rather than an iterator of pairs get key default None __getitem__ key Return a representation of the message corresponding to key If no such message exists default is returned if the method was called as get and a KeyError exception is raised if the method was called as __getitem__ The message is represented as an instance of the appropriate format specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized get_message key Return a representation of the message corresponding to key as an instance of the appropriate format specific Message subclass or raise a KeyError exception if no such message exists get_bytes key Return a byte representation of the message corresponding to key or raise a KeyError exception if no such message exists New in version 3 2 get_string key Return a string representation of the message corresponding to key or raise a KeyError exception if no such message exists The message is processed through email message Message to convert it to a 7bit clean representation get_file key Return a file like representation of the message corresponding to key or raise a KeyError exception if no such message exists The file like object behaves as if open in binary mode This file should be closed once it is no longer needed Changed in version 3 2 The file object really is a binary file previously it was incorrectly returned in text mode Also the file like object now supports the context manager protocol you can use a with statement to automatically close it Note Unlike other representations of messages file like representations are not necessarily independent of the Mailbox instance that created them or of the underlying mailbox More specific documentation is provided by each subclass __contains__ key Return True if key corresponds to a message False otherwise __len__ Return a count of messages in the mailbox clear Delete all messages from the mailbox pop key default None Return a representation of the message corresponding to key and delete the message If no such message exists return default The message is represented as an instance of the appropriate format specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized popitem Return an arbitrary key message pair where key is a key and message is a message representation and delete the corresponding message If the mailbox is empty raise a KeyError exception The message is represented as an instance of the appropriate format specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized update arg Parameter arg should be a key to message mapping or an iterable of key message pairs Updates the mailbox so that for each given key and message the message corresponding to key is set to message as if by using __setitem__ As with __setitem__ each key must already correspond to a message in the mailbox or else a KeyError excepti
en
null
2,375
on will be raised so in general it is incorrect for arg to be a Mailbox instance Note Unlike with dictionaries keyword arguments are not supported flush Write any pending changes to the filesystem For some Mailbox subclasses changes are always written immediately and flush does nothing but you should still make a habit of calling this method lock Acquire an exclusive advisory lock on the mailbox so that other processes know not to modify it An ExternalClashError is raised if the lock is not available The particular locking mechanisms used depend upon the mailbox format You should always lock the mailbox before making any modifications to its contents unlock Release the lock on the mailbox if any close Flush the mailbox unlock it if necessary and close any open files For some Mailbox subclasses this method does nothing Maildir objects class mailbox Maildir dirname factory None create True A subclass of Mailbox for mailboxes in Maildir format Parameter factory is a callable object that accepts a file like message representation which behaves as if opened in binary mode and returns a custom representation If factory is None MaildirMessage is used as the default message representation If create is True the mailbox is created if it does not exist If create is True and the dirname path exists it will be treated as an existing maildir without attempting to verify its directory layout It is for historical reasons that dirname is named as such rather than path Maildir is a directory based mailbox format invented for the qmail mail transfer agent and now widely supported by other programs Messages in a Maildir mailbox are stored in separate files within a common directory structure This design allows Maildir mailboxes to be accessed and modified by multiple unrelated programs without data corruption so file locking is unnecessary Maildir mailboxes contain three subdirectories namely tmp new and cur Messages are created momentarily in the tmp subdirectory and then moved to the new subdirectory to finalize delivery A mail user agent may subsequently move the message to the cur subdirectory and store information about the state of the message in a special info section appended to its file name Folders of the style introduced by the Courier mail transfer agent are also supported Any subdirectory of the main mailbox is considered a folder if is the first character in its name Folder names are represented by Maildir without the leading Each folder is itself a Maildir mailbox but should not contain other folders Instead a logical nesting is indicated using to delimit levels e g Archived 2005 07 colon The Maildir specification requires the use of a colon in certain message file names However some operating systems do not permit this character in file names If you wish to use a Maildir like format on such an operating system you should specify another character to use instead The exclamation point is a popular choice For example import mailbox mailbox Maildir colon The colon attribute may also be set on a per instance basis Maildir instances have all of the methods of Mailbox in addition to the following list_folders Return a list of the names of all folders get_folder folder Return a Maildir instance representing the folder whose name is folder A NoSuchMailboxError exception is raised if the folder does not exist add_folder folder Create a folder whose name is folder and return a Maildir instance representing it remove_folder folder Delete the folder whose name is folder If the folder contains any messages a NotEmptyError exception will be raised and the folder will not be deleted clean Delete temporary files from the mailbox that have not been accessed in the last 36 hours The Maildir specification says that mail reading programs should do this occasionally Some Mailbox methods implemented by Maildir deserve special remarks add message __setitem__ key message update arg Warning These methods generate unique file names based upon the current process ID When using multiple threads undetected name clashes may occur and cause corruption of t
en
null
2,376
he mailbox unless threads are coordinated to avoid using these methods to manipulate the same mailbox simultaneously flush All changes to Maildir mailboxes are immediately applied so this method does nothing lock unlock Maildir mailboxes do not support or require locking so these methods do nothing close Maildir instances do not keep any open files and the underlying mailboxes do not support locking so this method does nothing get_file key Depending upon the host platform it may not be possible to modify or remove the underlying message while the returned file remains open See also maildir man page from Courier A specification of the format Describes a common extension for supporting folders Using maildir format Notes on Maildir by its inventor Includes an updated name creation scheme and details on info semantics mbox objects class mailbox mbox path factory None create True A subclass of Mailbox for mailboxes in mbox format Parameter factory is a callable object that accepts a file like message representation which behaves as if opened in binary mode and returns a custom representation If factory is None mboxMessage is used as the default message representation If create is True the mailbox is created if it does not exist The mbox format is the classic format for storing mail on Unix systems All messages in an mbox mailbox are stored in a single file with the beginning of each message indicated by a line whose first five characters are From Several variations of the mbox format exist to address perceived shortcomings in the original In the interest of compatibility mbox implements the original format which is sometimes referred to as mboxo This means that the Content Length header if present is ignored and that any occurrences of From at the beginning of a line in a message body are transformed to From when storing the message although occurrences of From are not transformed to From when reading the message Some Mailbox methods implemented by mbox deserve special remarks get_file key Using the file after calling flush or close on the mbox instance may yield unpredictable results or raise an exception lock unlock Three locking mechanisms are used dot locking and if available the flock and lockf system calls See also mbox man page from tin A specification of the format with details on locking Configuring Netscape Mail on Unix Why The Content Length Format is Bad An argument for using the original mbox format rather than a variation mbox is a family of several mutually incompatible mailbox formats A history of mbox variations MH objects class mailbox MH path factory None create True A subclass of Mailbox for mailboxes in MH format Parameter factory is a callable object that accepts a file like message representation which behaves as if opened in binary mode and returns a custom representation If factory is None MHMessage is used as the default message representation If create is True the mailbox is created if it does not exist MH is a directory based mailbox format invented for the MH Message Handling System a mail user agent Each message in an MH mailbox resides in its own file An MH mailbox may contain other MH mailboxes called folders in addition to messages Folders may be nested indefinitely MH mailboxes also support sequences which are named lists used to logically group messages without moving them to sub folders Sequences are defined in a file called mh_sequences in each folder The MH class manipulates MH mailboxes but it does not attempt to emulate all of mh s behaviors In particular it does not modify and is not affected by the context or mh_profile files that are used by mh to store its state and configuration MH instances have all of the methods of Mailbox in addition to the following list_folders Return a list of the names of all folders get_folder folder Return an MH instance representing the folder whose name is folder A NoSuchMailboxError exception is raised if the folder does not exist add_folder folder Create a folder whose name is folder and return an MH instance representing it remove_folder folder Delet
en
null
2,377
e the folder whose name is folder If the folder contains any messages a NotEmptyError exception will be raised and the folder will not be deleted get_sequences Return a dictionary of sequence names mapped to key lists If there are no sequences the empty dictionary is returned set_sequences sequences Re define the sequences that exist in the mailbox based upon sequences a dictionary of names mapped to key lists like returned by get_sequences pack Rename messages in the mailbox as necessary to eliminate gaps in numbering Entries in the sequences list are updated correspondingly Note Already issued keys are invalidated by this operation and should not be subsequently used Some Mailbox methods implemented by MH deserve special remarks remove key __delitem__ key discard key These methods immediately delete the message The MH convention of marking a message for deletion by prepending a comma to its name is not used lock unlock Three locking mechanisms are used dot locking and if available the flock and lockf system calls For MH mailboxes locking the mailbox means locking the mh_sequences file and only for the duration of any operations that affect them locking individual message files get_file key Depending upon the host platform it may not be possible to remove the underlying message while the returned file remains open flush All changes to MH mailboxes are immediately applied so this method does nothing close MH instances do not keep any open files so this method is equivalent to unlock See also nmh Message Handling System Home page of nmh an updated version of the original mh MH nmh Email for Users Programmers A GPL licensed book on mh and nmh with some information on the mailbox format Babyl objects class mailbox Babyl path factory None create True A subclass of Mailbox for mailboxes in Babyl format Parameter factory is a callable object that accepts a file like message representation which behaves as if opened in binary mode and returns a custom representation If factory is None BabylMessage is used as the default message representation If create is True the mailbox is created if it does not exist Babyl is a single file mailbox format used by the Rmail mail user agent included with Emacs The beginning of a message is indicated by a line containing the two characters Control Underscore 037 and Control L 014 The end of a message is indicated by the start of the next message or in the case of the last message a line containing a Control Underscore 037 character Messages in a Babyl mailbox have two sets of headers original headers and so called visible headers Visible headers are typically a subset of the original headers that have been reformatted or abridged to be more attractive Each message in a Babyl mailbox also has an accompanying list of labels or short strings that record extra information about the message and a list of all user defined labels found in the mailbox is kept in the Babyl options section Babyl instances have all of the methods of Mailbox in addition to the following get_labels Return a list of the names of all user defined labels used in the mailbox Note The actual messages are inspected to determine which labels exist in the mailbox rather than consulting the list of labels in the Babyl options section but the Babyl section is updated whenever the mailbox is modified Some Mailbox methods implemented by Babyl deserve special remarks get_file key In Babyl mailboxes the headers of a message are not stored contiguously with the body of the message To generate a file like representation the headers and body are copied together into an io BytesIO instance which has an API identical to that of a file As a result the file like object is truly independent of the underlying mailbox but does not save memory compared to a string representation lock unlock Three locking mechanisms are used dot locking and if available the flock and lockf system calls See also Format of Version 5 Babyl Files A specification of the Babyl format Reading Mail with Rmail The Rmail manual with some information on Babyl semantics MMDF obj
en
null
2,378
ects class mailbox MMDF path factory None create True A subclass of Mailbox for mailboxes in MMDF format Parameter factory is a callable object that accepts a file like message representation which behaves as if opened in binary mode and returns a custom representation If factory is None MMDFMessage is used as the default message representation If create is True the mailbox is created if it does not exist MMDF is a single file mailbox format invented for the Multichannel Memorandum Distribution Facility a mail transfer agent Each message is in the same form as an mbox message but is bracketed before and after by lines containing four Control A 001 characters As with the mbox format the beginning of each message is indicated by a line whose first five characters are From but additional occurrences of From are not transformed to From when storing messages because the extra message separator lines prevent mistaking such occurrences for the starts of subsequent messages Some Mailbox methods implemented by MMDF deserve special remarks get_file key Using the file after calling flush or close on the MMDF instance may yield unpredictable results or raise an exception lock unlock Three locking mechanisms are used dot locking and if available the flock and lockf system calls See also mmdf man page from tin A specification of MMDF format from the documentation of tin a newsreader MMDF A Wikipedia article describing the Multichannel Memorandum Distribution Facility Message objects class mailbox Message message None A subclass of the email message module s Message Subclasses of mailbox Message add mailbox format specific state and behavior If message is omitted the new instance is created in a default empty state If message is an email message Message instance its contents are copied furthermore any format specific information is converted insofar as possible if message is a Message instance If message is a string a byte string or a file it should contain an RFC 2822 compliant message which is read and parsed Files should be open in binary mode but text mode files are accepted for backward compatibility The format specific state and behaviors offered by subclasses vary but in general it is only the properties that are not specific to a particular mailbox that are supported although presumably the properties are specific to a particular mailbox format For example file offsets for single file mailbox formats and file names for directory based mailbox formats are not retained because they are only applicable to the original mailbox But state such as whether a message has been read by the user or marked as important is retained because it applies to the message itself There is no requirement that Message instances be used to represent messages retrieved using Mailbox instances In some situations the time and memory required to generate Message representations might not be acceptable For such situations Mailbox instances also offer string and file like representations and a custom message factory may be specified when a Mailbox instance is initialized MaildirMessage objects class mailbox MaildirMessage message None A message with Maildir specific behaviors Parameter message has the same meaning as with the Message constructor Typically a mail user agent application moves all of the messages in the new subdirectory to the cur subdirectory after the first time the user opens and closes the mailbox recording that the messages are old whether or not they ve actually been read Each message in cur has an info section added to its file name to store information about its state Some mail readers may also add an info section to messages in new The info section may take one of two forms it may contain 2 followed by a list of standardized flags e g 2 FR or it may contain 1 followed by so called experimental information Standard flags for Maildir messages are as follows Flag Meaning Explanation D Draft Under composition F Flagged Marked as important P Passed Forwarded resent or bounced R Replied Replied to S Seen Read T Trashed Marked for subsequent
en
null
2,379
deletion MaildirMessage instances offer the following methods get_subdir Return either new if the message should be stored in the new subdirectory or cur if the message should be stored in the cur subdirectory Note A message is typically moved from new to cur after its mailbox has been accessed whether or not the message is has been read A message msg has been read if S in msg get_flags is True set_subdir subdir Set the subdirectory the message should be stored in Parameter subdir must be either new or cur get_flags Return a string specifying the flags that are currently set If the message complies with the standard Maildir format the result is the concatenation in alphabetical order of zero or one occurrence of each of D F P R S and T The empty string is returned if no flags are set or if info contains experimental semantics set_flags flags Set the flags specified by flags and unset all others add_flag flag Set the flag s specified by flag without changing other flags To add more than one flag at a time flag may be a string of more than one character The current info is overwritten whether or not it contains experimental information rather than flags remove_flag flag Unset the flag s specified by flag without changing other flags To remove more than one flag at a time flag maybe a string of more than one character If info contains experimental information rather than flags the current info is not modified get_date Return the delivery date of the message as a floating point number representing seconds since the epoch set_date date Set the delivery date of the message to date a floating point number representing seconds since the epoch get_info Return a string containing the info for a message This is useful for accessing and modifying info that is experimental i e not a list of flags set_info info Set info to info which should be a string When a MaildirMessage instance is created based upon an mboxMessage or MMDFMessage instance the Status and X Status headers are omitted and the following conversions take place Resulting state mboxMessage or MMDFMessage state cur subdirectory O flag F flag F flag R flag A flag S flag R flag T flag D flag When a MaildirMessage instance is created based upon an MHMessage instance the following conversions take place Resulting state MHMessage state cur subdirectory unseen sequence cur subdirectory and S flag no unseen sequence F flag flagged sequence R flag replied sequence When a MaildirMessage instance is created based upon a BabylMessage instance the following conversions take place Resulting state BabylMessage state cur subdirectory unseen label cur subdirectory and S flag no unseen label P flag forwarded or resent label R flag answered label T flag deleted label mboxMessage objects class mailbox mboxMessage message None A message with mbox specific behaviors Parameter message has the same meaning as with the Message constructor Messages in an mbox mailbox are stored together in a single file The sender s envelope address and the time of delivery are typically stored in a line beginning with From that is used to indicate the start of a message though there is considerable variation in the exact format of this data among mbox implementations Flags that indicate the state of the message such as whether it has been read or marked as important are typically stored in Status and X Status headers Conventional flags for mbox messages are as follows Flag Meaning Explanation R Read Read O Old Previously detected by MUA D Deleted Marked for subsequent deletion F Flagged Marked as important A Answered Replied to The R and O flags are stored in the Status header and the D F and A flags are stored in the X Status header The flags and headers typically appear in the order mentioned mboxMessage instances offer the following methods get_from Return a string representing the From line that marks the start of the message in an mbox mailbox The leading From and the trailing newline are excluded set_from from_ time_ None Set the From line to from_ which should be specified without a leading From or traili
en
null
2,380
ng newline For convenience time_ may be specified and will be formatted appropriately and appended to from_ If time_ is specified it should be a time struct_time instance a tuple suitable for passing to time strftime or True to use time gmtime get_flags Return a string specifying the flags that are currently set If the message complies with the conventional format the result is the concatenation in the following order of zero or one occurrence of each of R O D F and A set_flags flags Set the flags specified by flags and unset all others Parameter flags should be the concatenation in any order of zero or more occurrences of each of R O D F and A add_flag flag Set the flag s specified by flag without changing other flags To add more than one flag at a time flag may be a string of more than one character remove_flag flag Unset the flag s specified by flag without changing other flags To remove more than one flag at a time flag maybe a string of more than one character When an mboxMessage instance is created based upon a MaildirMessage instance a From line is generated based upon the MaildirMessage instance s delivery date and the following conversions take place Resulting state MaildirMessage state R flag S flag O flag cur subdirectory D flag T flag F flag F flag A flag R flag When an mboxMessage instance is created based upon an MHMessage instance the following conversions take place Resulting state MHMessage state R flag and O flag no unseen sequence O flag unseen sequence F flag flagged sequence A flag replied sequence When an mboxMessage instance is created based upon a BabylMessage instance the following conversions take place Resulting state BabylMessage state R flag and O flag no unseen label O flag unseen label D flag deleted label A flag answered label When a mboxMessage instance is created based upon an MMDFMessage instance the From line is copied and all flags directly correspond Resulting state MMDFMessage state R flag R flag O flag O flag D flag D flag F flag F flag A flag A flag MHMessage objects class mailbox MHMessage message None A message with MH specific behaviors Parameter message has the same meaning as with the Message constructor MH messages do not support marks or flags in the traditional sense but they do support sequences which are logical groupings of arbitrary messages Some mail reading programs although not the standard mh and nmh use sequences in much the same way flags are used with other formats as follows Sequence Explanation unseen Not read but previously detected by MUA replied Replied to flagged Marked as important MHMessage instances offer the following methods get_sequences Return a list of the names of sequences that include this message set_sequences sequences Set the list of sequences that include this message add_sequence sequence Add sequence to the list of sequences that include this message remove_sequence sequence Remove sequence from the list of sequences that include this message When an MHMessage instance is created based upon a MaildirMessage instance the following conversions take place Resulting state MaildirMessage state unseen sequence no S flag replied sequence R flag flagged sequence F flag When an MHMessage instance is created based upon an mboxMessage or MMDFMessage instance the Status and X Status headers are omitted and the following conversions take place Resulting state mboxMessage or MMDFMessage state unseen sequence no R flag replied sequence A flag flagged sequence F flag When an MHMessage instance is created based upon a BabylMessage instance the following conversions take place Resulting state BabylMessage state unseen sequence unseen label replied sequence answered label BabylMessage objects class mailbox BabylMessage message None A message with Babyl specific behaviors Parameter message has the same meaning as with the Message constructor Certain message labels called attributes are defined by convention to have special meanings The attributes are as follows Label Explanation unseen Not read but previously detected by MUA deleted Marked for subsequent dele
en
null
2,381
tion filed Copied to another file or mailbox answered Replied to forwarded Forwarded edited Modified by the user resent Resent By default Rmail displays only visible headers The BabylMessage class though uses the original headers because they are more complete Visible headers may be accessed explicitly if desired BabylMessage instances offer the following methods get_labels Return a list of labels on the message set_labels labels Set the list of labels on the message to labels add_label label Add label to the list of labels on the message remove_label label Remove label from the list of labels on the message get_visible Return an Message instance whose headers are the message s visible headers and whose body is empty set_visible visible Set the message s visible headers to be the same as the headers in message Parameter visible should be a Message instance an email message Message instance a string or a file like object which should be open in text mode update_visible When a BabylMessage instance s original headers are modified the visible headers are not automatically modified to correspond This method updates the visible headers as follows each visible header with a corresponding original header is set to the value of the original header each visible header without a corresponding original header is removed and any of Date From Reply To To CC and Subject that are present in the original headers but not the visible headers are added to the visible headers When a BabylMessage instance is created based upon a MaildirMessage instance the following conversions take place Resulting state MaildirMessage state unseen label no S flag deleted label T flag answered label R flag forwarded label P flag When a BabylMessage instance is created based upon an mboxMessage or MMDFMessage instance the Status and X Status headers are omitted and the following conversions take place Resulting state mboxMessage or MMDFMessage state unseen label no R flag deleted label D flag answered label A flag When a BabylMessage instance is created based upon an MHMessage instance the following conversions take place Resulting state MHMessage state unseen label unseen sequence answered label replied sequence MMDFMessage objects class mailbox MMDFMessage message None A message with MMDF specific behaviors Parameter message has the same meaning as with the Message constructor As with message in an mbox mailbox MMDF messages are stored with the sender s address and the delivery date in an initial line beginning with From Likewise flags that indicate the state of the message are typically stored in Status and X Status headers Conventional flags for MMDF messages are identical to those of mbox message and are as follows Flag Meaning Explanation R Read Read O Old Previously detected by MUA D Deleted Marked for subsequent deletion F Flagged Marked as important A Answered Replied to The R and O flags are stored in the Status header and the D F and A flags are stored in the X Status header The flags and headers typically appear in the order mentioned MMDFMessage instances offer the following methods which are identical to those offered by mboxMessage get_from Return a string representing the From line that marks the start of the message in an mbox mailbox The leading From and the trailing newline are excluded set_from from_ time_ None Set the From line to from_ which should be specified without a leading From or trailing newline For convenience time_ may be specified and will be formatted appropriately and appended to from_ If time_ is specified it should be a time struct_time instance a tuple suitable for passing to time strftime or True to use time gmtime get_flags Return a string specifying the flags that are currently set If the message complies with the conventional format the result is the concatenation in the following order of zero or one occurrence of each of R O D F and A set_flags flags Set the flags specified by flags and unset all others Parameter flags should be the concatenation in any order of zero or more occurrences of each of R O D F and A add_
en
null
2,382
flag flag Set the flag s specified by flag without changing other flags To add more than one flag at a time flag may be a string of more than one character remove_flag flag Unset the flag s specified by flag without changing other flags To remove more than one flag at a time flag maybe a string of more than one character When an MMDFMessage instance is created based upon a MaildirMessage instance a From line is generated based upon the MaildirMessage instance s delivery date and the following conversions take place Resulting state MaildirMessage state R flag S flag O flag cur subdirectory D flag T flag F flag F flag A flag R flag When an MMDFMessage instance is created based upon an MHMessage instance the following conversions take place Resulting state MHMessage state R flag and O flag no unseen sequence O flag unseen sequence F flag flagged sequence A flag replied sequence When an MMDFMessage instance is created based upon a BabylMessage instance the following conversions take place Resulting state BabylMessage state R flag and O flag no unseen label O flag unseen label D flag deleted label A flag answered label When an MMDFMessage instance is created based upon an mboxMessage instance the From line is copied and all flags directly correspond Resulting state mboxMessage state R flag R flag O flag O flag D flag D flag F flag F flag A flag A flag Exceptions The following exception classes are defined in the mailbox module exception mailbox Error The based class for all other module specific exceptions exception mailbox NoSuchMailboxError Raised when a mailbox is expected but is not found such as when instantiating a Mailbox subclass with a path that does not exist and with the create parameter set to False or when opening a folder that does not exist exception mailbox NotEmptyError Raised when a mailbox is not empty but is expected to be such as when deleting a folder that contains messages exception mailbox ExternalClashError Raised when some mailbox related condition beyond the control of the program causes it to be unable to proceed such as when failing to acquire a lock that another program already holds a lock or when a uniquely generated file name already exists exception mailbox FormatError Raised when the data in a file cannot be parsed such as when an MH instance attempts to read a corrupted mh_sequences file Examples A simple example of printing the subjects of all messages in a mailbox that seem interesting import mailbox for message in mailbox mbox mbox subject message subject Could possibly be None if subject and python in subject lower print subject To copy all mail from a Babyl mailbox to an MH mailbox converting all of the format specific information that can be converted import mailbox destination mailbox MH Mail destination lock for message in mailbox Babyl RMAIL destination add mailbox MHMessage message destination flush destination unlock This example sorts mail from several mailing lists into different mailboxes being careful to avoid mail corruption due to concurrent modification by other programs mail loss due to interruption of the program or premature termination due to malformed messages in the mailbox import mailbox import email errors list_names python list python dev python bugs boxes name mailbox mbox email s name for name in list_names inbox mailbox Maildir Maildir factory None for key in inbox iterkeys try message inbox key except email errors MessageParseError continue The message is malformed Just leave it for name in list_names list_id message list id if list_id and name in list_id Get mailbox to use box boxes name Write copy to disk before removing original If there s a crash you might duplicate a message but that s better than losing a message completely box lock box add message box flush box unlock Remove original message inbox lock inbox discard key inbox flush inbox unlock break Found destination so stop looking for box in boxes itervalues box close
en
null
2,383
msilib Read and write Microsoft Installer files Source code Lib msilib __init__ py Deprecated since version 3 11 will be removed in version 3 13 The msilib module is deprecated see PEP 594 for details The msilib supports the creation of Microsoft Installer msi files Because these files often contain an embedded cabinet file cab it also exposes an API to create CAB files Support for reading cab files is currently not implemented read support for the msi database is possible This package aims to provide complete access to all tables in an msi file therefore it is a fairly low level API One primary application of this package is the creation of Python installer package itself although that currently uses a different version of msilib The package contents can be roughly split into four parts low level CAB routines low level MSI routines higher level MSI routines and standard table structures msilib FCICreate cabname files Create a new CAB file named cabname files must be a list of tuples each containing the name of the file on disk and the name of the file inside the CAB file The files are added to the CAB file in the order they appear in the list All files are added into a single CAB file using the MSZIP compression algorithm Callbacks to Python for the various steps of MSI creation are currently not exposed msilib UuidCreate Return the string representation of a new unique identifier This wraps the Windows API functions UuidCreate and UuidToString msilib OpenDatabase path persist Return a new database object by calling MsiOpenDatabase path is the file name of the MSI file persist can be one of the constants MSIDBOPEN_CREATEDIRECT MSIDBOPEN_CREATE MSIDBOPEN_DIRECT MSIDBOPEN_READONLY or MSIDBOPEN_TRANSACT and may include the flag MSIDBOPEN_PATCHFILE See the Microsoft documentation for the meaning of these flags depending on the flags an existing database is opened or a new one created msilib CreateRecord count Return a new record object by calling MSICreateRecord count is the number of fields of the record msilib init_database name schema ProductName ProductCode ProductVersion Manufacturer Create and return a new database name initialize it with schema and set the properties ProductName ProductCode ProductVersion and Manufacturer schema must be a module object containing tables and _Validation_records attributes typically msilib schema should be used The database will contain just the schema and the validation records when this function returns msilib add_data database table records Add all records to the table named table in database The table argument must be one of the predefined tables in the MSI schema e g Feature File Component Dialog Control etc records should be a list of tuples each one containing all fields of a record according to the schema of the table For optional fields None can be passed Field values can be ints strings or instances of the Binary class class msilib Binary filename Represents entries in the Binary table inserting such an object using add_data reads the file named filename into the table msilib add_tables database module Add all table content from module to database module must contain an attribute tables listing all tables for which content should be added and one attribute per table that has the actual content This is typically used to install the sequence tables msilib add_stream database name path Add the file path into the _Stream table of database with the stream name name msilib gen_uuid Return a new UUID in the format that MSI typically requires i e in curly braces and with all hexdigits in uppercase See also FCICreate UuidCreate UuidToString Database Objects Database OpenView sql Return a view object by calling MSIDatabaseOpenView sql is the SQL statement to execute Database Commit Commit the changes pending in the current transaction by calling MSIDatabaseCommit Database GetSummaryInformation count Return a new summary information object by calling MsiGetSummaryInformation count is the maximum number of updated values Database Close Close the database object through MsiCloseHandle New
en
null
2,384
in version 3 7 See also MSIDatabaseOpenView MSIDatabaseCommit MSIGetSummaryInformation MsiCloseHandle View Objects View Execute params Execute the SQL query of the view through MSIViewExecute If params is not None it is a record describing actual values of the parameter tokens in the query View GetColumnInfo kind Return a record describing the columns of the view through calling MsiViewGetColumnInfo kind can be either MSICOLINFO_NAMES or MSICOLINFO_TYPES View Fetch Return a result record of the query through calling MsiViewFetch View Modify kind data Modify the view by calling MsiViewModify kind can be one of MSIMODIFY_SEEK MSIMODIFY_REFRESH MSIMODIFY_INSERT MSIMODIFY_UPDATE MSIMODIFY_ASSIGN MSIMODIFY_REPLACE MSIMODIFY_MERGE MSIMODIFY_DELETE MSIMODIFY_INSERT_TEMPORARY MSIMODIFY_VALIDATE MSIMODIFY_VALIDATE_NEW MSIMODIFY_VALIDATE_FIELD or MSIMODIFY_VALIDATE_DELETE data must be a record describing the new data View Close Close the view through MsiViewClose See also MsiViewExecute MSIViewGetColumnInfo MsiViewFetch MsiViewModify MsiViewClose Summary Information Objects SummaryInformation GetProperty field Return a property of the summary through MsiSummaryInfoGetProperty field is the name of the property and can be one of the constants PID_CODEPAGE PID_TITLE PID_SUBJECT PID_AUTHOR PID_KEYWORDS PID_COMMENTS PID_TEMPLATE PID_LASTAUTHOR PID_REVNUMBER PID_LASTPRINTED PID_CREATE_DTM PID_LASTSAVE_DTM PID_PAGECOUNT PID_WORDCOUNT PID_CHARCOUNT PID_APPNAME or PID_SECURITY SummaryInformation GetPropertyCount Return the number of summary properties through MsiSummaryInfoGetPropertyCount SummaryInformation SetProperty field value Set a property through MsiSummaryInfoSetProperty field can have the same values as in GetProperty value is the new value of the property Possible value types are integer and string SummaryInformation Persist Write the modified properties to the summary information stream using MsiSummaryInfoPersist See also MsiSummaryInfoGetProperty MsiSummaryInfoGetPropertyCount MsiSummaryInfoSetProperty MsiSummaryInfoPersist Record Objects Record GetFieldCount Return the number of fields of the record through MsiRecordGetFieldCount Record GetInteger field Return the value of field as an integer where possible field must be an integer Record GetString field Return the value of field as a string where possible field must be an integer Record SetString field value Set field to value through MsiRecordSetString field must be an integer value a string Record SetStream field value Set field to the contents of the file named value through MsiRecordSetStream field must be an integer value a string Record SetInteger field value Set field to value through MsiRecordSetInteger Both field and value must be an integer Record ClearData Set all fields of the record to 0 through MsiRecordClearData See also MsiRecordGetFieldCount MsiRecordSetString MsiRecordSetStream MsiRecordSetInteger MsiRecordClearData Errors All wrappers around MSI functions raise MSIError the string inside the exception will contain more detail CAB Objects class msilib CAB name The class CAB represents a CAB file During MSI construction files will be added simultaneously to the Files table and to a CAB file Then when all files have been added the CAB file can be written then added to the MSI file name is the name of the CAB file in the MSI file append full file logical Add the file with the pathname full to the CAB file under the name logical If there is already a file named logical a new file name is created Return the index of the file in the CAB file and the new name of the file inside the CAB file commit database Generate a CAB file add it as a stream to the MSI file put it into the Media table and remove the generated file from the disk Directory Objects class msilib Directory database cab basedir physical logical default componentflags Create a new directory in the Directory table There is a current component at each point in time for the directory which is either explicitly created through start_component or implicitly when files are added for the first time Files a
en
null
2,385
re added into the current component and into the cab file To create a directory a base directory object needs to be specified can be None the path to the physical directory and a logical directory name default specifies the DefaultDir slot in the directory table componentflags specifies the default flags that new components get start_component component None feature None flags None keyfile None uuid None Add an entry to the Component table and make this component the current component for this directory If no component name is given the directory name is used If no feature is given the current feature is used If no flags are given the directory s default flags are used If no keyfile is given the KeyPath is left null in the Component table add_file file src None version None language None Add a file to the current component of the directory starting a new one if there is no current component By default the file name in the source and the file table will be identical If the src file is specified it is interpreted relative to the current directory Optionally a version and a language can be specified for the entry in the File table glob pattern exclude None Add a list of files to the current component as specified in the glob pattern Individual files can be excluded in the exclude list remove_pyc Remove pyc files on uninstall See also Directory Table File Table Component Table FeatureComponents Table Features class msilib Feature db id title desc display level 1 parent None directory None attributes 0 Add a new record to the Feature table using the values id parent id title desc display level directory and attributes The resulting feature object can be passed to the start_component method of Directory set_current Make this feature the current feature of msilib New components are automatically added to the default feature unless a feature is explicitly specified See also Feature Table GUI classes msilib provides several classes that wrap the GUI tables in an MSI database However no standard user interface is provided class msilib Control dlg name Base class of the dialog controls dlg is the dialog object the control belongs to and name is the control s name event event argument condition 1 ordering None Make an entry into the ControlEvent table for this control mapping event attribute Make an entry into the EventMapping table for this control condition action condition Make an entry into the ControlCondition table for this control class msilib RadioButtonGroup dlg name property Create a radio button control named name property is the installer property that gets set when a radio button is selected add name x y width height text value None Add a radio button named name to the group at the coordinates x y width height and with the label text If value is None it defaults to name class msilib Dialog db name x y w h attr title first default cancel Return a new Dialog object An entry in the Dialog table is made with the specified coordinates dialog attributes title name of the first default and cancel controls control name type x y width height attributes property text control_next help Return a new Control object An entry in the Control table is made with the specified parameters This is a generic method for specific types specialized methods are provided text name x y width height attributes text Add and return a Text control bitmap name x y width height text Add and return a Bitmap control line name x y width height Add and return a Line control pushbutton name x y width height attributes text next_control Add and return a PushButton control radiogroup name x y width height attributes property text next_control Add and return a RadioButtonGroup control checkbox name x y width height attributes property text next_control Add and return a CheckBox control See also Dialog Table Control Table Control Types ControlCondition Table ControlEvent Table EventMapping Table RadioButton Table Precomputed tables msilib provides a few subpackages that contain only schema and table definitions Currently these definitions are based on MSI versio
en
null
2,386
n 2 0 msilib schema This is the standard MSI schema for MSI 2 0 with the tables variable providing a list of table definitions and _Validation_records providing the data for MSI validation msilib sequence This module contains table contents for the standard sequence tables AdminExecuteSequence AdminUISequence AdvtExecuteSequence InstallExecuteSequence and InstallUISequence msilib text This module contains definitions for the UIText and ActionText tables for the standard installer actions
en
null
2,387
secrets Generate secure random numbers for managing secrets New in version 3 6 Source code Lib secrets py The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords account authentication security tokens and related secrets In particular secrets should be used in preference to the default pseudo random number generator in the random module which is designed for modelling and simulation not security or cryptography See also PEP 506 Random numbers The secrets module provides access to the most secure source of randomness that your operating system provides class secrets SystemRandom A class for generating random numbers using the highest quality sources provided by the operating system See random SystemRandom for additional details secrets choice sequence Return a randomly chosen element from a non empty sequence secrets randbelow n Return a random int in the range 0 n secrets randbits k Return an int with k random bits Generating tokens The secrets module provides functions for generating secure tokens suitable for applications such as password resets hard to guess URLs and similar secrets token_bytes nbytes None Return a random byte string containing nbytes number of bytes If nbytes is None or not supplied a reasonable default is used token_bytes 16 b xebr x17D t xae xd4 xe3S xb6 xe2 xebP1 x8b secrets token_hex nbytes None Return a random text string in hexadecimal The string has nbytes random bytes each byte converted to two hex digits If nbytes is None or not supplied a reasonable default is used token_hex 16 f9bf78b9a18ce6d46a0cd2b0b86df9da secrets token_urlsafe nbytes None Return a random URL safe text string containing nbytes random bytes The text is Base64 encoded so on average each byte results in approximately 1 3 characters If nbytes is None or not supplied a reasonable default is used token_urlsafe 16 Drmhze6EPcv0fN_81Bj nA How many bytes should tokens use To be secure against brute force attacks tokens need to have sufficient randomness Unfortunately what is considered sufficient will necessarily increase as computers get more powerful and able to make more guesses in a shorter period As of 2015 it is believed that 32 bytes 256 bits of randomness is sufficient for the typical use case expected for the secrets module For those who want to manage their own token length you can explicitly specify how much randomness is used for tokens by giving an int argument to the various token_ functions That argument is taken as the number of bytes of randomness to use Otherwise if no argument is provided or if the argument is None the token_ functions will use a reasonable default instead Note That default is subject to change at any time including during maintenance releases Other functions secrets compare_digest a b Return True if strings or bytes like objects a and b are equal otherwise False using a constant time compare to reduce the risk of timing attacks See hmac compare_digest for additional details Recipes and best practices This section shows recipes and best practices for using secrets to manage a basic level of security Generate an eight character alphanumeric password import string import secrets alphabet string ascii_letters string digits password join secrets choice alphabet for i in range 8 Note Applications should not store passwords in a recoverable format whether plain text or encrypted They should be salted and hashed using a cryptographically strong one way irreversible hash function Generate a ten character alphanumeric password with at least one lowercase character at least one uppercase character and at least three digits import string import secrets alphabet string ascii_letters string digits while True password join secrets choice alphabet for i in range 10 if any c islower for c in password and any c isupper for c in password and sum c isdigit for c in password 3 break Generate an XKCD style passphrase import secrets On standard Linux systems use a convenient dictionary file Other platforms may need to provide their own word list
en
null
2,388
with open usr share dict words as f words word strip for word in f password join secrets choice words for i in range 4 Generate a hard to guess temporary URL containing a security token suitable for password recovery applications import secrets url https example com reset secrets token_urlsafe
en
null
2,389
contextlib Utilities for with statement contexts Source code Lib contextlib py This module provides utilities for common tasks involving the with statement For more information see also Context Manager Types and With Statement Context Managers Utilities Functions and classes provided class contextlib AbstractContextManager An abstract base class for classes that implement object __enter__ and object __exit__ A default implementation for object __enter__ is provided which returns self while object __exit__ is an abstract method which by default returns None See also the definition of Context Manager Types New in version 3 6 class contextlib AbstractAsyncContextManager An abstract base class for classes that implement object __aenter__ and object __aexit__ A default implementation for object __aenter__ is provided which returns self while object __aexit__ is an abstract method which by default returns None See also the definition of Asynchronous Context Managers New in version 3 7 contextlib contextmanager This function is a decorator that can be used to define a factory function for with statement context managers without needing to create a class or separate __enter__ and __exit__ methods While many objects natively support use in with statements sometimes a resource needs to be managed that isn t a context manager in its own right and doesn t implement a close method for use with contextlib closing An abstract example would be the following to ensure correct resource management from contextlib import contextmanager contextmanager def managed_resource args kwds Code to acquire resource e g resource acquire_resource args kwds try yield resource finally Code to release resource e g release_resource resource The function can then be used like this with managed_resource timeout 3600 as resource Resource is released at the end of this block even if code in the block raises an exception The function being decorated must return a generator iterator when called This iterator must yield exactly one value which will be bound to the targets in the with statement s as clause if any At the point where the generator yields the block nested in the with statement is executed The generator is then resumed after the block is exited If an unhandled exception occurs in the block it is reraised inside the generator at the point where the yield occurred Thus you can use a try except finally statement to trap the error if any or ensure that some cleanup takes place If an exception is trapped merely in order to log it or to perform some action rather than to suppress it entirely the generator must reraise that exception Otherwise the generator context manager will indicate to the with statement that the exception has been handled and execution will resume with the statement immediately following the with statement contextmanager uses ContextDecorator so the context managers it creates can be used as decorators as well as in with statements When used as a decorator a new generator instance is implicitly created on each function call this allows the otherwise one shot context managers created by contextmanager to meet the requirement that context managers support multiple invocations in order to be used as decorators Changed in version 3 2 Use of ContextDecorator contextlib asynccontextmanager Similar to contextmanager but creates an asynchronous context manager This function is a decorator that can be used to define a factory function for async with statement asynchronous context managers without needing to create a class or separate __aenter__ and __aexit__ methods It must be applied to an asynchronous generator function A simple example from contextlib import asynccontextmanager asynccontextmanager async def get_connection conn await acquire_db_connection try yield conn finally await release_db_connection conn async def get_all_users async with get_connection as conn return conn query SELECT New in version 3 7 Context managers defined with asynccontextmanager can be used either as decorators or with async with statements import time from conte
en
null
2,390
xtlib import asynccontextmanager asynccontextmanager async def timeit now time monotonic try yield finally print f it took time monotonic now s to run timeit async def main async code When used as a decorator a new generator instance is implicitly created on each function call This allows the otherwise one shot context managers created by asynccontextmanager to meet the requirement that context managers support multiple invocations in order to be used as decorators Changed in version 3 10 Async context managers created with asynccontextmanager can be used as decorators contextlib closing thing Return a context manager that closes thing upon completion of the block This is basically equivalent to from contextlib import contextmanager contextmanager def closing thing try yield thing finally thing close And lets you write code like this from contextlib import closing from urllib request import urlopen with closing urlopen https www python org as page for line in page print line without needing to explicitly close page Even if an error occurs page close will be called when the with block is exited Note Most types managing resources support the context manager protocol which closes thing on leaving the with statement As such closing is most useful for third party types that don t support context managers This example is purely for illustration purposes as urlopen would normally be used in a context manager contextlib aclosing thing Return an async context manager that calls the aclose method of thing upon completion of the block This is basically equivalent to from contextlib import asynccontextmanager asynccontextmanager async def aclosing thing try yield thing finally await thing aclose Significantly aclosing supports deterministic cleanup of async generators when they happen to exit early by break or an exception For example from contextlib import aclosing async with aclosing my_generator as values async for value in values if value 42 break This pattern ensures that the generator s async exit code is executed in the same context as its iterations so that exceptions and context variables work as expected and the exit code isn t run after the lifetime of some task it depends on New in version 3 10 contextlib nullcontext enter_result None Return a context manager that returns enter_result from __enter__ but otherwise does nothing It is intended to be used as a stand in for an optional context manager for example def myfunction arg ignore_exceptions False if ignore_exceptions Use suppress to ignore all exceptions cm contextlib suppress Exception else Do not ignore any exceptions cm has no effect cm contextlib nullcontext with cm Do something An example using enter_result def process_file file_or_path if isinstance file_or_path str If string open file cm open file_or_path else Caller is responsible for closing file cm nullcontext file_or_path with cm as file Perform processing on the file It can also be used as a stand in for asynchronous context managers async def send_http session None if not session If no http session create it with aiohttp cm aiohttp ClientSession else Caller is responsible for closing the session cm nullcontext session async with cm as session Send http requests with session New in version 3 7 Changed in version 3 10 asynchronous context manager support was added contextlib suppress exceptions Return a context manager that suppresses any of the specified exceptions if they occur in the body of a with statement and then resumes execution with the first statement following the end of the with statement As with any other mechanism that completely suppresses exceptions this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do For example from contextlib import suppress with suppress FileNotFoundError os remove somefile tmp with suppress FileNotFoundError os remove someotherfile tmp This code is equivalent to try os remove somefile tmp except FileNotFoundError pass try os remove someotherfile tmp except FileNotFo
en
null
2,391
undError pass This context manager is reentrant If the code within the with block raises a BaseExceptionGroup suppressed exceptions are removed from the group If any exceptions in the group are not suppressed a group containing them is re raised New in version 3 4 Changed in version 3 12 suppress now supports suppressing exceptions raised as part of an BaseExceptionGroup contextlib redirect_stdout new_target Context manager for temporarily redirecting sys stdout to another file or file like object This tool adds flexibility to existing functions or classes whose output is hardwired to stdout For example the output of help normally is sent to sys stdout You can capture that output in a string by redirecting the output to an io StringIO object The replacement stream is returned from the __enter__ method and so is available as the target of the with statement with redirect_stdout io StringIO as f help pow s f getvalue To send the output of help to a file on disk redirect the output to a regular file with open help txt w as f with redirect_stdout f help pow To send the output of help to sys stderr with redirect_stdout sys stderr help pow Note that the global side effect on sys stdout means that this context manager is not suitable for use in library code and most threaded applications It also has no effect on the output of subprocesses However it is still a useful approach for many utility scripts This context manager is reentrant New in version 3 4 contextlib redirect_stderr new_target Similar to redirect_stdout but redirecting sys stderr to another file or file like object This context manager is reentrant New in version 3 5 contextlib chdir path Non parallel safe context manager to change the current working directory As this changes a global state the working directory it is not suitable for use in most threaded or async contexts It is also not suitable for most non linear code execution like generators where the program execution is temporarily relinquished unless explicitly desired you should not yield when this context manager is active This is a simple wrapper around chdir it changes the current working directory upon entering and restores the old one on exit This context manager is reentrant New in version 3 11 class contextlib ContextDecorator A base class that enables a context manager to also be used as a decorator Context managers inheriting from ContextDecorator have to implement __enter__ and __exit__ as normal __exit__ retains its optional exception handling even when used as a decorator ContextDecorator is used by contextmanager so you get this functionality automatically Example of ContextDecorator from contextlib import ContextDecorator class mycontext ContextDecorator def __enter__ self print Starting return self def __exit__ self exc print Finishing return False The class can then be used like this mycontext def function print The bit in the middle function Starting The bit in the middle Finishing with mycontext print The bit in the middle Starting The bit in the middle Finishing This change is just syntactic sugar for any construct of the following form def f with cm Do stuff ContextDecorator lets you instead write cm def f Do stuff It makes it clear that the cm applies to the whole function rather than just a piece of it and saving an indentation level is nice too Existing context managers that already have a base class can be extended by using ContextDecorator as a mixin class from contextlib import ContextDecorator class mycontext ContextBaseClass ContextDecorator def __enter__ self return self def __exit__ self exc return False Note As the decorated function must be able to be called multiple times the underlying context manager must support use in multiple with statements If this is not the case then the original construct with the explicit with statement inside the function should be used New in version 3 2 class contextlib AsyncContextDecorator Similar to ContextDecorator but only for asynchronous functions Example of AsyncContextDecorator from asyncio import run from contextlib import AsyncConte
en
null
2,392
xtDecorator class mycontext AsyncContextDecorator async def __aenter__ self print Starting return self async def __aexit__ self exc print Finishing return False The class can then be used like this mycontext async def function print The bit in the middle run function Starting The bit in the middle Finishing async def function async with mycontext print The bit in the middle run function Starting The bit in the middle Finishing New in version 3 10 class contextlib ExitStack A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions especially those that are optional or otherwise driven by input data For example a set of files may easily be handled in a single with statement as follows with ExitStack as stack files stack enter_context open fname for fname in filenames All opened files will automatically be closed at the end of the with statement even if attempts to open files later in the list raise an exception The __enter__ method returns the ExitStack instance and performs no additional operations Each instance maintains a stack of registered callbacks that are called in reverse order when the instance is closed either explicitly or implicitly at the end of a with statement Note that callbacks are not invoked implicitly when the context stack instance is garbage collected This stack model is used so that context managers that acquire their resources in their __init__ method such as file objects can be handled correctly Since registered callbacks are invoked in the reverse order of registration this ends up behaving as if multiple nested with statements had been used with the registered set of callbacks This even extends to exception handling if an inner callback suppresses or replaces an exception then outer callbacks will be passed arguments based on that updated state This is a relatively low level API that takes care of the details of correctly unwinding the stack of exit callbacks It provides a suitable foundation for higher level context managers that manipulate the exit stack in application specific ways New in version 3 3 enter_context cm Enters a new context manager and adds its __exit__ method to the callback stack The return value is the result of the context manager s own __enter__ method These context managers may suppress exceptions just as they normally would if used directly as part of a with statement Changed in version 3 11 Raises TypeError instead of AttributeError if cm is not a context manager push exit Adds a context manager s __exit__ method to the callback stack As __enter__ is not invoked this method can be used to cover part of an __enter__ implementation with a context manager s own __exit__ method If passed an object that is not a context manager this method assumes it is a callback with the same signature as a context manager s __exit__ method and adds it directly to the callback stack By returning true values these callbacks can suppress exceptions the same way context manager __exit__ methods can The passed in object is returned from the function allowing this method to be used as a function decorator callback callback args kwds Accepts an arbitrary callback function and arguments and adds it to the callback stack Unlike the other methods callbacks added this way cannot suppress exceptions as they are never passed the exception details The passed in callback is returned from the function allowing this method to be used as a function decorator pop_all Transfers the callback stack to a fresh ExitStack instance and returns it No callbacks are invoked by this operation instead they will now be invoked when the new stack is closed either explicitly or implicitly at the end of a with statement For example a group of files can be opened as an all or nothing operation as follows with ExitStack as stack files stack enter_context open fname for fname in filenames Hold onto the close method but don t call it yet close_files stack pop_all close If opening any file fails all previously opened files will be closed automatically If all files
en
null
2,393
are opened successfully they will remain open even after the with statement ends close_files can then be invoked explicitly to close them all close Immediately unwinds the callback stack invoking callbacks in the reverse order of registration For any context managers and exit callbacks registered the arguments passed in will indicate that no exception occurred class contextlib AsyncExitStack An asynchronous context manager similar to ExitStack that supports combining both synchronous and asynchronous context managers as well as having coroutines for cleanup logic The close method is not implemented aclose must be used instead coroutine enter_async_context cm Similar to ExitStack enter_context but expects an asynchronous context manager Changed in version 3 11 Raises TypeError instead of AttributeError if cm is not an asynchronous context manager push_async_exit exit Similar to ExitStack push but expects either an asynchronous context manager or a coroutine function push_async_callback callback args kwds Similar to ExitStack callback but expects a coroutine function coroutine aclose Similar to ExitStack close but properly handles awaitables Continuing the example for asynccontextmanager async with AsyncExitStack as stack connections await stack enter_async_context get_connection for i in range 5 All opened connections will automatically be released at the end of the async with statement even if attempts to open a connection later in the list raise an exception New in version 3 7 Examples and Recipes This section describes some examples and recipes for making effective use of the tools provided by contextlib Supporting a variable number of context managers The primary use case for ExitStack is the one given in the class documentation supporting a variable number of context managers and other cleanup operations in a single with statement The variability may come from the number of context managers needed being driven by user input such as opening a user specified collection of files or from some of the context managers being optional with ExitStack as stack for resource in resources stack enter_context resource if need_special_resource special acquire_special_resource stack callback release_special_resource special Perform operations that use the acquired resources As shown ExitStack also makes it quite easy to use with statements to manage arbitrary resources that don t natively support the context management protocol Catching exceptions from __enter__ methods It is occasionally desirable to catch exceptions from an __enter__ method implementation without inadvertently catching exceptions from the with statement body or the context manager s __exit__ method By using ExitStack the steps in the context management protocol can be separated slightly in order to allow this stack ExitStack try x stack enter_context cm except Exception handle __enter__ exception else with stack Handle normal case Actually needing to do this is likely to indicate that the underlying API should be providing a direct resource management interface for use with try except finally statements but not all APIs are well designed in that regard When a context manager is the only resource management API provided then ExitStack can make it easier to handle various situations that can t be handled directly in a with statement Cleaning up in an __enter__ implementation As noted in the documentation of ExitStack push this method can be useful in cleaning up an already allocated resource if later steps in the __enter__ implementation fail Here s an example of doing this for a context manager that accepts resource acquisition and release functions along with an optional validation function and maps them to the context management protocol from contextlib import contextmanager AbstractContextManager ExitStack class ResourceManager AbstractContextManager def __init__ self acquire_resource release_resource check_resource_ok None self acquire_resource acquire_resource self release_resource release_resource if check_resource_ok is None def check_resource_ok resource r
en
null
2,394
eturn True self check_resource_ok check_resource_ok contextmanager def _cleanup_on_error self with ExitStack as stack stack push self yield The validation check passed and didn t raise an exception Accordingly we want to keep the resource and pass it back to our caller stack pop_all def __enter__ self resource self acquire_resource with self _cleanup_on_error if not self check_resource_ok resource msg Failed validation for r raise RuntimeError msg format resource return resource def __exit__ self exc_details We don t need to duplicate any of our resource release logic self release_resource Replacing any use of try finally and flag variables A pattern you will sometimes see is a try finally statement with a flag variable to indicate whether or not the body of the finally clause should be executed In its simplest form that can t already be handled just by using an except clause instead it looks something like this cleanup_needed True try result perform_operation if result cleanup_needed False finally if cleanup_needed cleanup_resources As with any try statement based code this can cause problems for development and review because the setup code and the cleanup code can end up being separated by arbitrarily long sections of code ExitStack makes it possible to instead register a callback for execution at the end of a with statement and then later decide to skip executing that callback from contextlib import ExitStack with ExitStack as stack stack callback cleanup_resources result perform_operation if result stack pop_all This allows the intended cleanup up behaviour to be made explicit up front rather than requiring a separate flag variable If a particular application uses this pattern a lot it can be simplified even further by means of a small helper class from contextlib import ExitStack class Callback ExitStack def __init__ self callback args kwds super __init__ self callback callback args kwds def cancel self self pop_all with Callback cleanup_resources as cb result perform_operation if result cb cancel If the resource cleanup isn t already neatly bundled into a standalone function then it is still possible to use the decorator form of ExitStack callback to declare the resource cleanup in advance from contextlib import ExitStack with ExitStack as stack stack callback def cleanup_resources result perform_operation if result stack pop_all Due to the way the decorator protocol works a callback function declared this way cannot take any parameters Instead any resources to be released must be accessed as closure variables Using a context manager as a function decorator ContextDecorator makes it possible to use a context manager in both an ordinary with statement and also as a function decorator For example it is sometimes useful to wrap functions or groups of statements with a logger that can track the time of entry and time of exit Rather than writing both a function decorator and a context manager for the task inheriting from ContextDecorator provides both capabilities in a single definition from contextlib import ContextDecorator import logging logging basicConfig level logging INFO class track_entry_and_exit ContextDecorator def __init__ self name self name name def __enter__ self logging info Entering s self name def __exit__ self exc_type exc exc_tb logging info Exiting s self name Instances of this class can be used as both a context manager with track_entry_and_exit widget loader print Some time consuming activity goes here load_widget And also as a function decorator track_entry_and_exit widget loader def activity print Some time consuming activity goes here load_widget Note that there is one additional limitation when using context managers as function decorators there s no way to access the return value of __enter__ If that value is needed then it is still necessary to use an explicit with statement See also PEP 343 The with statement The specification background and examples for the Python with statement Single use reusable and reentrant context managers Most context managers are written in a way that means they c
en
null
2,395
an only be used effectively in a with statement once These single use context managers must be created afresh each time they re used attempting to use them a second time will trigger an exception or otherwise not work correctly This common limitation means that it is generally advisable to create context managers directly in the header of the with statement where they are used as shown in all of the usage examples above Files are an example of effectively single use context managers since the first with statement will close the file preventing any further IO operations using that file object Context managers created using contextmanager are also single use context managers and will complain about the underlying generator failing to yield if an attempt is made to use them a second time from contextlib import contextmanager contextmanager def singleuse print Before yield print After cm singleuse with cm pass Before After with cm pass Traceback most recent call last RuntimeError generator didn t yield Reentrant context managers More sophisticated context managers may be reentrant These context managers can not only be used in multiple with statements but may also be used inside a with statement that is already using the same context manager threading RLock is an example of a reentrant context manager as are suppress redirect_stdout and chdir Here s a very simple example of reentrant use from contextlib import redirect_stdout from io import StringIO stream StringIO write_to_stream redirect_stdout stream with write_to_stream print This is written to the stream rather than stdout with write_to_stream print This is also written to the stream print This is written directly to stdout This is written directly to stdout print stream getvalue This is written to the stream rather than stdout This is also written to the stream Real world examples of reentrancy are more likely to involve multiple functions calling each other and hence be far more complicated than this example Note also that being reentrant is not the same thing as being thread safe redirect_stdout for example is definitely not thread safe as it makes a global modification to the system state by binding sys stdout to a different stream Reusable context managers Distinct from both single use and reentrant context managers are reusable context managers or to be completely explicit reusable but not reentrant context managers since reentrant context managers are also reusable These context managers support being used multiple times but will fail or otherwise not work correctly if the specific context manager instance has already been used in a containing with statement threading Lock is an example of a reusable but not reentrant context manager for a reentrant lock it is necessary to use threading RLock instead Another example of a reusable but not reentrant context manager is ExitStack as it invokes all currently registered callbacks when leaving any with statement regardless of where those callbacks were added from contextlib import ExitStack stack ExitStack with stack stack callback print Callback from first context print Leaving first context Leaving first context Callback from first context with stack stack callback print Callback from second context print Leaving second context Leaving second context Callback from second context with stack stack callback print Callback from outer context with stack stack callback print Callback from inner context print Leaving inner context print Leaving outer context Leaving inner context Callback from inner context Callback from outer context Leaving outer context As the output from the example shows reusing a single stack object across multiple with statements works correctly but attempting to nest them will cause the stack to be cleared at the end of the innermost with statement which is unlikely to be desirable behaviour Using separate ExitStack instances instead of reusing a single instance avoids that problem from contextlib import ExitStack with ExitStack as outer_stack outer_stack callback print Callback from outer context wi
en
null
2,396
th ExitStack as inner_stack inner_stack callback print Callback from inner context print Leaving inner context print Leaving outer context Leaving inner context Callback from inner context Leaving outer context Callback from outer context
en
null
2,397
email mime Creating email and MIME objects from scratch Source code Lib email mime This module is part of the legacy Compat32 email API Its functionality is partially replaced by the contentmanager in the new API but in certain applications these classes may still be useful even in non legacy code Ordinarily you get a message object structure by passing a file or some text to a parser which parses the text and returns the root message object However you can also build a complete message structure from scratch or even individual Message objects by hand In fact you can also take an existing structure and add new Message objects move them around etc This makes a very convenient interface for slicing and dicing MIME messages You can create a new object structure by creating Message instances adding attachments and all the appropriate headers manually For MIME messages though the email package provides some convenient subclasses to make things easier Here are the classes class email mime base MIMEBase _maintype _subtype policy compat32 _params Module email mime base This is the base class for all the MIME specific subclasses of Message Ordinarily you won t create instances specifically of MIMEBase although you could MIMEBase is provided primarily as a convenient base class for more specific MIME aware subclasses _maintype is the Content Type major type e g text or image and _subtype is the Content Type minor type e g plain or gif _params is a parameter key value dictionary and is passed directly to Message add_header If policy is specified defaults to the compat32 policy it will be passed to Message The MIMEBase class always adds a Content Type header based on _maintype _subtype and _params and a MIME Version header always set to 1 0 Changed in version 3 6 Added policy keyword only parameter class email mime nonmultipart MIMENonMultipart Module email mime nonmultipart A subclass of MIMEBase this is an intermediate base class for MIME messages that are not multipart The primary purpose of this class is to prevent the use of the attach method which only makes sense for multipart messages If attach is called a MultipartConversionError exception is raised class email mime multipart MIMEMultipart _subtype mixed boundary None _subparts None policy compat32 _params Module email mime multipart A subclass of MIMEBase this is an intermediate base class for MIME messages that are multipart Optional _subtype defaults to mixed but can be used to specify the subtype of the message A Content Type header of multipart _subtype will be added to the message object A MIME Version header will also be added Optional boundary is the multipart boundary string When None the default the boundary is calculated when needed for example when the message is serialized _subparts is a sequence of initial subparts for the payload It must be possible to convert this sequence to a list You can always attach new subparts to the message by using the Message attach method Optional policy argument defaults to compat32 Additional parameters for the Content Type header are taken from the keyword arguments or passed into the _params argument which is a keyword dictionary Changed in version 3 6 Added policy keyword only parameter class email mime application MIMEApplication _data _subtype octet stream _encoder email encoders encode_base64 policy compat32 _params Module email mime application A subclass of MIMENonMultipart the MIMEApplication class is used to represent MIME message objects of major type application _data contains the bytes for the raw application data Optional _subtype specifies the MIME subtype and defaults to octet stream Optional _encoder is a callable i e function which will perform the actual encoding of the data for transport This callable takes one argument which is the MIMEApplication instance It should use get_payload and set_payload to change the payload to encoded form It should also add any Content Transfer Encoding or other headers to the message object as necessary The default encoding is base64 See the email encoders module for a list of
en
null
2,398
the built in encoders Optional policy argument defaults to compat32 _params are passed straight through to the base class constructor Changed in version 3 6 Added policy keyword only parameter class email mime audio MIMEAudio _audiodata _subtype None _encoder email encoders encode_base64 policy compat32 _params Module email mime audio A subclass of MIMENonMultipart the MIMEAudio class is used to create MIME message objects of major type audio _audiodata contains the bytes for the raw audio data If this data can be decoded as au wav aiff or aifc then the subtype will be automatically included in the Content Type header Otherwise you can explicitly specify the audio subtype via the _subtype argument If the minor type could not be guessed and _subtype was not given then TypeError is raised Optional _encoder is a callable i e function which will perform the actual encoding of the audio data for transport This callable takes one argument which is the MIMEAudio instance It should use get_payload and set_payload to change the payload to encoded form It should also add any Content Transfer Encoding or other headers to the message object as necessary The default encoding is base64 See the email encoders module for a list of the built in encoders Optional policy argument defaults to compat32 _params are passed straight through to the base class constructor Changed in version 3 6 Added policy keyword only parameter class email mime image MIMEImage _imagedata _subtype None _encoder email encoders encode_base64 policy compat32 _params Module email mime image A subclass of MIMENonMultipart the MIMEImage class is used to create MIME message objects of major type image _imagedata contains the bytes for the raw image data If this data type can be detected jpeg png gif tiff rgb pbm pgm ppm rast xbm bmp webp and exr attempted then the subtype will be automatically included in the Content Type header Otherwise you can explicitly specify the image subtype via the _subtype argument If the minor type could not be guessed and _subtype was not given then TypeError is raised Optional _encoder is a callable i e function which will perform the actual encoding of the image data for transport This callable takes one argument which is the MIMEImage instance It should use get_payload and set_payload to change the payload to encoded form It should also add any Content Transfer Encoding or other headers to the message object as necessary The default encoding is base64 See the email encoders module for a list of the built in encoders Optional policy argument defaults to compat32 _params are passed straight through to the MIMEBase constructor Changed in version 3 6 Added policy keyword only parameter class email mime message MIMEMessage _msg _subtype rfc822 policy compat32 Module email mime message A subclass of MIMENonMultipart the MIMEMessage class is used to create MIME objects of main type message _msg is used as the payload and must be an instance of class Message or a subclass thereof otherwise a TypeError is raised Optional _subtype sets the subtype of the message it defaults to rfc822 Optional policy argument defaults to compat32 Changed in version 3 6 Added policy keyword only parameter class email mime text MIMEText _text _subtype plain _charset None policy compat32 Module email mime text A subclass of MIMENonMultipart the MIMEText class is used to create MIME objects of major type text _text is the string for the payload _subtype is the minor type and defaults to plain _charset is the character set of the text and is passed as an argument to the MIMENonMultipart constructor it defaults to us ascii if the string contains only ascii code points and utf 8 otherwise The _charset parameter accepts either a string or a Charset instance Unless the _charset argument is explicitly set to None the MIMEText object created will have both a Content Type header with a charset parameter and a Content Transfer Encoding header This means that a subsequent set_payload call will not result in an encoded payload even if a charset is passed in the set_payload comman
en
null
2,399
d You can reset this behavior by deleting the Content Transfer Encoding header after which a set_payload call will automatically encode the new payload and add a new Content Transfer Encoding header Optional policy argument defaults to compat32 Changed in version 3 5 _charset also accepts Charset instances Changed in version 3 6 Added policy keyword only parameter
en
null