美高梅官方网站66159

请参阅更新日志,这种语言具有非常爽直而显明的语法特点

作者:文章排名    来源:未知    发布时间:2020-04-21 17:49    浏览量:

Python 3.4.0 发表,此版本包括一花样好些个 3.x 类别的精雕细刻,数百个小的精雕细琢和 bug 修复。

正文解释了Python 3.6中的新功能,与3.5对待。Python 3.6于二零一四年12月二十三日透露。有关总体的详细新闻,请参阅更新日志。

图片 1

值得注意的翻新内容如下:

Summary – Release highlights(摘要)

新特性

  • PEP 498, formatted string literals.
    (格式化的字符串文字。)
  • PEP 515, underscores in numeric literals.
    (以数字文字表示。)
  • PEP 526, syntax for variable annotations.
    (变量注释的语法。)
  • PEP 525, asynchronous generators.
    (异步产生器。)
  • PEP 530: asynchronous comprehensions.
    (异步领悟。)

Python 是一种面向对象、直译式Computer程序设计语言,也是一种功能强盛而全面的通用型语言,已经持有十多年的腾飞历史,成熟且稳固性。这种语言具备拾壹分耿直而清晰的语法特点,切合实现各类高级任务,大约可以在全数的操作系统中运维。 Python 3.2 RC 1 版本发布。该版本的精益求精内容: •numerous improvements to the unittest module•PEP 3147, support for .pyc repository directories•PEP 3149, support for version tagged dynamic libraries•PEP 3148, a new futures library for concurrent programming•PEP 384, a stable ABI for extension modules•PEP 391, dictionary-based logging configuration•an overhauled GIL implementation that reduces contention•an extended email package that handles bytes messages•a much improved ssl module with support for SSL contexts and certificate hostname matching•a sysconfig module to access configuration information•additions to the shutil module, among them archive file support•many enhancements to configparser, among them mapping protocol support•improvements to pdb, the Python debugger•countless fixes regarding bytes/string issues; among them full support for a bytes environment (filenames, environment variablesState of Qatar•many consistency and behavior fixes for numeric operations下载和查看详细的本子公布消息:访问python官网:

新语法本性:

CPython达成改良

CPython implementation improvements:

  • The dict(词典,python的主干类型) type has been reimplemented to use a more compact representation based on a proposal by RaymondHettinger and similar to the PyPy dict implementation(PyPy dict完成). This resulted in dictionaries using 60% to 十分之三 less memory when compared to Python 3.5.
    (该词典类型已重新完成选取更紧密的代表 基于由雷Mond·赫廷格的提构和左近PyPy辞书达成。与Python 3.5相对来讲,那使得词典的内部存储器裁减了20%到25%。)
  • Customization of class creation has been simplified with the new protocol.
    (通过新说道简化了类创立的定制 。)
  • The class attribute definition order is now preserved.
    (类属性定义顺序 现在被保存。)
  • The order of elements in kwargs now corresponds to the order in which keyword arguments were passed to the function.
    kwargs中的成分顺序现在对应于传递给函数的显要字参数的一一。)
    DTrace and SystemTap probing support has been added.
    (增多了DTrace和SystemTap探测援助。)
  • The new PYTHONMALLOC environment variable can now be used to debug the interpreter memory allocation and access errors.
    (今后得以选择新的PYTHONMALLOC景况变量来调解解释器内部存款和储蓄器分配和访问错误。)
  • Python 3.4 并未有丰富别的新的语法脾气

标准库的主要修正:

Significant improvements in the standard library

  • The asyncio module has received new features, significant usability and performance improvements, and a fair amount of bug fixes. Starting with Python 3.6 the asyncio module is no longer provisional and its API is considered stable.
    (该asyncio模块已经获取了新效率,显着的可用性和性质改善,以至大气的不当修复。从Python 3.6发端,该asyncio模块不再是一时半刻的,它的API被以为是平静的。)
  • A new file system path protocol has been implemented to support path-like objects. All standard library functions operating on paths have been updated to work with the new protocol.
  • (已经达成了一种新的文件系统路线公约来支撑相近路线的指标。全部在路子上运营的业内库函数皆是履新,以十一分新说道)
  • The datetime module has gained support for Local Time Disambiguation.
    (该datetime模块获得了地面时间消歧的支撑 。)
    The typing module received a number of improvements.
    (typing模块选择了有的 校正。)
  • The tracemalloc module has been significantly reworked and is now used to provide better output for ResourceWarning as well as provide better diagnostics for memory allocation errors. See the PYTHONMALLOC section for more information.
    (该tracemalloc模块已经大大退换,以后用于提供越来越好的输出ResourceWarning以致为内部存款和储蓄器分配错误提供越来越好的确诊。有关详细消息,请参阅PYTHONMALLOC部分。)

其余新特点:

白山改正

  • The new secrets module has been added to simplify the generation of cryptographically strong pseudo-random numbers suitable for managing secrets such as account authentication, tokens, and similar.
  • On Linux, os.urandom() now blocks until the system urandom entropy pool is initialized to increase the security. See the PEP 524 for the rationale.
  • The hashlib and ssl modules now support OpenSSL 1.1.0.
  • The default settings and feature set of the ssl module have been improved.
  • The hashlib module received support for the BLAKE2, SHA-3 and SHAKE hash algorithms and the scrypt() key derivation function.
    (该hashlib模块援救BLAKE2,SHA-3和SHAKE哈希算法以致scrypt(卡塔尔密钥导出效果。)
  • pip should always be available (PEP 453).

  • Newly created file descriptors are non-inheritable(PEP 446).

  • command line option for isolated mode(issue 16499).

  • improvements in the handling of codecsthat are not text encodings (multiple issues).

  • A ModuleSpec Type for the Import System (PEP 451).  (Affects importer authors.)

  • The marshal format has been made more compact and efficient (issue 16475).

Windows improvements

  • PEP 528 and PEP 529, Windows filesystem and console encoding changed to UTF-8.
    (Windows文件系统和决定台编码纠正为UTF-8)
  • The py.exe launcher, when used interactively, no longer prefers Python 2 over Python 3 when the user doesn’t specify a version (via command line arguments or a config file). Handling of shebang lines remains unchanged - “python” refers to Python 2 in that case.
  • (py.exe当顾客未有一点名版本(通过命令行参数或铺排文件)时,运维器在人机联作式使用时不再动用Python 2,而是使用Python 3。shebang行的管理保持不改变 - “python”在这里种境况下是指Python 2。)
  • python.exe and pythonw.exe have been marked as long-path aware, which means that the 260 character path limit may no longer apply. See removing the MAX_PATH limitation for details.
    (python.exe和pythonw.exe已被标识为长光程知道,那代表264个字符的- 路线约束或许不再适用。有关详细音信,请参阅删除MAX_PATH限制。)
  • A ._pth file can be added to force isolated mode and fully specify all search paths to avoid registry and environment lookup. See the documentation for more information.
    (一个._pth文件能够被加多到强迫隔开分离形式和完全内定全数的查找路线,以免止注册表和条件查找。有关详细新闻,请参阅 文书档案。)
  • A python36.zip file now works as a landmark to infer PYTHONHOME. See the documentation for more information.
    (三个python36.zip文件现在作为多少个里程碑估量PYTHONHOME。有关详细消息,请参阅文书档案。)

新的库模块:

New Features(新功能)

  • asyncio: New provisional API for asynchronous IO (PEP 3156).

  • ensurepip: Bootstrapping the pip installer(PEP 453).

  • enum: Support for enumeration types(PEP 435).

  • pathlib: Object-oriented filesystem paths(PEP 428).

  • selectors: High-level and efficient I/O multiplexing, built upon the select module primitives (part of PEP 3156).

  • statistics: A basic numerically stable statistics library (PEP 450).

  • tracemalloc: Trace Python memory allocations (PEP 454).

Formatted string literals(string的格式化)

Formatted string literals are prefixed with 'f' and are similar to the format strings accepted by str.format(). They contain replacement fields surrounded by curly braces. The replacement fields are expressions, which are evaluated at run time, and then formatted using the format() protocol:
(字符串的格式化相通于字符串f的str.format(卡塔尔国格式化。它们含有被大括号包围的替换字段。替换字段是在运营时怎么格式的表达式,然后接收format(卡塔尔公约举行格式化 )

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'

库模块中根本的精雕细刻:

变量注释的语法

Syntax for variable annotations

introduced the standard for type annotations of function parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating the types of variables including class variables and instance variables:
(引入了功能参数类型注释的职业,也称为类型提醒。这一个PEP加多了Python的语法来批注变量的档次,包括类变量和实例变量:State of Qatar

primes: List[int] = []

captain: str  # Note: no initial value!

class Starship:
    stats: Dict[str, int] = {}

  Just as for function annotations, the Python interpreter does not attach any particular meaning to variable annotations and only stores them in the annotations attribute of a class or module.

   In contrast to variable declarations in statically typed languages, the goal of annotation syntax is to provide an easy way to specify structured type metadata for third party tools and libraries via the abstract syntax tree and the annotations attribute.

(  就如函数注释相像,Python解释器对变量注释未有增大其余特定的意思,只将它们存款和储蓄在__annotations__类或模块的 属性中。

  与静态类型语言中的变量注解反倒,注释语法的指标是提供一种通过架空语法树和__annotations__性子为第三方工具和库钦赐结构化类型元数据的简要方法。卡塔尔(قطر‎

  • Single-dispatch generic functions infunctools (PEP 443).

  • New pickle protocol 4 (PEP 3154).

  • multiprocessing now has an option to avoid using os.fork on Unix (issue 8713).

  • email has a new submodule, contentmanager, and a new Message subclass (EmailMessage) that simplify MIME handling (issue 18891).

  • The inspect and pydoc modules are now capable of correct introspection of a much wider variety of callable objects, which improves the output of the Python help() system.

  • The ipaddress module API has been declared stable

数字的加强

Underscores in Numeric Literals

   adds the ability to use underscores in numeric literals for improved readability. For example:
(扩大了在数字文字中利用下划线的本领,以进步可读性。举个例子)

>>> 1_000_000_000_000_000
1000000000000000
>>> 0x_FF_FF_FF_FF
4294967295

Single underscores are allowed between digits and after any base specifier. Leading, trailing, or multiple underscores in a row are not allowed.

The string formatting language also now has support for the '_' option to signal the use of an underscore for a thousands separator for floating point presentation types and for integer presentation type 'd'. For integer presentation types 'b', 'o', 'x', and 'X', underscores will be inserted every 4 digits:

(  允许在数字之间和别的基本表明符之后接收单个下划线。不容许一行中的前导,尾随或多个下划线。

  该字符串格式化语言将来也具备了协理'_'信号为千位分隔符使用下划线的浮点展现类型和整数显示类型选择'd'。对于整数展现类型'b', 'o','x',和'X',下划线将被插入每4个位数:)

'{:_}'.format(1000000) '1_000_000' '{:_x}'.format(0xFFFFFFFF) 'ffff_ffff'

安全改善:

异步发生器

  引进了对地面协作程序的协理和async/await 或Python 3.5语法。Python 3.5兑现的贰个显着的界定是不可能利用await和yield在同叁个成效体中。在Python 3.6中,这么些限定被破除了,能够定义异步产生器:

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)

新语法允许更加快更简洁的代码。

  • Secure and interchangeable hash algorithm(PEP 456).

  • Make newly created file descriptors non-inheritable(PEP 446) to avoid leaking file descriptors to child processes.

  • New command line option for isolated mode, (issue 16499).

  • multiprocessing now has an option to avoid using os.fork on Unix.  spawn and forkserver are more secure because they avoid sharing data with child processes.

  • multiprocessing child processes on Windows no longer inherit all of the parent’s inheritable handles, only the necessary ones.

  • A new hashlib.pbkdf2_hmac() function provides the PKCS#5 password-based key derivation function 2.

  • TLSv1.1 and TLSv1.2 support for ssl.

  • Retrieving certificates from the Windows system cert store support for ssl.

  • Server-side SNI (Server Name Indication) support for ssl.

  • The ssl.SSLContext class has a lot of improvements.

  • All modules in the standard library that support SSL now support server certificate verification, including hostname matching (ssl.match_hostname()) and CRLs (Certificate Revocation lists, seessl.SSLContext.load_verify_locations()).

异步扶植

 adds support for using async for in list, set, dict comprehensions and generator expressions:
  (扩展了在列表,会集,字母推导和生成器表达式中的使用帮忙:async for)

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

  Additionally, await expressions are supported in all kinds of comprehensions:
  (其它,await表达式扶助种种精晓:)

result = [await fun() for fun in funcs if await condition()]

CPython 完成修正:

定制类创立的简化

  It is now possible to customize subclass creation without using a metaclass. The new init_subclass classmethod will be called on the base class whenever a new subclass is created:

  (未来得以定制子类创造而不使用元类。新__init_subclass__类格局将在基类每当创设一个新的子类被号称:)

class PluginBase:
    subclasses = []

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

class Plugin1(PluginBase):
    pass

class Plugin2(PluginBase):
    pass

  In order to allow zero-argument super() calls to work correctly from init_subclass() implementations, custom metaclasses must ensure that the new classcell namespace entry is propagated to type.new (as described in Creating the class object).
  (为了允许零参数super(卡塔尔国调用从__init_subclass__(State of Qatar实现中健康工作,自定义元类必得保障新的__classcell__命名空间条约被传播到 type.new(如成立类对象中所述)。)

  • Safe object finalization (PEP 442).

  • Leveraging PEP 442, in most cases module globals are no longer set to None during finalization (issue 18214).

  • Configurable memory allocators (PEP 445).

  • Argument Clinic (PEP 436).

陈说符左券巩固

  extends the descriptor protocol to include the new optional set_name() method. Whenever a new class is defined, the new method will be called on all descriptors included in the definition, providing them with a reference to the class being defined and the name given to the descriptor within the class namespace. In other words, instances of descriptors can now know the attribute name of the descriptor in the owner class:

  (扩展描述符公约以囊括新的可选 set_name(卡塔尔国方法。每当定义八个新类时,将调用定义中包涵的全部描述符的新方式,为它们提供对定义的类的援用,以致类名称空间中给描述符的称谓。换句话说,描述符的实例以后能够知晓全体者类中的描述符的属性名称:)

class IntField:
    def __get__(self, instance, owner):
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if not isinstance(value, int):
            raise ValueError(f'expecting integer in {self.name}')
        instance.__dict__[self.name] = value

    # this is the new initializer:
    def __set_name__(self, owner, name):
        self.name = name

class Model:
    int_field = IntField()

其他的还富含不菲 CPython 的优化,用法和秘密移植难题,更多内容请看批发表达,新特征介绍或者是更新日志,可以在这里下载最新版本。

文件系统路线合同的加码

Adding a file system path protocol

File system paths have historically been represented as str or bytes objects. This has led to people who write code which operate on file system paths to assume that such objects are only one of those two types (an int representing a file descriptor does not count as that is not a file path). Unfortunately that assumption prevents alternative object representations of file system paths like pathlib from working with pre-existing code, including Python’s standard library.

(文件系统路线历来被代表为str 或bytes对象。那招致编写在文件系统路线上操作的代码的大家感觉那样的对象只是这两种类型之一(int表示一个文书陈诉符不被视为不是文件路线)。不幸的是,这种固然阻止了文件系统路径的代表对象表示,举例pathlib使用预先存在的代码,富含Python的标准库。)

To fix this situation, a new interface represented by os.PathLike has been defined. By implementing the fspath() method, an object signals that it represents a path. An object can then provide a low-level representation of a file system path as a str or bytes object. This means an object is considered path-like if it implements os.PathLike or is a str or bytes object which represents a file system path. Code can use os.fspath(), os.fsdecode(), or os.fsencode() to explicitly get a str and/or bytes representation of a path-like object.
(为驾驭决这种情景,os.帕特hLike已经定义了三个新的分界面 。通过落到实处该 fspath(卡塔尔国方法,三个目的表示它意味着路线。然后,对象能够提供作为str或 bytes对象的文件系统路线的低等表示。那意味三个目的被以为是 路线,假设它实现os.PathLike或是一个str或bytes表示文件系统路线的目的。代码能够使用os.fspath(卡塔尔国, os.fsdecode(卡塔尔(قطر‎或os.fsencode(卡塔尔(قطر‎显式地收获一个str和/或bytes三个看似路线的对象的代表。)

The built-in open() function has been updated to accept os.PathLike objects, as have all relevant functions in the os and os.path modules, and most other functions and classes in the standard library. The os.DirEntry class and relevant classes in pathlib have also been updated to implement os.PathLike.

(内置open(卡塔尔(قطر‎函数已被更新为接纳os.PathLike对象,os以至os.path模块中的全数相关功能以致标准库中的大非常多别样职能和类。本os.DirEntry类和血脉雷同类pathlib也扩充了更新来完成os.PathLike。)

The hope is that updating the fundamental functions for operating on file system paths will lead to third-party code to implicitly support all path-like objects without any code changes, or at least very minimal ones (e.g. calling os.fspath() at the beginning of code before operating on a path-like object).

  (希望更新文件系统路径上运转的基本效能将促成第三方代码隐含地协理具有相像路径的对象,而无需任何代码改良,或最少非常的小的os.fspath(卡塔尔代码(比方在操作起来时调用 代码)在路线样的对象上)。)

以下是有个别演示,表明什么pathlib.Path使用预先存在的代码更便于和透明地行使新界面:

>>> import pathlib
>>> with open(pathlib.Path("README")) as f:
...     contents = f.read()
...
>>> import os.path
>>> os.path.splitext(pathlib.Path("some_file.txt"))
('some_file', '.txt')
>>> os.path.join("/a/b", pathlib.Path("c"))
'/a/b/c'
>>> import os
>>> os.fspath(pathlib.Path("some_file.txt"))
'some_file.txt'

(文/开源中华夏儿女民共和国卡塔尔    

对当地时间歧义的管理

Local Time Disambiguation

In most world locations, there have been and will be times when local clocks are moved back. In those times, intervals are introduced in which local clocks show the same time twice in the same day. In these situations, the information displayed on a local clock (or stored in a Python datetime instance) is insufficient to identify a particular moment in time.
(在大部世界外省,皆有过,或在在以后都有地方的挂钟回调的时候。在此些时间里,在同一时候内,本地石英钟会同有的时候候呈现四个日子。在这里些意况下,彰显在地点时钟(或存款和储蓄在Python日期时间实例中)的音信不足以识别特准期刻。)

PEP 495 adds the new fold attribute to instances of datetime.datetime and datetime.time classes to differentiate between two moments in time for which local times are the same:
(将新的 fold属性加多到实例 datetime.datetime和datetime.time类中,以界别三个时间点,在那之中本土时间相近:)

u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc) for i in range(4): ... u = u0 + i*HOUR ... t = u.astimezone(Eastern) ... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold) ... 04:00:00 UTC = 00:00:00 EDT 0 05:00:00 UTC = 01:00:00 EDT 0 06:00:00 UTC = 01:00:00 EST 1 07:00:00 UTC = 02:00:00 EST 0

将Windows文件系统一编写码改正为UTF-8

  代表文件系统路线最棒用str(Unicode)实际不是字节来施行。不过,有个别情形下采纳字节是十足和不利的。

  在Python 3.6事情未发生前,在Windows上接收字节路径时大概会促成数据错失。通过这种转移,现在在Windows上扶持使用字节来表示路线,前提是这一个字节使用重回的编码(sys.getfilesystemencoding(卡塔尔国以后暗中同意为编码)实行编码 'utf-8'。

  不应用str表示路径的应用程序应该采用os.fsencode(卡塔尔(قطر‎并os.fsdecode(卡塔尔国确认保证其字节被正确编码。要恢复生机到早先的表现,请设置 PYTHONLEGACYWINDOWSFSENCODING或打电话 sys._enablelegacywindowsfsencoding()。

将Windows调控台编码改良为UTF-8

  Windows上的私下认可调节台以往将收受全数Unicode字符,并将准确读取的str对象提供给Python代码。sys.stdin, sys.stdout况且sys.stderr今后默感觉UTF-8编码。

  此改良仅适用于接纳交互作用式调控台时,并非重定向文件或管道时。要还原原先的人机联作式调整台使用的行事,请设置PYTHONLEGACYWINDOWSSTDIO。

下一篇:没有了

更多新闻推荐

Copyright © 2015-2019 http://www.77zhth.net. 美高梅官方网站66159有限公司 版权所有