Python 3.6 Brings Better Dictionaries, Improved Async I/O, and More

Python 3.6 Brings Better Dictionaries, Improved Async I/O, and More

原文連接html

bypython

Python is approaching its next major milestone, version 3.6. Expected to be released on December 16, Python 3.6 brings many new features, including faster and more compact dictionaries, improved asyncio, a new file system path protocol, and more.app

Python 3.6 introduces improvements to the dict type which reduce memory usage by 20% in comparison with Python 3.5. This is accomplished by using a new representation that is similar to PyPy’s and has be shown to also improve garbage collection performance.dom

The new Python release also makes it easier to customize subclass creation thanks to a new __init_subclass__ classmethod which is called on the base class whenever a subclass is created:async

class PluginBase:
    subclasses = []

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.subclasses.append(cls)

class Plugin1(PluginBase):
    pass

class Plugin2(PluginBase):
    pass

This new mechanism can be seen as an easier to use alternative to the previously existing metaclass mechanism for base class creation customization.ide

On the standard library front, there are several improved or new modules worth of mention: the asyncio module is no longer provisional and its API is considered stable, while a new secrets module aims to provide a way to reliably generate cryptographically strong pseudo-random values, such as those used to handle account authentication, tokens, etc. Additionally, the typing module, which supports the specification of type hints, has been declared stable.code

Other new features in Python 3.6 are:orm

  • literal string interpolation by means of formatted string literals as in the following example:htm

    >>> name = "Fred"
    >>> f"He said his name is {name}."
    'He said his name is Fred.'
    >>> width = 10
    >>> precision = 4
    >>> value = decimal.Decimal("12.34567")
    >>> f"result: {value:{width}.{precision}}"  # nested fields
    'result:      12.35'
  • underscores in numeric literals, which make it possible to write:blog

    >>> 1_000_000_000_000_000
    1000000000000000
    >>> 0x_FF_FF_FF_FF
    4294967295
  • asynchronous generators, made possible by removing the constraints that await and async could not be used in the same function body:

    async def ticker(delay, to): 
         """Yield numbers from 0 to *to* every *delay* seconds."""
         for i in range(to):
             yield i
             await asyncio.sleep(delay)
  • asynchronous comprehensions, as in the following example:

    result = [i async for i in aiter() if i % 2]

You can read the full list of new and improved features in Python 3.6 in the what’s new document.

相關文章
相關標籤/搜索