What's new in Python 3.6

Introduction

Previously, I wrote an article What's new in Python 3.5, but since the alpha version of 3.6 has come out, I will anticipate the features of 3.6. I'll check it.

According to the development roadmap (PEP-494)

--3.6.0 alpha 1: 2016-05-17 (Completed) --3.6.0 alpha 2: 2016-06-13 (Completed) --3.6.0 alpha 3: 2016-07-11 (Completed) --3.6.0 alpha 4: 2016-08-15 (Completed) --3.6.0 beta 1: 2016-09-12 (Completed and added new functions up to here)

The destination is still long. The final version will be released on December 16th. Before Christmas. We'll continue to add new features until the September beta, so I'm sure it will change until then, but I'll update this article as it changes. It's easier than looking at it all at once (^^;

So, I referred to 3.6.0b1 this time, and I referred to the draft release document of here.

Use pyenv to try

pyenv install 3.6.0b1
pyenv local 3.6.0b1

Please.

Change log

2016.07.16 --Changed the version used for confirmation from 3.6.0a2 to 3.6.0a3 -(Other than that, no changes I noticed ...)

2016.10.01 --Changed the version used for confirmation to 3.6.0b1 --Because it became Beta and there is no further specification change, "(a3 version)" was deleted from the title. --Added global / nonlocal changes, PEP515, PEP526, PEP525, PEP530 to "Introduction of new grammar" --Added "Security Improvement" --Added PSP529, PEP528, etc. to "Improvements on Windows" --Added "new built-in function" --Many additions to "new features" --Added description in "Change of other languages" --Added description to "Improved Module" --Added "Deprecated Build Options" to "Candidates for Decommissioning"

Changes

Release highlights

Introduction of new grammar

--global and nonlocal have to be placed before the first use of the variable in that scope (previously only warnings) -PEP-498 Formatted string literal -PEP-515 You can now put _ in numeric literals -PEP-526 Introduction of notation to annotate variables -PEP-525 Introduction of asynchronous generator -PEP-530 Introduction of asynchronous comprehension

PEP-498, PEP-515 and PEP-526 are mentioned in more detail in "New Features".

Security improvements

--On Linux, os.urandom () will now block until the system's urandom entropy pool is initialized. See PEP524 (https://www.python.org/dev/peps/pep-0524/) for a detailed rationale. --hashlib and ssl modules support OpenSSL 1.1.0 --Make the default settings and feature set of ssl more secure --hashlib module supports new hash functions (BLAKE2, SHA-3, SHAKE) and key derivation functionscrypt ()

Improvements on Windows

--PEP529 (https://www.python.org/dev/peps/pep-0529/) Changed Windows file system encoding to UTF-8 --PEP528 (https://www.python.org/dev/peps/pep-0528/) Changed Windows console encoding to UTF-8 --In the past, when using py.exe on the command line, Python2 was prioritized if no version was specified, but now it will be Python3. --python.exe and pythonw.exe now support long paths, removing the 260 character limit on file paths --You can now write the module search path in the ._pth file. --If PYTHONHOME is not set in an environment variable, it will now be guessed at the location of Python36.zip.

New built-in function

--PEP-520 (https://www.python.org/dev/peps/pep-0520/) Keeps the definition order of class attributes --PEP-468 (https://www.python.org/dev/peps/pep-0468/) Keep the order of keyword arguments

new function

PEP-515 Now you can put _ in a numeric literal

You can now write 1000000000000000 as 1_000_000_000_000_000. There are no semantic changes, just _ for readability.

PEP-523 Addition of frame evaluation API

I couldn't customize the evaluation of the frame object so far, but I added a C-level API to make it possible. This seems to make it easier to implement JIT and Debugger.

PEP-519 Addition of file system path protocol

Traditionally, filesystem paths are of type str or bytes, and libraries that handle paths, including the Python standard, have been created with that assumption. This made it difficult to use a path representation library in combination with an existing library, such as pathlib. ..

To solve this, we defined an interface (virtual base class) called ʻos.PathLike. By defining a method called fspath ()` that inherits this and returns a string representation of the path, the object that represents the path will be recognized by other libraries as the path and will operate. It was.

PEP-498 Formatted string literal

Prefix the string with f to make it a formatted string. Similar to str.format format, but the part enclosed by { and } is replaced as a variable. For example, like this.

>>> name = "Monty Python"
>>> f"my name is{name}is"
'My name is monty python'

This is when str.format is used

>>> "my name is{name}is".format(name=name)

Or

>>> "my name is{}is".format(name)

I had to do it, so it seems a little easier to describe.

PEP-526 Introduction of notation to annotate variables

Python is a dynamically typed language without explicit typing, but it has the problem that it is difficult to do static analysis. To solve this, PEP-484 (https://www.python.org/dev/peps/pep-0484/) proposed a method of adding type information to the function argument, and in Python 3.5 Introduced.

This change is to extend this further so that variables (including class variables and instance variables) can also be given type information. In the past, it was possible to do the same by using comments, but the difference is that it was handled by changing the grammar. For example, like this.

from typing import List, Dict
 
primes: List[int] = [] #An example of an integer list type, initializing it with an empty list

captain: str  #String type. Example of not initializing

class Starship:
    stats: Dict[str, int] = {} #An example of a class variable. Dictionary type that takes a character string as a Key and an integer as a value

Note that this type annotation does not change the behavior, and assigning a value of a different type does not cause an error. It is just a "hint" for type information, and is intended for static analysis based on this information.

PEP-529 Changed Windows file system encoding to UTF-8

In the past, when passing a path using Bytes on Windows, data loss may occur. Starting with Python 3.6, even if you are using Bytes, it will be encoded and returned with the system default encoding. The default encoding is UTF-8 so far, but it may change eventually depending on the feedback during the beta period.

PEP-487 Easy customization of class generation

When a class is inherited, a class method called __init_subclass__ (cls) will be called. You can write customized code in this. Also, when initializing the descriptor object, a method called __set_name__ will be called.

PEP-528 Changed Windows console encoding to UTF-8

It now accepts all Unicode characters and can be read correctly into a str object. And the default encoding for sys.stdin, sys.stdout, and sys.stderr is UTF-8.

PYTHONMALLOC environment variable

You can change the behavior of Python's memory allocation or set a hook for debugging by entering a value in an environment variable called PYTHONMALLOC.

PYTHONMALLOC=debug With this setting, the following debugging functions are enabled. --The newly allocated memory area is filled with 0xCB --The free space is filled with 0xDB --Illegal use of memory allocation API is detected. For example, when the area taken by PyMem_Malloc () is released by PyObject_Free (). --Detects when writing before the allocated area (buffer underflow) or after writing (buffer overflow). --Check if GIL (Global Interpreter Lock) is secured when the memory allocation function is called.

PYTHONMALLOC=malloc This setting forces the C library's malloc to be used. This allows you to use external tools such as Valgrind.

PYTHONMALLOC=malloc_debug Combination of the above two

DTrace and system tap support

Compiling with --with-dtrace enables markers that detect the following events.

--Function call, function return --Start and end of garbage collection --Line number of the code being executed

This feature allows you to debug and profile Python without having to recompile it for debugging.

PEP-520 Preserving the definition order of class attributes

Class attributes are retained in the class's __dict __ attribute in the order they are written in the source code.

PEP-468 Preserving keyword argument order

Function keyword arguments are passed to ** kwargs in a preserved order.

PEP-509 Introduced internal version to dictionary type object

Introduced a version that is updated only when changes are made to dictionary objects. As a result, various optimizations (performance improvements) can be performed.

Other language changes

dict () now uses a compact representation derived from PyPy, which uses 20-25% less memory than Pythono 3.5. And the order retention of the keyword arguments of PEP-468 is implemented using this. On the other hand, the property of "order is preserved" is implementation-dependent and may change in the future, so implementation should not be based on that assumption.

--Long traceback repetitions are now omitted

--ʻImportnow returnsModuleNotFoundError` if the module cannot be found

New module

(None so far)

Improved module

asyncio Since asyncio is defined as "provisional", all changes will be backported to 3.5.x as well.

The main changes from 3.5.0 are as follows.

--ʻEnsure_future () functions and functions that use them can now take all kinds of awaitable objects as arguments. --A new run_coroutine_threadsafe ()function has been introduced to allow other threads to submit coroutines into the event loop. --ATransport.is_closing ()method has been added to allow you to see if the transport is closed (or in the process of being closed). --Theloop.create_server ()method can now take a list of hosts as an argument. --Theloop.create_future ()method has been added to allow you to create Future objects. This allows for an alternative event loop implementation and can provide a faster asyncio.Future. --Added theloop.get_exception_handler () method to get the current exception handler. --timeout ()The context manager makes it easier to apply timeout processing code. --Added theStreamReader.readuntil ()method to read streams delimited by separator bytes. --Theloop.getaddrinfo ()method has been improved so that you don't have to callgetaddrinfo` on the OS side if the address has already resolved.

I haven't used asyncio very much, but I tried using run_coroutine_threadsafe ().

asyncio_test.py


import asyncio

@asyncio.coroutine
def wakeup(name, repeat):
    for i in range(repeat):
        yield from asyncio.sleep(1)
        print("{}/{}:woke up!".format(name, i))
    return repeat

def target(name, repeat, loop):
    future = asyncio.run_coroutine_threadsafe(wakeup(name, repeat), loop)
    return future.result()

loop = asyncio.get_event_loop()

futures = [
    loop.run_in_executor(None, target, "A", 1, loop),
    loop.run_in_executor(None, target, "B", 2, loop),
    loop.run_in_executor(None, target, "C", 3, loop),
]

loop.run_until_complete(asyncio.wait(futures))
loop.close()

It's a little confusing, but the coroutine that wakeup executes. After sleeping for 1 second, just print the line "Wake up!" With the name given by name. Repeat it as many times as the other argument repeat. The function called target executes the coroutine, and calls run_coroutine_threadsafe in it. I'm running it with run_in_executor to run it in a separate thread.

The execution result should look like this.

$ python asyncio_test.py
A/0:woke up!
B/0:woke up!
C/0:woke up!
B/1:woke up!
C/1:woke up!
C/2:woke up!

As mentioned above, this asyncio change has been backported to the 3.5 series, and it seems that it is actually implemented in 3.5.1. In fact, the above example works fine.

contextlib Contextlib.AbstractContextManager has been added as a virtual base class for context managers to provide default implementations for__enter__ ()and__exit__ (). A similar class has also been added to the typing module.

venv venv now accepts the --prompt parameter. This allows you to change the command line prompt prefix in a virtual environment.

datetime The datetime.strftime () and date.strftime () methods now support ISO 8601's % G,% u, and % V. % G and% V represent the year and week number (01-53) in weekly notation, and% u represents the number of the week (Monday is 1 and Sunday is 7).

distutils.command.sdist The default_format attribute has been removed from distutils.command.sdist.sdist and the default attribute is now ['gztar']. Unexpectedly, any code that depends on this attribute must be fixed.

email The new email API with the policy argument is no longer "provisional" and the documentation has been rewritten around it. Traditional documentation remains as a legacy API.

ʻEmail.mime classes and DecodedGenerator` now accept policy arguments.

A message_factory attribute has been added to the policy object to allow the parser to specify which message class to use when generating new messages.

encodings Added 'oem' to use CP_OEMCP on Windows environment. Also, an alias ʻansi has been added to mbcsthat usesCP_ACP`.

faulthandler Now installs handlers that raise Windows exceptions in a Windows environment.

hashlib hashlib now supports OpenSSL 1.1.0. The recommended version is 1.0.2 or higher, but it has also been tested with 0.9.8zc, 0.9.8zh, 1.0.1t and LibreSSL 2.3, 2.4.

Support for the BLAKE2 hash function has been added, and blake2b () and blake2s () are now available.

SHA-3 hash functions sha3_224 (), sha3_256 (), sha3_384 (), sha3_512 () and SHAKE hash functions shake_128 (), shake_256 () have been added.

It is now available when the password-based key derivation function scrypt () is OpenSSL 1.1.0 or higher.

http.client

HTTPConnection.request () and endheaders () now support chunked encoding in the request body.

idlelib and IDLE

The idlelib package has been refactored in a modern way to improve the look, operability and visibility of IDLE. The changes include changing the file name, and the code up to 3.5 will not work as it is.

importlib Since ʻimportlib.util.LazyLoader now calls create_module () on the wrapper loader, ʻimportlib.machinery.BuiltinImporter and ʻimportlib.machinery.ExtensionFileLoader are together with ʻimportlib.util.LazyLoader. There is no longer a restriction that it cannot be used for.

ʻImportlib.util.cache_from_source (), ʻimportlib.util.source_from_cache (), ʻimportlib.util.spec_from_file_location ()` can now receive path-like objects.

json json.load () and json.loads () can now accept binaries as input. The encoded JSON must be encoded in UTF-8, UTF-16, or UTF-32.

os A close () method has been provided to explicitly close the scandir () itator. And the scandir () iterator now supports the context manager protocol. If the scandir () iterator is not used up or explicitly closed, a ResourceWarning exception will be raised in the destructor. I think this is a memory leak countermeasure, but if you use it with the with statement, it will be called automatically.

The Linux getrandom () system call is now available via the new os.getrandm () function.

pickle You can now salt (pickle) objects that had to be called __new__ with keyword arguments. This was possible with pickle version 4 or higher, but with this change it is now possible with version 3 or lower.

re

Added qualifiers for regular expressions. For example, '(? I: p) ython' matches'python' and 'Python' but not'PYTHON'. Similarly, '(? I) g (?-i: v) r' matches'GvR' and 'gvr' but not'GVR'.

readline set_auto_history () has been added, and it is now possible to control whether or not it is automatically added to the history.

rlcompleter rlcompleter is readline's completion. The first change is to remove module variables, methods and attributes starting with an underscore ('_') from the list of completions. It's hard to understand, so here's an example. Previously, when I started Python in interactive mode, typed "int." And then pressed the TAB key twice, this happened.

$ python
Python 3.5.2 (default, Jul  7 2016, 23:37:57)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> int.<TAB><TAB>
int.__abs__(            int.__dir__(            int.__hash__(           int.__mul__(            int.__reduce__(         int.__rtruediv__(       int.__xor__(
int.__add__(            int.__divmod__(         int.__index__(          int.__name__            int.__reduce_ex__(      int.__rxor__(           int.bit_length(
int.__and__(            int.__doc__             int.__init__(           int.__ne__(             int.__repr__(           int.__setattr__(        int.conjugate(
int.__base__(           int.__eq__(             int.__instancecheck__(  int.__neg__(            int.__rfloordiv__(      int.__sizeof__(         int.denominator
int.__bases__           int.__flags__           int.__int__(            int.__new__(            int.__rlshift__(        int.__str__(            int.from_bytes(
int.__basicsize__       int.__float__(          int.__invert__(         int.__or__(             int.__rmod__(           int.__sub__(            int.imag
int.__bool__(           int.__floor__(          int.__itemsize__        int.__pos__(            int.__rmul__(           int.__subclasscheck__(  int.mro(
int.__call__(           int.__floordiv__(       int.__le__(             int.__pow__(            int.__ror__(            int.__subclasses__(     int.numerator
int.__ceil__(           int.__format__(         int.__lshift__(         int.__prepare__(        int.__round__(          int.__subclasshook__(   int.real
int.__class__(          int.__ge__(             int.__lt__(             int.__qualname__        int.__rpow__(           int.__text_signature__  int.to_bytes(
int.__delattr__(        int.__getattribute__(   int.__mod__(            int.__radd__(           int.__rrshift__(        int.__truediv__(
int.__dict__            int.__getnewargs__(     int.__module__          int.__rand__(           int.__rshift__(         int.__trunc__(
int.__dictoffset__      int.__gt__(             int.__mro__             int.__rdivmod__(        int.__rsub__(           int.__weakrefoffset__
>>> int.

This will be like this from 3.6.

ython 3.6.0a3 (default, Jul 16 2016, 00:35:58)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> int.
int.bit_length(  int.conjugate(   int.denominator  int.from_bytes(  int.imag         int.mro(         int.numerator    int.real         int.to_bytes(

Names starting with _ are excluded from completion candidates. If you want to see them, type _ and then<TAB> <TAB>.

>>> int.__
int.__abs__(             int.__dict__             int.__getattribute__(    int.__lt__(              int.__prepare__(         int.__ror__(             int.__subclasscheck__(
int.__abstractmethods__  int.__dictoffset__       int.__getnewargs__(      int.__mod__(             int.__qualname__         int.__round__(           int.__subclasses__(
int.__add__(             int.__dir__(             int.__gt__(              int.__module__           int.__radd__(            int.__rpow__(            int.__subclasshook__(
int.__and__(             int.__divmod__(          int.__hash__(            int.__mro__              int.__rand__(            int.__rrshift__(         int.__text_signature__
int.__base__(            int.__doc__              int.__index__(           int.__mul__(             int.__rdivmod__(         int.__rshift__(          int.__truediv__(
int.__bases__            int.__eq__(              int.__init__(            int.__name__             int.__reduce__(          int.__rsub__(            int.__trunc__(
int.__basicsize__        int.__flags__            int.__instancecheck__(   int.__ne__(              int.__reduce_ex__(       int.__rtruediv__(        int.__weakrefoffset__
int.__bool__(            int.__float__(           int.__int__(             int.__neg__(             int.__repr__(            int.__rxor__(            int.__xor__(
int.__call__(            int.__floor__(           int.__invert__(          int.__new__(             int.__rfloordiv__(       int.__setattr__(
int.__ceil__(            int.__floordiv__(        int.__itemsize__         int.__or__(              int.__rlshift__(         int.__sizeof__(
int.__class__(           int.__format__(          int.__le__(              int.__pos__(             int.__rmod__(            int.__str__(
int.__delattr__(         int.__ge__(              int.__lshift__(          int.__pow__(             int.__rmul__(            int.__sub__(
>>> int.__

Then, after completing some keywords, a space ('') or a colon (':') was added. For example, if you type wi and press<TAB>, it will be complemented withwithwith a space, and if you type tr, <TAB> will result in try:. Convenient for soberness.

Also, it is possible to complement attributes created with @property that have not been displayed so far, but I was not sure about this.

site I'm checking for duplicates when adding a path to sys.path, but it seems to be a fix if it doesn't work.

sqlite3 sqlite3.Cursor.lastrowid returns the column ID of the last modified column, which was valid only when INSERT was executed so far, but now it can be obtained when REPLACE is executed.

socket The SIO_LOOPBACK_FAST_PATH function can now be used with the ʻioctl ()` function to improve TCP loopback performance in Windows environments (Win8 and above).

The getsockopt () constants SO_DOMAIN, SO_PROTOCOL, SO_PEERSEC, and ʻand SO_PASSSEC` are now supported.

The address family AF_ALG is now supported and the Crypto API of the Linux kernel is now available.

socketserver Servers based on the socketserver module (as defined in http.server, xmlrpc.server and wsgiref.simple_server) now support the context manager protocol.

Implemented the writable interface where the wfile attribute of the StreamRequestHandler class is ʻio.BufferedIOBase. In particular, write ()` is now guaranteed to send all the data.

ssl ssl now supports OpenSSL 1.1.0. The recommended version is 1.0.2 or higher, but it has also been tested with 0.9.8zc, 0.9.8zh, 1.0.1t and LibreSSL 2.3, 2.4.

3DES has been removed from the default cipher suite. Also, the ChaCha20 Poly1305 cipher suite is now in the right place.

The default configuration for SSLContext now uses better options and ciphers.

SSL sessions can now be copied from the client side to the other side using SSLSession. Improved speed of resuming TLS sessions.

All constants and flags have been changed from IntEnum to IntFlags.

Server-side only and Client-side only protocols have been added as parameters to be passed when creating an SSLContext.

Entering the General resource ID in the subject alias extension area no longer causes a system error.

subprocess A child process created with subprocess.Popen now raises aResourceWarning exception when trying to clear a Popen object while it is running.

telnetlib Telnet implements the context manager protocol.

tkinter Added the trace_add () trace_remove () trace_info () method to the tkinter.Variable class to replace the implementation that used the old Tcl API.

traceback Long traceback repetitions are now omitted. For example, if you execute a self-looping function, it will look like this.

>>> def f(): f()
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  [Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded

typing Added the typing.ContextManager class for contextlib.AbstractContextManager (as mentioned above).

unicodedata The internal database has been upgraded to Unicode 9.0.0.

unittest.mock Mock.assert_called () and Mock.assert_called_once () have been added to the Mock class to allow you to see if a mock object has been called.

urllib.request If the HTTP request has a file or a repeatable body (except for byte objects) but the Content-length header is not specified, it used to be an error, but it should be sent with Chunked transfer encoding. Became.

urllib.robotparser The RobotFileParser now supports the Crawl-delay and Request-rate extensions. These are used in robots.txt to adjust the crawling interval. --Crawl-delay: Time (in seconds) to wait before starting crawling --Request-rate: Number of pages that can be requested within a certain period of time

warnings The source parameter has been added to thewarnings.warn_explicit ()function to show the object that caused the ResourceWarning. The source attribute has also been added to warnings.WarningMessage.

Then, when ResourceWarning goes up, tracemalloc is used, and it is now possible to trace back the memory of the object to be erased. Such an example is given.

example.py


import warnings

def func():
    return open(__file__)

f = func()
f = None

The file is opened in the func function, and immediately after that, the reference to the file object is overwritten with NULL to cut it. When you do this, it looks like this.

$ python -Wd -X tracemalloc=5 example.py
example.py:7: ResourceWarning: unclosed file <_io.TextIOWrapper name='example.py' mode='r' encoding='UTF-8'>
  f = None
Object allocated at (most recent call first):
  File "example.py", lineno 4
    return open(__file__)
  File "example.py", lineno 6
    f = func()

winreg The winreg module that manipulates the registry in the Windows environment now supports the REG_QWORD type of 64-bit integer.

winsound You can now pass keyword arguments with Beep, MessageBeep, and PlaySound.

xmlrpc.client Supports new numeric type and None unmarshalling in Apache XML-RPC implementation

zipfile A class method called ZipInfo.from_file () has been added, allowing you to create a ZipInfo object by specifying a file name, and the ZipInfo.is_dir () method to check if it is a directory. It was. And ZipFile.open () can now be used not only to retrieve data from ZIP files, but also to write to them.

zlib The compress () function can now specify level as a keyword argument.

fileinput With hook_encoded (), you can now specify not only the encoding used when opening a file, but also the error handler. See the ʻerrors parameter in ʻopen () for details.

optimisation

--ASCII decoders are up to 60 times faster when the error handler is surrogate escape ʻignore replace`. --ASCII and Latin1 encoders are up to 3x faster when the error handler is `surrogate escape`. --The UTF-8 encoder is up to 75 times faster when the error handler is ʻignore replace surrogateescape surrogatepass`. --The UTF-8 decoder is up to 15 times faster when the error handler is ʻignore` `replace surrogate escape. --bytes% args is now up to 2x faster. --bytearray% args is now 2.5 to 5 times faster. --bytes.fromhex ()andbytearray.fromhex () are now 2 to 3.5 times faster. --bytes.replace (b'', b'.')Andbytearray.replace (b'', b'.') Are up to 80% faster. --PyMem_Malloc () now uses pymalloc instead of malloc in the C library for domain memory allocation. pymalloc is optimized for short-lived objects of 512 bytes or less, and malloc is used to allocate larger blocks. --pickle.load ()andpickle.loads ()` are now up to 10% faster when loading large numbers of small objects. --Keyword arguments have more overhead than passing positional arguments, but the feature using Argument Clinic (a preprocessor for CPython's C code) has significantly reduced that overhead. --glob () and iglob () in the glob module have been optimized and are 3 to 6 times faster. --Optimized pathlib globbling with os.scandir (), 1.5 to 4 times faster

Build and C API changes

--You need a toolchain that supports C99 to build Python. --Cpython can now be cross-compiled with Android NDK and run normally at Android API level 21 and above. Android is not yet an officially supported platform, but the standardized test suite runs on the Android emulator with good results (only 16 failures). -Added --with-optimization to the configuration flag. If specified, LTO (Link Time Optimization) and PGO (Profile-Guided Optimization) build support will be enabled. --The Py_FinalizeEx () API has been introduced to let you know if the interpreter termination process was successful (whether there was an error during termination processing). --PyArg_ParseTupleAndKeywords () now supports position-only arguments. --PyTrackback_Print now displays without long iterations.

Candidate for abolition

Deprecated build options

The --with-system-ffi option is enabled by default on platforms other than OS X. It can be disabled with --without-system-ffi, but the use of this flag is no longer possible since Python 3.7. OS X is not affected by this change.

New keywords

Using ʻasync and ʻawait as variable names, class names, function names, and module names has been deprecated. Introduced in Python 3.5 by PEP-492, ʻasync and ʻawait will be official keywords in Python 3.7.

Deprecated Python modules, functions, methods

--importlib.machinery.SourceFileLoader.load_module () importlib.machinery.SourcelessFileLoader.load_module () has been deprecated. --The tkinter.tix module has been deprecated. Use tkinter.ttk instead.

Deprecated C API functions and types

-(None for now)

Deprecated features

--The pyvenv script will be deprecated. The python3 -m venv specification is recommended instead --ImportWarning exception will now occur if __spec__ or __package__ is not defined when doing relative import. --The dbm.dumb module was always open and updatable, and was created if it didn't exist. This behavior has been deprecated to match other dbm implementations and will not be available in Python 3.8. --The use of byte-like objects used as paths in some modules has been deprecated. --distutils ʻextra_pathhas been deprecated. --DeprecationWarning will occur if the backslash and character combination does not result in the correct escape sequence. In the future, it will be a syntax error, but it will remain as it is for a while. --The inline flag(? Letters)can now only be used at the beginning of a regular expression. --SSL-related arguments likecertfile, keyfile, check_hostnameare used in ftplib, http.client, imaplib, poplib, smtplib, etc., but they have been deprecated. Expected to usecontext` instead. --Several protocols and functions in the ssl module have been deprecated. Those that will no longer be OpenSSL in the future, or those for which other alternatives have been provided.

Deprecated Python behavior

--Deprecation Warning now increases when Stop Iteration is raised in the generator. From 3.7 this is a Runtime Error.

deleted

API and feature removal

--ʻInspect.getmoduleinfo () has been removed. Use ʻinspect.getmodulename () to find out the module name of a path. --traceback.Ignore class and traceback.usage traceback.modname`` traceback.fullmodname traceback.find_lines_from_code`` traceback.find_lines traceback.find_strings`` traceback.find_executable_lines I did. These are deprecated candidates from 3.2 and similar functionality is provided by private methods. --tk_menuBar () tk_bindForTraversal () The dummy method has been removed from the tkinter widget class. --The ʻopen ()method of thezipfile.ZipFile class has removed support for'U'mode. As an alternative, use ʻio.TextIOWrapper to read the compressed file.

When porting to Python 3.6

Here are some things to keep in mind when porting your code to Python 3.6.

Python command behavior

--COUNT_ALLOCS`` SHOW_ALLOC_COUNT`` SHOW_TRACK_COUNT Python output built with macros defined is turned off by default. To turn this on, add -X showalloccount to the argument and start Python. Also, the output destination has changed from stdout to stderr.

Python API changes

-(Omitted because it is a little fine)

C API changes

--PyMem_Malloc () Memory allocation now uses pymalloc instead of system maloc, so apps that call PyMem_Malloc () without taking the GIL will crash. You can check the memory allocation by setting the PYTHONMALLOC environment variable to debug. --Py_Exit () (and the main interpreter) now returns 120 if memory release at exit fails.

Finally

I was going to take a quick look at the changes, but as I was looking at them, various interesting points came out and it took longer than I expected. As of now, there is no further change in b1 by definition, so I deleted "(α3 version)" from the title. The final of 3.6 is scheduled for mid-December, so there may be changes again, but I'll update it from time to time.

Recommended Posts

What's new in Python 3.5
What's new in Python 3.6
What's new in Python 3.10 (Summary)
What's new in Python 3.4.0 (2) --enum
What's new in Python 3.9 (Summary)
What's new in python3.9 Merge dictionaries
New in Python 3.4.0 (1)-pathlib
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
pandas 1.2.0 What's new
Lifegame in Python.
FizzBuzz in Python
StepAIC in Python
N-gram in python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
New in Python 3.9 (2)-Sort directed acyclic graphs in Python
What's new in Django 1.8 Conditional Expressions #djangoja
New features in Python 3.4.0 (3)-Single-dispatch generic functions
What's new in datetime that is a bit more useful in Python 3
Daily AtCoder # 36 in Python
Clustering text in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python
Edit fonts in Python
Singleton pattern in Python
File operations in Python
Read DXF in python
Daily AtCoder # 53 in Python