Python

Python 3.4의 새로운 기능

저자:

R. David Murray <rdmurray@bitdance.com> (편집자)

이 기사에서는 파이썬 3.3과 비교하여 3.4의 새로운 기능에 관해 설명합니다. 파이썬 3.4는 2014년 3월 16일에 출시되었습니다. 자세한 내용은 changelog <https://docs.python.org/3.4/whatsnew/changelog.html>\를 참조하십시오.

더 보기

PEP 429 – Python 3.4 출시 일정

요약 – 배포 주요 사항

새로운 문법 기능:

  • Python 3.4에서는 새로운 구문 기능이 추가되지 않았습니다.

다른 새로운 기능들:

새 라이브러리 모듈:

상당히 개선된 라이브러리 모듈:

  • functools`의 :ref:`Single-dispatch generic functions. ( PEP 443).

  • 새로운 pickle protocol 4 (PEP 3154).

  • multiprocessing`에는 Unix에서 os.fork 사용을 피할 있는 옵션이 생겼습니다 <whatsnew-multiprocessing-no-fork> (:issue:`8713).

  • email`에는 새로운 서브모듈인 :mod:`~email.contentmanager`와 새로운 :mod:`~email.message.Message 하위 클래스( EmailMessage)가 추가되어 MIME 처리 간소화 (bpo-18891)를 할 수 있습니다:

  • inspectpydoc 모듈은 이제 훨씬 더 다양한 호출 가능 객체를 올바르게 역직렬화할 수 있게 되어, 파이썬 help() 시스템의 출력을 향상시킵니다.

  • ipaddress 모듈 API가 안정 버전으로 선언되었습니다.

보안 개선 사항:

  • :ref:`안전하고 상호 교환 가능한 해시 알고리즘 <whatsnew-pep-456> (PEP 456).

  • 자식 프로세스로 파일 디스크립터를 누설하지 않으려면, 새로 생성된 파일 기술자를 상속 불가능 (PEP 446)으로 지정하십시오.

  • isolated mode <whatsnew-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.

  • Windows에서 multiprocessing 자식 프로세스는 더 이상 부모의 상속 가능한 핸들들을 모두 상속받지 않고, 필요한 핸들만 상속받습니다.

  • 새로운 hashlib.pbkdf2_hmac() 함수가 PKCS#5 암호 기반 키 파생 함수 2 <https://en.wikipedia.org/wiki/PBKDF2>\를 제공합니다.

  • ssl`에 대한 :ref:`TLSv1.1 TLSv1.2 지원.

  • ssl`에 대한 :ref:`Windows 시스템 인증서 저장소에서 인증서 검색 지원.

  • ssl`에 대한 :ref:`서버 SNI (Server Name Indication) 지원.

  • ssl.SSLContext 클래스는 :ref:`많은 개선 사항 <whatsnew34-sslcontext>`을 갖추었습니다.

  • SSL을 지원하는 표준 라이브러리의 모든 모듈이 이제 호스트 이름 일치(ssl.match_hostname()) 및 CRL(인증서 폐기 목록, ssl.SSLContext.load_verify_locations() 참조)을 포함하여 서버 인증서 검증을 지원합니다.

CPython implementation improvements:

사용자에게 노출되는 변경 사항, 다른 여러 작은 개선 사항, CPython 최적화, 비권장 사항(deprecations), 그리고 잠재적인 포팅 문제를 포함한 종합 목록을 계속 읽어보십시오.

새로운 기능들

PEP 453: Python 설치에서 PIP의 명시적 부트스트랩핑

기본적으로 pip 부트스트래핑

The new ensurepip module (defined in PEP 453) provides a standard cross-platform mechanism to bootstrap the pip installer into Python installations and virtual environments. The version of pip included with Python 3.4.0 is pip 1.5.4, and future 3.4.x maintenance releases will update the bundled version to the latest version of pip that is available at the time of creating the release candidate.

By default, the commands pipX and pipX.Y will be installed on all platforms (where X.Y stands for the version of the Python installation), along with the pip Python package and its dependencies. On Windows and in virtual environments on all platforms, the unversioned pip command will also be installed. On other platforms, the system wide unversioned pip command typically refers to the separately installed Python 2 version.

The pyvenv command line utility and the venv module make use of the ensurepip module to make pip readily available in virtual environments. When using the command line utility, pip is installed by default, while when using the venv module API installation of pip must be requested explicitly.

For CPython source builds on POSIX systems, the make install and make altinstall commands bootstrap pip by default. This behaviour can be controlled through configure options, and overridden through Makefile options.

On Windows and Mac OS X, the CPython installers now default to installing pip along with CPython itself (users may opt out of installing it during the installation process). Window users will need to opt in to the automatic PATH modifications to have pip available from the command line by default, otherwise it can still be accessed through the Python launcher for Windows as py -m pip.

As discussed in the PEP platform packagers may choose not to install these commands by default, as long as, when invoked, they provide clear and simple directions on how to install them on that platform (usually using the system package manager).

참고

To avoid conflicts between parallel Python 2 and Python 3 installations, only the versioned pip3 and pip3.4 commands are bootstrapped by default when ensurepip is invoked directly - the --default-pip option is needed to also request the unversioned pip command. pyvenv and the Windows installer ensure that the unqualified pip command is made available in those environments, and pip can always be invoked via the -m switch rather than directly to avoid ambiguity on systems with multiple Python installations.

Documentation Changes

As part of this change, the 파이썬 모듈 설치하기 and 파이썬 모듈 배포하기 sections of the documentation have been completely redesigned as short getting started and FAQ documents. Most packaging documentation has now been moved out to the Python Packaging Authority maintained Python Packaging User Guide and the documentation of the individual projects.

However, as this migration is currently still incomplete, the legacy versions of those guides remaining available as setuptools로 C와 C++ 확장 빌드하기 and setuptools로 C와 C++ 확장 빌드하기.

더 보기

PEP 453 – Explicit bootstrapping of pip in Python installations

PEP written by Donald Stufft and Nick Coghlan, implemented by Donald Stufft, Nick Coghlan, Martin von Löwis and Ned Deily.

PEP 446: Newly Created File Descriptors Are Non-Inheritable

PEP 446 makes newly created file descriptors non-inheritable. In general, this is the behavior an application will want: when launching a new process, having currently open files also open in the new process can lead to all sorts of hard to find bugs, and potentially to security issues.

However, there are occasions when inheritance is desired. To support these cases, the following new functions and methods are available:

더 보기

PEP 446 – Make newly created file descriptors non-inheritable

PEP written and implemented by Victor Stinner.

Improvements to Codec Handling

Since it was first introduced, the codecs module has always been intended to operate as a type-neutral dynamic encoding and decoding system. However, its close coupling with the Python text model, especially the type restricted convenience methods on the builtin str, bytes and bytearray types, has historically obscured that fact.

As a key step in clarifying the situation, the codecs.encode() and codecs.decode() convenience functions are now properly documented in Python 2.7, 3.3 and 3.4. These functions have existed in the codecs module (and have been covered by the regression test suite) since Python 2.4, but were previously only discoverable through runtime introspection.

Unlike the convenience methods on str, bytes and bytearray, the codecs convenience functions support arbitrary codecs in both Python 2 and Python 3, rather than being limited to Unicode text encodings (in Python 3) or basestring <-> basestring conversions (in Python 2).

In Python 3.4, the interpreter is able to identify the known non-text encodings provided in the standard library and direct users towards these general purpose convenience functions when appropriate:

>>> b"abcdef".decode("hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs

>>> "hello".encode("rot13")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'rot13' is not a text encoding; use codecs.encode() to handle arbitrary codecs

>>> open("foo.txt", encoding="hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'hex' is not a text encoding; use codecs.open() to handle arbitrary codecs

In a related change, whenever it is feasible without breaking backwards compatibility, exceptions raised during encoding and decoding operations are wrapped in a chained exception of the same type that mentions the name of the codec responsible for producing the error:

>>> import codecs

>>> codecs.decode(b"abcdefgh", "hex")
Traceback (most recent call last):
  File "/usr/lib/python3.4/encodings/hex_codec.py", line 20, in hex_decode
    return (binascii.a2b_hex(input), len(input))
binascii.Error: Non-hexadecimal digit found

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
binascii.Error: decoding with 'hex' codec failed (Error: Non-hexadecimal digit found)

>>> codecs.encode("hello", "bz2")
Traceback (most recent call last):
  File "/usr/lib/python3.4/encodings/bz2_codec.py", line 17, in bz2_encode
    return (bz2.compress(input), len(input))
  File "/usr/lib/python3.4/bz2.py", line 498, in compress
    return comp.compress(data) + comp.flush()
TypeError: 'str' does not support the buffer interface

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: encoding with 'bz2' codec failed (TypeError: 'str' does not support the buffer interface)

Finally, as the examples above show, these improvements have permitted the restoration of the convenience aliases for the non-Unicode codecs that were themselves restored in Python 3.2. This means that encoding binary data to and from its hexadecimal representation (for example) can now be written as:

>>> from codecs import encode, decode
>>> encode(b"hello", "hex")
b'68656c6c6f'
>>> decode(b"68656c6c6f", "hex")
b'hello'

The binary and text transforms provided in the standard library are detailed in 바이너리 변환 and 텍스트 변환.

(Contributed by Nick Coghlan in bpo-7475, bpo-17827, bpo-17828 and bpo-19619.)

PEP 451: A ModuleSpec Type for the Import System

PEP 451 provides an encapsulation of the information about a module that the import machinery will use to load it (that is, a module specification). This helps simplify both the import implementation and several import-related APIs. The change is also a stepping stone for several future import-related improvements.

The public-facing changes from the PEP are entirely backward-compatible. Furthermore, they should be transparent to everyone but importer authors. Key finder and loader methods have been deprecated, but they will continue working. New importers should use the new methods described in the PEP. Existing importers should be updated to implement the new methods. See the Deprecated section for a list of methods that should be replaced and their replacements.

Other Language Changes

Some smaller changes made to the core Python language are:

  • Unicode database updated to UCD version 6.3.

  • min() and max() now accept a default keyword-only argument that can be used to specify the value they return if the iterable they are evaluating has no elements. (Contributed by Julian Berman in bpo-18111.)

  • Module objects are now weakly referenceable.

  • Module __file__ attributes (and related values) should now always contain absolute paths by default, with the sole exception of __main__.__file__ when a script has been executed directly using a relative path. (Contributed by Brett Cannon in bpo-18416.)

  • All the UTF-* codecs (except UTF-7) now reject surrogates during both encoding and decoding unless the surrogatepass error handler is used, with the exception of the UTF-16 decoder (which accepts valid surrogate pairs) and the UTF-16 encoder (which produces them while encoding non-BMP characters). (Contributed by Victor Stinner, Kang-Hao (Kenny) Lu and Serhiy Storchaka in bpo-12892.)

  • New German EBCDIC codec cp273. (Contributed by Michael Bierenfeld and Andrew Kuchling in bpo-1097797.)

  • New Ukrainian codec cp1125. (Contributed by Serhiy Storchaka in bpo-19668.)

  • bytes.join() and bytearray.join() now accept arbitrary buffer objects as arguments. (Contributed by Antoine Pitrou in bpo-15958.)

  • The int constructor now accepts any object that has an __index__ method for its base argument. (Contributed by Mark Dickinson in bpo-16772.)

  • Frame objects now have a clear() method that clears all references to local variables from the frame. (Contributed by Antoine Pitrou in bpo-17934.)

  • memoryview is now registered as a Sequence, and supports the reversed() builtin. (Contributed by Nick Coghlan and Claudiu Popa in bpo-18690 and bpo-19078.)

  • Signatures reported by help() have been modified and improved in several cases as a result of the introduction of Argument Clinic and other changes to the inspect and pydoc modules.

  • __length_hint__() is now part of the formal language specification (see PEP 424). (Contributed by Armin Ronacher in bpo-16148.)

New Modules

asyncio

The new asyncio module (defined in PEP 3156) provides a standard pluggable event loop model for Python, providing solid asynchronous IO support in the standard library, and making it easier for other event loop implementations to interoperate with the standard library and each other.

For Python 3.4, this module is considered a provisional API.

더 보기

PEP 3156 – Asynchronous IO Support Rebooted: the “asyncio” Module

PEP written and implementation led by Guido van Rossum.

ensurepip

The new ensurepip module is the primary infrastructure for the PEP 453 implementation. In the normal course of events end users will not need to interact with this module, but it can be used to manually bootstrap pip if the automated bootstrapping into an installation or virtual environment was declined.

ensurepip includes a bundled copy of pip, up-to-date as of the first release candidate of the release of CPython with which it ships (this applies to both maintenance releases and feature releases). ensurepip does not access the internet. If the installation has internet access, after ensurepip is run the bundled pip can be used to upgrade pip to a more recent release than the bundled one. (Note that such an upgraded version of pip is considered to be a separately installed package and will not be removed if Python is uninstalled.)

The module is named ensurepip because if called when pip is already installed, it does nothing. It also has an --upgrade option that will cause it to install the bundled copy of pip if the existing installed version of pip is older than the bundled copy.

enum

The new enum module (defined in PEP 435) provides a standard implementation of enumeration types, allowing other modules (such as socket) to provide more informative error messages and better debugging support by replacing opaque integer constants with backwards compatible enumeration values.

더 보기

PEP 435 – Adding an Enum type to the Python standard library

PEP written by Barry Warsaw, Eli Bendersky and Ethan Furman, implemented by Ethan Furman.

pathlib

The new pathlib module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations.

For Python 3.4, this module is considered a provisional API.

더 보기

PEP 428 – The pathlib module – object-oriented filesystem paths

PEP written and implemented by Antoine Pitrou.

selectors

The new selectors module (created as part of implementing PEP 3156) allows high-level and efficient I/O multiplexing, built upon the select module primitives.

statistics

The new statistics module (defined in PEP 450) offers some core statistics functionality directly in the standard library. This module supports calculation of the mean, median, mode, variance and standard deviation of a data series.

더 보기

PEP 450 – Adding A Statistics Module To The Standard Library

PEP written and implemented by Steven D’Aprano

tracemalloc

The new tracemalloc module (defined in PEP 454) is a debug tool to trace memory blocks allocated by Python. It provides the following information:

  • Trace 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

더 보기

PEP 454 – Add a new tracemalloc module to trace Python memory allocations

PEP written and implemented by Victor Stinner

Improved Modules

abc

New function abc.get_cache_token() can be used to know when to invalidate caches that are affected by changes in the object graph. (Contributed by Łukasz Langa in bpo-16832.)

New class ABC has ABCMeta as its meta class. Using ABC as a base class has essentially the same effect as specifying metaclass=abc.ABCMeta, but is simpler to type and easier to read. (Contributed by Bruno Dupuis in bpo-16049.)

aifc

The getparams() method now returns a namedtuple rather than a plain tuple. (Contributed by Claudiu Popa in bpo-17818.)

aifc.open() now supports the context management protocol: when used in a with block, the close() method of the returned object will be called automatically at the end of the block. (Contributed by Serhiy Storchacha in bpo-16486.)

The writeframesraw() and writeframes() methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in bpo-8311.)

argparse

The FileType class now accepts encoding and errors arguments, which are passed through to open(). (Contributed by Lucas Maystre in bpo-11175.)

audioop

audioop now supports 24-bit samples. (Contributed by Serhiy Storchaka in bpo-12866.)

New byteswap() function converts big-endian samples to little-endian and vice versa. (Contributed by Serhiy Storchaka in bpo-19641.)

All audioop functions now accept any bytes-like object. Strings are not accepted: they didn’t work before, now they raise an error right away. (Contributed by Serhiy Storchaka in bpo-16685.)

base64

The encoding and decoding functions in base64 now accept any bytes-like object in cases where it previously required a bytes or bytearray instance. (Contributed by Nick Coghlan in bpo-17839.)

New functions a85encode(), a85decode(), b85encode(), and b85decode() provide the ability to encode and decode binary data from and to Ascii85 and the git/mercurial Base85 formats, respectively. The a85 functions have options that can be used to make them compatible with the variants of the Ascii85 encoding, including the Adobe variant. (Contributed by Martin Morrison, the Mercurial project, Serhiy Storchaka, and Antoine Pitrou in bpo-17618.)

collections

The ChainMap.new_child() method now accepts an m argument specifying the child map to add to the chain. This allows an existing mapping and/or a custom mapping type to be used for the child. (Contributed by Vinay Sajip in bpo-16613.)

colorsys

The number of digits in the coefficients for the RGB — YIQ conversions have been expanded so that they match the FCC NTSC versions. The change in results should be less than 1% and may better match results found elsewhere. (Contributed by Brian Landers and Serhiy Storchaka in bpo-14323.)

contextlib

The new contextlib.suppress context manager helps to clarify the intent of code that deliberately suppresses exceptions from a single statement. (Contributed by Raymond Hettinger in bpo-15806 and Zero Piraeus in bpo-19266.)

The new contextlib.redirect_stdout() context manager makes it easier for utility scripts to handle inflexible APIs that write their output to sys.stdout and don’t provide any options to redirect it. Using the context manager, the sys.stdout output can be redirected to any other stream or, in conjunction with io.StringIO, to a string. The latter can be especially useful, for example, to capture output from a function that was written to implement a command line interface. It is recommended only for utility scripts because it affects the global state of sys.stdout. (Contributed by Raymond Hettinger in bpo-15805.)

The contextlib documentation has also been updated to include a discussion of the differences between single use, reusable and reentrant context managers.

dbm

dbm.open() objects now support the context management protocol. When used in a with statement, the close method of the database object will be called automatically at the end of the block. (Contributed by Claudiu Popa and Nick Coghlan in bpo-19282.)

dis

Functions show_code(), dis(), distb(), and disassemble() now accept a keyword-only file argument that controls where they write their output.

The dis module is now built around an Instruction class that provides object oriented access to the details of each individual bytecode operation.

A new method, get_instructions(), provides an iterator that emits the Instruction stream for a given piece of Python code. Thus it is now possible to write a program that inspects and manipulates a bytecode object in ways different from those provided by the dis module itself. For example:

>>> import dis
>>> for instr in dis.get_instructions(lambda x: x + 1):
...     print(instr.opname)
LOAD_FAST
LOAD_CONST
BINARY_ADD
RETURN_VALUE

The various display tools in the dis module have been rewritten to use these new components.

In addition, a new application-friendly class Bytecode provides an object-oriented API for inspecting bytecode in both in human-readable form and for iterating over instructions. The Bytecode constructor takes the same arguments that get_instructions() does (plus an optional current_offset), and the resulting object can be iterated to produce Instruction objects. But it also has a dis method, equivalent to calling dis on the constructor argument, but returned as a multi-line string:

>>> bytecode = dis.Bytecode(lambda x: x + 1, current_offset=3)
>>> for instr in bytecode:
...     print('{} ({})'.format(instr.opname, instr.opcode))
LOAD_FAST (124)
LOAD_CONST (100)
BINARY_ADD (23)
RETURN_VALUE (83)
>>> bytecode.dis().splitlines()
['  1           0 LOAD_FAST                0 (x)',
 '      -->     3 LOAD_CONST               1 (1)',
 '              6 BINARY_ADD',
 '              7 RETURN_VALUE']

Bytecode also has a class method, from_traceback(), that provides the ability to manipulate a traceback (that is, print(Bytecode.from_traceback(tb).dis()) is equivalent to distb(tb)).

(Contributed by Nick Coghlan, Ryan Kelly and Thomas Kluyver in bpo-11816 and Claudiu Popa in bpo-17916.)

New function stack_effect() computes the effect on the Python stack of a given opcode and argument, information that is not otherwise available. (Contributed by Larry Hastings in bpo-19722.)

doctest

A new option flag, FAIL_FAST, halts test running as soon as the first failure is detected. (Contributed by R. David Murray and Daniel Urban in bpo-16522.)

The doctest command line interface now uses argparse, and has two new options, -o and -f. -o allows doctest options to be specified on the command line, and -f is a shorthand for -o FAIL_FAST (to parallel the similar option supported by the unittest CLI). (Contributed by R. David Murray in bpo-11390.)

doctest will now find doctests in extension module __doc__ strings. (Contributed by Zachary Ware in bpo-3158.)

email

as_string() now accepts a policy argument to override the default policy of the message when generating a string representation of it. This means that as_string can now be used in more circumstances, instead of having to create and use a generator in order to pass formatting parameters to its flatten method. (Contributed by R. David Murray in bpo-18600.)

New method as_bytes() added to produce a bytes representation of the message in a fashion similar to how as_string produces a string representation. It does not accept the maxheaderlen argument, but does accept the unixfrom and policy arguments. The Message __bytes__() method calls it, meaning that bytes(mymsg) will now produce the intuitive result: a bytes object containing the fully formatted message. (Contributed by R. David Murray in bpo-18600.)

The Message.set_param() message now accepts a replace keyword argument. When specified, the associated header will be updated without changing its location in the list of headers. For backward compatibility, the default is False. (Contributed by R. David Murray in bpo-18891.)

A pair of new subclasses of Message have been added (EmailMessage and MIMEPart), along with a new sub-module, contentmanager and a new policy attribute content_manager. All documentation is currently in the new module, which is being added as part of email’s new provisional API. These classes provide a number of new methods that make extracting content from and inserting content into email messages much easier. For details, see the contentmanager documentation and the email: 예제. These API additions complete the bulk of the work that was planned as part of the email6 project. The currently provisional API is scheduled to become final in Python 3.5 (possibly with a few minor additions in the area of error handling). (Contributed by R. David Murray in bpo-18891.)

filecmp

A new clear_cache() function provides the ability to clear the filecmp comparison cache, which uses os.stat() information to determine if the file has changed since the last compare. This can be used, for example, if the file might have been changed and re-checked in less time than the resolution of a particular filesystem’s file modification time field. (Contributed by Mark Levitt in bpo-18149.)

New module attribute DEFAULT_IGNORES provides the list of directories that are used as the default value for the ignore parameter of the dircmp() function. (Contributed by Eli Bendersky in bpo-15442.)

functools

The new partialmethod() descriptor brings partial argument application to descriptors, just as partial() provides for normal callables. The new descriptor also makes it easier to get arbitrary callables (including partial() instances) to behave like normal instance methods when included in a class definition. (Contributed by Alon Horev and Nick Coghlan in bpo-4331.)

The new @~functools.singledispatch decorator brings support for single-dispatch generic functions to the Python standard library. Where object oriented programming focuses on grouping multiple operations on a common set of data into a class, a generic function focuses on grouping multiple implementations of an operation that allows it to work with different kinds of data.

더 보기

PEP 443 – Single-dispatch generic functions

PEP written and implemented by Łukasz Langa.

@~functools.total_ordering now supports a return value of NotImplemented from the underlying comparison function. (Contributed by Katie Miller in bpo-10042.)

A pure-python version of the partial() function is now in the stdlib; in CPython it is overridden by the C accelerated version, but it is available for other implementations to use. (Contributed by Brian Thorne in bpo-12428.)

gc

New function get_stats() returns a list of three per-generation dictionaries containing the collections statistics since interpreter startup. (Contributed by Antoine Pitrou in bpo-16351.)

glob

A new function escape() provides a way to escape special characters in a filename so that they do not become part of the globbing expansion but are instead matched literally. (Contributed by Serhiy Storchaka in bpo-8402.)

hashlib

A new hashlib.pbkdf2_hmac() function provides the PKCS#5 password-based key derivation function 2. (Contributed by Christian Heimes in bpo-18582.)

The name attribute of hashlib hash objects is now a formally supported interface. It has always existed in CPython’s hashlib (although it did not return lower case names for all supported hashes), but it was not a public interface and so some other Python implementations have not previously supported it. (Contributed by Jason R. Coombs in bpo-18532.)

hmac

hmac now accepts bytearray as well as bytes for the key argument to the new() function, and the msg parameter to both the new() function and the update() method now accepts any type supported by the hashlib module. (Contributed by Jonas Borgström in bpo-18240.)

The digestmod argument to the hmac.new() function may now be any hash digest name recognized by hashlib. In addition, the current behavior in which the value of digestmod defaults to MD5 is deprecated: in a future version of Python there will be no default value. (Contributed by Christian Heimes in bpo-17276.)

With the addition of block_size and name attributes (and the formal documentation of the digest_size attribute), the hmac module now conforms fully to the PEP 247 API. (Contributed by Christian Heimes in bpo-18775.)

html

New function unescape() function converts HTML5 character references to the corresponding Unicode characters. (Contributed by Ezio Melotti in bpo-2927.)

HTMLParser accepts a new keyword argument convert_charrefs that, when True, automatically converts all character references. For backward-compatibility, its value defaults to False, but it will change to True in a future version of Python, so you are invited to set it explicitly and update your code to use this new feature. (Contributed by Ezio Melotti in bpo-13633.)

The strict argument of HTMLParser is now deprecated. (Contributed by Ezio Melotti in bpo-15114.)

http

send_error() now accepts an optional additional explain parameter which can be used to provide an extended error description, overriding the hardcoded default if there is one. This extended error description will be formatted using the error_message_format attribute and sent as the body of the error response. (Contributed by Karl Cow in bpo-12921.)

The http.server command line interface now has a -b/--bind option that causes the server to listen on a specific address. (Contributed by Malte Swart in bpo-17764.)

idlelib and IDLE

Since idlelib implements the IDLE shell and editor and is not intended for import by other programs, it gets improvements with every release. See Lib/idlelib/NEWS.txt for a cumulative list of changes since 3.3.0, as well as changes made in future 3.4.x releases. This file is also available from the IDLE Help ‣ About IDLE dialog.

importlib

The InspectLoader ABC defines a new method, source_to_code() that accepts source data and a path and returns a code object. The default implementation is equivalent to compile(data, path, 'exec', dont_inherit=True). (Contributed by Eric Snow and Brett Cannon in bpo-15627.)

InspectLoader also now has a default implementation for the get_code() method. However, it will normally be desirable to override the default implementation for performance reasons. (Contributed by Brett Cannon in bpo-18072.)

The reload() function has been moved from imp to importlib as part of the imp module deprecation. (Contributed by Berker Peksag in bpo-18193.)

importlib.util now has a MAGIC_NUMBER attribute providing access to the bytecode version number. This replaces the get_magic() function in the deprecated imp module. (Contributed by Brett Cannon in bpo-18192.)

New importlib.util functions cache_from_source() and source_from_cache() replace the same-named functions in the deprecated imp module. (Contributed by Brett Cannon in bpo-18194.)

The importlib bootstrap NamespaceLoader now conforms to the InspectLoader ABC, which means that runpy and python -m can now be used with namespace packages. (Contributed by Brett Cannon in bpo-18058.)

importlib.util has a new function decode_source() that decodes source from bytes using universal newline processing. This is useful for implementing InspectLoader.get_source() methods.

importlib.machinery.ExtensionFileLoader now has a get_filename() method. This was inadvertently omitted in the original implementation. (Contributed by Eric Snow in bpo-19152.)

inspect

The inspect module now offers a basic command line interface to quickly display source code and other information for modules, classes and functions. (Contributed by Claudiu Popa and Nick Coghlan in bpo-18626.)

unwrap() makes it easy to unravel wrapper function chains created by @functools.wraps (and any other API that sets the __wrapped__ attribute on a wrapper function). (Contributed by Daniel Urban, Aaron Iles and Nick Coghlan in bpo-13266.)

As part of the implementation of the new enum module, the inspect module now has substantially better support for custom __dir__ methods and dynamic class attributes provided through metaclasses. (Contributed by Ethan Furman in bpo-18929 and bpo-19030.)

getfullargspec() and getargspec() now use the signature() API. This allows them to support a much broader range of callables, including those with __signature__ attributes, those with metadata provided by argument clinic, functools.partial() objects and more. Note that, unlike signature(), these functions still ignore __wrapped__ attributes, and report the already bound first argument for bound methods, so it is still necessary to update your code to use signature() directly if those features are desired. (Contributed by Yury Selivanov in bpo-17481.)

signature() now supports duck types of CPython functions, which adds support for functions compiled with Cython. (Contributed by Stefan Behnel and Yury Selivanov in bpo-17159.)

ipaddress

ipaddress was added to the standard library in Python 3.3 as a provisional API. With the release of Python 3.4, this qualification has been removed: ipaddress is now considered a stable API, covered by the normal standard library requirements to maintain backwards compatibility.

A new is_global property is True if an address is globally routeable. (Contributed by Peter Moody in bpo-17400.)

logging

The TimedRotatingFileHandler has a new atTime parameter that can be used to specify the time of day when rollover should happen. (Contributed by Ronald Oussoren in bpo-9556.)

SocketHandler and DatagramHandler now support Unix domain sockets (by setting port to None). (Contributed by Vinay Sajip in commit ce46195b56a9.)

fileConfig() now accepts a configparser.RawConfigParser subclass instance for the fname parameter. This facilitates using a configuration file when logging configuration is just a part of the overall application configuration, or where the application modifies the configuration before passing it to fileConfig(). (Contributed by Vinay Sajip in bpo-16110.)

Logging configuration data received from a socket via the logging.config.listen() function can now be validated before being processed by supplying a verification function as the argument to the new verify keyword argument. (Contributed by Vinay Sajip in bpo-15452.)

marshal

The default marshal version has been bumped to 3. The code implementing the new version restores the Python2 behavior of recording only one copy of interned strings and preserving the interning on deserialization, and extends this “one copy” ability to any object type (including handling recursive references). This reduces both the size of .pyc files and the amount of memory a module occupies in memory when it is loaded from a .pyc (or .pyo) file. (Contributed by Kristján Valur Jónsson in bpo-16475, with additional speedups by Antoine Pitrou in bpo-19219.)

mmap

mmap objects are now weakly referenceable. (Contributed by Valerie Lambert in bpo-4885.)

multiprocessing

On Unix two new start methods, spawn and forkserver, have been added for starting processes using multiprocessing. These make the mixing of processes with threads more robust, and the spawn method matches the semantics that multiprocessing has always used on Windows. New function get_all_start_methods() reports all start methods available on the platform, get_start_method() reports the current start method, and set_start_method() sets the start method. (Contributed by Richard Oudkerk in bpo-8713.)

multiprocessing also now has the concept of a context, which determines how child processes are created. New function get_context() returns a context that uses a specified start method. It has the same API as the multiprocessing module itself, so you can use it to create Pools and other objects that will operate within that context. This allows a framework and an application or different parts of the same application to use multiprocessing without interfering with each other. (Contributed by Richard Oudkerk in bpo-18999.)

Except when using the old fork start method, child processes no longer inherit unneeded handles/file descriptors from their parents (part of bpo-8713).

multiprocessing now relies on runpy (which implements the -m switch) to initialise __main__ appropriately in child processes when using the spawn or forkserver start methods. This resolves some edge cases where combining multiprocessing, the -m command line switch, and explicit relative imports could cause obscure failures in child processes. (Contributed by Nick Coghlan in bpo-19946.)

operator

New function length_hint() provides an implementation of the specification for how the __length_hint__() special method should be used, as part of the PEP 424 formal specification of this language feature. (Contributed by Armin Ronacher in bpo-16148.)

There is now a pure-python version of the operator module available for reference and for use by alternate implementations of Python. (Contributed by Zachary Ware in bpo-16694.)

os

There are new functions to get and set the inheritable flag of a file descriptor (os.get_inheritable(), os.set_inheritable()) or a Windows handle (os.get_handle_inheritable(), os.set_handle_inheritable()).

New function cpu_count() reports the number of CPUs available on the platform on which Python is running (or None if the count can’t be determined). The multiprocessing.cpu_count() function is now implemented in terms of this function). (Contributed by Trent Nelson, Yogesh Chaudhari, Victor Stinner, and Charles-François Natali in bpo-17914.)

os.path.samestat() is now available on the Windows platform (and the os.path.samefile() implementation is now shared between Unix and Windows). (Contributed by Brian Curtin in bpo-11939.)

os.path.ismount() now recognizes volumes mounted below a drive root on Windows. (Contributed by Tim Golden in bpo-9035.)

os.open() supports two new flags on platforms that provide them, O_PATH (un-opened file descriptor), and O_TMPFILE (unnamed temporary file; as of 3.4.0 release available only on Linux systems with a kernel version of 3.11 or newer that have uapi headers). (Contributed by Christian Heimes in bpo-18673 and Benjamin Peterson, respectively.)

pdb

pdb has been enhanced to handle generators, yield, and yield from in a more useful fashion. This is especially helpful when debugging asyncio based programs. (Contributed by Andrew Svetlov and Xavier de Gaye in bpo-16596.)

The print command has been removed from pdb, restoring access to the Python print() function from the pdb command line. Python2’s pdb did not have a print command; instead, entering print executed the print statement. In Python3 print was mistakenly made an alias for the pdb p command. p, however, prints the repr of its argument, not the str like the Python2 print command did. Worse, the Python3 pdb print command shadowed the Python3 print function, making it inaccessible at the pdb prompt. (Contributed by Connor Osborn in bpo-18764.)

pickle

pickle now supports (but does not use by default) a new pickle protocol, protocol 4. This new protocol addresses a number of issues that were present in previous protocols, such as the serialization of nested classes, very large strings and containers, and classes whose __new__() method takes keyword-only arguments. It also provides some efficiency improvements.

더 보기

PEP 3154 – Pickle protocol 4

PEP written by Antoine Pitrou and implemented by Alexandre Vassalotti.

plistlib

plistlib now has an API that is similar to the standard pattern for stdlib serialization protocols, with new load(), dump(), loads(), and dumps() functions. (The older API is now deprecated.) In addition to the already supported XML plist format (FMT_XML), it also now supports the binary plist format (FMT_BINARY). (Contributed by Ronald Oussoren and others in bpo-14455.)

poplib

Two new methods have been added to poplib: capa(), which returns the list of capabilities advertised by the POP server, and stls(), which switches a clear-text POP3 session into an encrypted POP3 session if the POP server supports it. (Contributed by Lorenzo Catucci in bpo-4473.)

pprint

The pprint module’s PrettyPrinter class and its pformat(), and pprint() functions have a new option, compact, that controls how the output is formatted. Currently setting compact to True means that sequences will be printed with as many sequence elements as will fit within width on each (indented) line. (Contributed by Serhiy Storchaka in bpo-19132.)

Long strings are now wrapped using Python’s normal line continuation syntax. (Contributed by Antoine Pitrou in bpo-17150.)

pty

pty.spawn() now returns the status value from os.waitpid() on the child process, instead of None. (Contributed by Gregory P. Smith.)

pydoc

The pydoc module is now based directly on the inspect.signature() introspection API, allowing it to provide signature information for a wider variety of callable objects. This change also means that __wrapped__ attributes are now taken into account when displaying help information. (Contributed by Larry Hastings in bpo-19674.)

The pydoc module no longer displays the self parameter for already bound methods. Instead, it aims to always display the exact current signature of the supplied callable. (Contributed by Larry Hastings in bpo-20710.)

In addition to the changes that have been made to pydoc directly, its handling of custom __dir__ methods and various descriptor behaviours has also been improved substantially by the underlying changes in the inspect module.

As the help() builtin is based on pydoc, the above changes also affect the behaviour of help().

re

New fullmatch() function and Pattern.fullmatch() method anchor the pattern at both ends of the string to match. This provides a way to be explicit about the goal of the match, which avoids a class of subtle bugs where $ characters get lost during code changes or the addition of alternatives to an existing regular expression. (Contributed by Matthew Barnett in bpo-16203.)

The repr of regex objects now includes the pattern and the flags; the repr of match objects now includes the start, end, and the part of the string that matched. (Contributed by Hugo Lopes Tavares and Serhiy Storchaka in bpo-13592 and bpo-17087.)

resource

New prlimit() function, available on Linux platforms with a kernel version of 2.6.36 or later and glibc of 2.13 or later, provides the ability to query or set the resource limits for processes other than the one making the call. (Contributed by Christian Heimes in bpo-16595.)

On Linux kernel version 2.6.36 or later, there are also some new Linux specific constants: RLIMIT_MSGQUEUE, RLIMIT_NICE, RLIMIT_RTPRIO, RLIMIT_RTTIME, and RLIMIT_SIGPENDING. (Contributed by Christian Heimes in bpo-19324.)

On FreeBSD version 9 and later, there some new FreeBSD specific constants: RLIMIT_SBSIZE, RLIMIT_SWAP, and RLIMIT_NPTS. (Contributed by Claudiu Popa in bpo-19343.)

select

epoll objects now support the context management protocol. When used in a with statement, the close() method will be called automatically at the end of the block. (Contributed by Serhiy Storchaka in bpo-16488.)

devpoll objects now have fileno() and close() methods, as well as a new attribute closed. (Contributed by Victor Stinner in bpo-18794.)

shelve

Shelf instances may now be used in with statements, and will be automatically closed at the end of the with block. (Contributed by Filip Gruszczyński in bpo-13896.)

shutil

copyfile() now raises a specific Error subclass, SameFileError, when the source and destination are the same file, which allows an application to take appropriate action on this specific error. (Contributed by Atsuo Ishimoto and Hynek Schlawack in bpo-1492704.)

smtpd

The SMTPServer and SMTPChannel classes now accept a map keyword argument which, if specified, is passed in to asynchat.async_chat as its map argument. This allows an application to avoid affecting the global socket map. (Contributed by Vinay Sajip in bpo-11959.)

smtplib

SMTPException is now a subclass of OSError, which allows both socket level errors and SMTP protocol level errors to be caught in one try/except statement by code that only cares whether or not an error occurred. (Contributed by Ned Jackson Lovely in bpo-2118.)

socket

The socket module now supports the CAN_BCM protocol on platforms that support it. (Contributed by Brian Thorne in bpo-15359.)

Socket objects have new methods to get or set their inheritable flag, get_inheritable() and set_inheritable().

The socket.AF_* and socket.SOCK_* constants are now enumeration values using the new enum module. This allows meaningful names to be printed during debugging, instead of integer “magic numbers”.

The AF_LINK constant is now available on BSD and OSX.

inet_pton() and inet_ntop() are now supported on Windows. (Contributed by Atsuo Ishimoto in bpo-7171.)

sqlite3

A new boolean parameter to the connect() function, uri, can be used to indicate that the database parameter is a uri (see the SQLite URI documentation). (Contributed by poq in bpo-13773.)

ssl

PROTOCOL_TLSv1_1 and PROTOCOL_TLSv1_2 (TLSv1.1 and TLSv1.2 support) have been added; support for these protocols is only available if Python is linked with OpenSSL 1.0.1 or later. (Contributed by Michele Orrù and Antoine Pitrou in bpo-16692.)

New function create_default_context() provides a standard way to obtain an SSLContext whose settings are intended to be a reasonable balance between compatibility and security. These settings are more stringent than the defaults provided by the SSLContext constructor, and may be adjusted in the future, without prior deprecation, if best-practice security requirements change. The new recommended best practice for using stdlib libraries that support SSL is to use create_default_context() to obtain an SSLContext object, modify it if needed, and then pass it as the context argument of the appropriate stdlib API. (Contributed by Christian Heimes in bpo-19689.)

SSLContext method load_verify_locations() accepts a new optional argument cadata, which can be used to provide PEM or DER encoded certificates directly via strings or bytes, respectively. (Contributed by Christian Heimes in bpo-18138.)

New function get_default_verify_paths() returns a named tuple of the paths and environment variables that the set_default_verify_paths() method uses to set OpenSSL’s default cafile and capath. This can be an aid in debugging default verification issues. (Contributed by Christian Heimes in bpo-18143.)

SSLContext has a new method, cert_store_stats(), that reports the number of loaded X.509 certs, X.509 CA certs, and certificate revocation lists (crls), as well as a get_ca_certs() method that returns a list of the loaded CA certificates. (Contributed by Christian Heimes in bpo-18147.)

If OpenSSL 0.9.8 or later is available, SSLContext has a new attribute verify_flags that can be used to control the certificate verification process by setting it to some combination of the new constants VERIFY_DEFAULT, VERIFY_CRL_CHECK_LEAF, VERIFY_CRL_CHECK_CHAIN, or VERIFY_X509_STRICT. OpenSSL does not do any CRL verification by default. (Contributed by Christien Heimes in bpo-8813.)

새로운 SSLContext 메서드 이는 클라이언트가 서버를 검증하는 사용할 TLS 서버 인증서(``purpose=`()SERVER_AUTH)와 서버가 클라이언트 인증서를 확인하는 데 사용할 인증서 모두를 로드하는 데 사용될 수 있습니다. (기여자: Christian Heimes bpo-19292.)

두 개의 새로운 windows 전용 함수인 (기여자: Christian Heimes :issue:`17134().)

새로운 ssl.SSLContext.set_servername_callback() 메서드를 사용하여 서버 측 SNI(Server Name Indication)를 지원합니다. (기여자: Daniel Black bpo-8109.)

SSLSocket.getpeercert`가 반환하는 딕셔너리는 추가적인 ``X509v3`() 확장 항목인 crlDistributionPoints, calIssuersOCSP URI를 포함합니다. (기여자: Christian Heimes bpo-18379.)

통계

stat 모듈은 이제 레거시 C 구현인 _stat`에 의해 지원됩니다. 대부분의 값이 표준화되어 있지 않고 플랫폼 의존적이기 때문에 C 구현이 필요합니다. (기여자: Christian Heimes :issue:`11016.)

모듈은 새로운 ST_MODE 플래그, S_IFDOOR, S_IFPORT, 그리고 (기여자: Christian Hiemes :issue:`11016.)

구조체

새로운 함수 iter_unpack 메서드는 주어진 형식이 반복되는 데이터를 포함하는 버퍼를 스트리밍 방식으로 언팩합니다. (기여자: Antoine Pitrou bpo-17804.)

서브프로세스

check_output`은 이제 *input* 인자를 받아 실행하는 명령어의 ``stdin`() 내용을 제공하는 데 사용할 수 있습니다. (기여자: Zack Weinberg bpo-16624.)

(기여자: Tim Golden :issue:`10197().)

sunau

getparams() 메서드는 이제 단순 튜플이 아닌 이름 지정 튜플을 반환합니다. (기여자: Claudiu Popa bpo-18901.)

sunau.open`은 이제 컨텍스트 관리 프로토콜을 지원하여, :keyword:`with() 블록에서 사용될 때 반환된 객체의 close 메서드가 블록 끝에서 자동으로 호출됩니다. (기여자: Serhiy Storchaka bpo-18878.)

AU_write.setsampwidth`는 이제 24비트 샘플을 지원하여, 모듈을 사용하여 24 샘플을 쓰는 것이 가능해졌습니다. (기여자: Serhiy Storchaka :issue:`19261().)

The writeframesraw() and writeframes() methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in bpo-8311.)

sys 모듈

새 함수 sys.getallocatedblocks`는 인터프리터가 할당한 현재 블록 수를 반환합니다. (기본 `()–with-pymalloc`` 설정의 CPython에서, 이는 PyObject_Malloc() API를 통해 할당된 할당량을 의미합니다.) 이 기능은 메모리 누수를 추적하는 데 유용할 수 있으며, 특히 테스트 스위트를 통해 자동화할 경우 더욱 그렇습니다. (기여자: Antoine Pitrou bpo-13390.)

Python 인터프리터가 대화형 모드 <tut-interactive>`로 시작할 때, :mod:`sys 모듈에서 __interactivehook__ 속성을 확인합니다. 이 속성이 존재하는 경우, 대화형 모드가 시작되기 직전에 인자 없이 그 값이 호출됩니다. 이 확인은 PYTHONSTARTUP 파일이 읽힌 후에 이루어지므로, 여기에서 설정할 수 있습니다. site 모듈은 플랫폼이 readline`을 지원하는 경우 완성 히스토리 저장(파일: `~/.python-history)을 활성화하는 함수로 이를 <rlcompleter-config> 설정을 합니다. 이 새로운 동작을 원하지 않으면, PYTHONSTARTUP, sitecustomize, 또는 usercustomize`에서 속성을 삭제하거나(:mod:`sys`를 대상으로) 다른 호출 가능한 값으로 재정의할 있습니다. (기여자: Éric Araujo Antoine Pitrou :issue:`5845.)

타르파일

tarfile 모듈은 이제 스크립트로 직접 호출하거나 -m 옵션을 통해 간단한 :ref:`tarfile-commandline`을 지원합니다. 를 사용하여 tar 아카이브를 생성하고 추출할 수 있습니다. (Berker Peksag님이 :issue:`13477`에서 기여함.)

textwrap

TextWrapper 클래스는 두 가지 새로운 속성/생성자 인수를 가집니다. ]`)로 끝납니다. (Antoine Pitrou와 Serhiy Storchaka가 bpo-18585 및 :issue:`18725`에서 기여함.)

threading

메인 스레드를 나타내는 Thread 객체는 새로운 main_thread() 함수에서 얻을 수 있습니다. 정상적인 조건에서 이 것은 파이썬 인터프리터가 시작된 스레드입니다. (Andrew Svetlov님이 :issue:`18882`에서 기여함.)

추적(Traceback)

새로운 traceback.clear_frames() 함수는 트레이스백 객체를 받아서 참조하는 모든 프레임의 로컬 변수를 지워 사용되는 메모리 양을 감소시킵니다. (Andrew Kuchling님이 :issue:`1565525`에서 기여함.)

types

새로운 DynamicClassAttribute() 데스크립터는 인스턴스 객체를 통해 조회될 때는 정상적으로 작동하고, 클래스를 통해 조회될 때는 class __getattr__ 로 라우팅되는 속성을 정의하는 방법을 제공합니다. 이를 통해 클래스에서 활성화된 프로퍼티를 가짐과 동시에, 클래스에 같은 이름의 가상 어트리뷰트를 가질 수 있습니다 (예제는 enum 을 참조하십시오). (Ethan Furman님이 bpo-19030 에서 기여함.)

urllib

urllib.request`는 이제 :class:`~urllib.request.DataHandler 클래스를 통해 data: URL을 지원합니다. (Mathias Panzenböck님이 :issue:`16423`에서 기여함.)

Request 클래스에 사용될 HTTP 메서드는 이제 서브클래스의 method 클래스 속성을 설정하여 지정할 수 있습니다. (Jason R Coombs님이 :issue:`18978`에서 기여함.)

Request 객체는 이제 재사용이 가능합니다. full_url 또는 data 속성이 수정되면, 모든 관련 내부 속성들이 업데이트됩니다. 이것은 예를 들어, 서로 다른 data 인수를 가진 여러 개의 OpenerDirector.open() 호출에서 동일한 Request 객체를 사용하거나, 처음부터 다시 계산하는 대신 Request ‘s url 을 수정할 수 있게 되었음을 의미합니다. 또한 Request 에서 헤더를 제거하는 데 사용될 수 있는 새로운 remove_header() 메서드도 있습니다. (Alexey Kachayev가 bpo-16464, Daniel Wozniak이 bpo-17485, 그리고 Damien Brecht와 Senthil Kumaran이 bpo-17272 에서 기여함.)

HTTPError 객체는 이제 오류와 관련된 HTTP 응답 헤더에 접근할 수 있는 headers 속성을 가집니다. (Berker Peksag님이 :issue:`15701`에서 기여함.)

unittest`

TestCase 클래스는 새로운 메서드인 subTest`를 갖게 되었으며, 메서드는 컨텍스트 관리자를 생성하여 :keyword:`with() 블록을 “sub-test”로 만듭니다. 이 컨텍스트 관리자는 예를 들어 반복문 내부에서 subTest 컨텍스트 관리자를 호출함으로써 테스트 메서드가 서브테스트를 동적으로 생성할 수 있게 합니다. 따라서 단일 테스트 메서드를 통해 개별적으로 식별되고 개별적으로 계산되는 무한한 수의 테스트가 생성될 수 있으며, 이들 중 하나 또는 여러개가 실패하더라도 모두 실행됩니다. 예를 들면:

class NumbersTest(unittest.TestCase):
    def test_even(self):
        for i in range(6):
            with self.subTest(i=i):
                self.assertEqual(i % 2, 0)

i'' 변수와 특정 값을 가진 레이블로 식별되는 6개의 서브 테스트가 포함될 것입니다 (예: ``i=0, i=1 등). 전체 버전은 서브테스트 <subtests>`를 참조하십시오. (Antoine Pitrou가 처리함, :issue:`16997.)

unittest.main`은 이제 이전에는 문자열로 단일 테스트 이름만 허용했던 것과 달리 *defaultTest*의 테스트 이름 이터러블을 허용합니다. (Jyrki Pulliainen가 처리함, :issue:`15132().)

테스트 검색 과정에서 (Zach Ware가 처리함, :issue:`16935.)

(Martin Melin Jeff Ramnani가 처리함, :issue:`16709().)

TestSuite 서브클래스를 생성하여 사용자 정의 _removeTestAtIndex 메서드를 정의함으로써 이 동작을 재정의하는 것이 가능합니다. (Tom Wardill, Matt McClure, 및 Andrew Svetlov가 처리함, bpo-11798.)

새 테스트 주장 컨텍스트 관리자 assertLogs`는 주어진 코드 블록이 :mod:`logging() 모듈을 사용하여 로그 메시지를 방출하도록 보장합니다. 기본적으로 이 메시지는 모든 로거에서 나올 수 있으며 INFO 이상의 우선순위를 가질 수 있지만, 로거 이름과 대체 최소 로깅 수준을 모두 지정할 수 있습니다. 컨텍스트 관리자가 반환하는 객체는 기록된 (Antoine Pitrou가 처리함, :issue:`18937.)

테스트 검색은 이제 네임스페이스 패키지(Namespace package)와 함께 작동합니다 (Claudiu Popa가 처리함, bpo-17457.)

unittest.mock 객체는 호출을 일치시킬 때 이제 사양 시그니처를 검사하며, 이는 인수가 위치로만 아니라 이름으로도 매칭될 수 있음을 의미합니다. (Antoine Pitrou가 처리함, bpo-17015.)

mock_open() 객체는 이제 readlinereadlines 메서드를 가집니다. (Toshio Kuratomi가 처리함, bpo-17467.)

venv`

venv`는 이제 ``csh`fish 셸에 대한 활성화 스크립트를 포함합니다. (Andrew Svetlov가 처리함, bpo-15417.)

EnvBuildercreate() 편의 함수는 새로운 키워드 인자 with_pip 를 받습니다. 이 인자는 기본값으로 False 이며, 가상 환경에 pip 이 설치되도록 EnvBuilder 가 보장하는지 여부를 제어합니다. (Nick Coghlan가 처리함, bpo-19552 로, PEP 453 구현의 일부.)

wave

getparams() 메서드는 더 이상 일반 튜플이 아닌 namedtuple을 반환합니다. (Claudiu Popa가 처리함, bpo-17487.)

wave.open`은 컨텍스트 관리 프로토콜을 지원하게 되었습니다. (Claudiu Popa가 처리함, :issue:`17616().)

wave`는 이제 :ref:`탐색 불가능한 파일에 결과를 쓰기 <wave-write-objects>`을 있습니다. (David Jones, Guilherme Polo, Serhiy Storchaka가 처리함, :issue:`5202.)

writeframes() 메서드는 이제 모든 bytes-like object`을 허용합니다. (Serhiy Storchaka가 처리함, :issue:`8311.)

weakref

새로운 WeakMethod 클래스는 연결된 메서드에 대한 약한 참조를 시뮬레이션합니다. (Antoine Pitrou가 처리함, bpo-14631.)

새로운 finalize 클래스는 객체가 가비지 수집될 때 호출되도록 콜백을 등록하는 것이 가능하며, 자체 약한 참조의 라이프사이클 관리를 세심하게 할 필요가 없습니다. (Richard Oudkerk가 처리함, bpo-15528.)

__callback__ 속성을 통해 노출됩니다. (Mark Dickinson가 처리함, bpo-17643.)

xml.etree

새로운 파서인 :class:`~xml.etree.ElementTree.XMLPullParser`는 비차단 애플리케이션이 XML 문서를 구문 분석할 수 있게 합니다. 예시는 :ref:`elementtree-pull-parsing`에서 확인할 수 있습니다. (Antoine Pitrou가 :issue:`17741`에서 기여했습니다.)

xml.etree.ElementTree`의 :func:`~xml.etree.ElementTree.tostringtostringlist() 함수, 그리고 write`는 이제 *short_empty_elements* :ref:`키워드 전용 매개 변수 <keyword-only_parameter>`를 갖추게 되어, 내용이 없는 요소가 축약된 형식(``<tag />`)으로 작성될지 확장된 형식(<tag></tag>)으로 작성될지를 제어할 수 있습니다. (Ariel Poliak와 Serhiy Storchaka가 :issue:`14377`에서 기여했습니다.)

zipfile`

writepy 메서드에는 새로운 filterfunc 옵션이 추가되어, 아카이브에 어떤 디렉토리와 파일이 추가될지 제어하는 데 사용됩니다. 예를 들어, 이 기능은 테스트 파일을 아카이브에서 제외하는 데 사용할 수 있습니다. (Christian Tismer가 :issue:`19274`에서 기여했습니다.)

ZipFilePyZipFileallowZip64 매개 변수가 기본값으로 True 가 되었습니다. (William Mallard가 bpo-17201 에서 기여했습니다.)

CPython 구현 변경 사항

PEP 445: CPython 메모리 할당자 사용자 정의 방식

:pep:`445`는 CPython 인터프리터의 메모리 할당을 사용자 정의하기 위한 새로운 C 레벨 인터페이스를 추가합니다.

더 보기

PEP 445 – 파이썬 메모리 할당자를 사용자 정의하기 위한 새 API 추가

PEP written and implemented by Victor Stinner.

PEP 442: 안전한 객체 최종화

PEP 442 는 CPython에서 객체 최종화의 현재 제한 사항과 특이점을 제거합니다. 이를 통해 __del__() 메서드를 가진 객체와 finally 절을 가진 제너레이터가 참조 순환에 포함될 때 최종화될 수 있습니다.

이번 변경의 일부로, 모듈 전역 변수는 대부분의 경우 더 이상 인터프리터 종료 시 강제로 None`으로 설정되지 않으며, 대신 순환 가비지 컬렉터의 정상 작동에 의존합니다. 이는 파이썬에서 순환 GC가 처음 도입된 이래 문제를 일으키던 `__del__` 메서드와 관련된 일련의 인터프리터 종료 시간 오류를 방지합니다.

더 보기

PEP 442 – 안전한 객체 최종화

PEP written and implemented by Antoine Pitrou.

PEP 456: 안전하고 상호 교환 가능한 해시 알고리즘

:pep:`456`은 파이썬의 해시 알고리즘에 대한 이전 보안 수정 작업(Public-facing API가 딕셔너리 조회를 백킹하는 특정 DOS 공격을 해결하기 위한)을 기반으로 합니다. (현재 개선 주기의 시작은 :issue:`14621`을 참조하십시오.) 이 PEP는 CPython의 해시 코드를 통합하여 패키징 프로그램이 다른 해시 알고리즘으로 대체하기 쉽게 만들고, 파이썬의 기본 구현은 64비트 데이터 타입을 갖는 플랫폼에서 SipHash 구현으로 전환합니다. 이전 FNV 알고리즘과의 성능 차이는 미미합니다.

해당 PEP는 sys.hash_info 이름 지정 튜플에 추가 필드를 추가하여 현재 실행 중인 바이너리가 사용하는 해시 알고리즘을 설명합니다. 그 외에는, 이 PEP가 기존 CPython API를 변경하는 것은 없습니다.

PEP 436: Argument Clinic

“Argument Clinic” (PEP 436)은 이제 CPython 빌드 프로세스의 일부이며, C로 구현된 builtins 및 표준 라이브러리 확장 모듈의 정확한 시그니처를 정의하고 유지 관리하는 과정을 단순화하는 데 사용될 수 있습니다.

일부 표준 라이브러리 확장 모듈은 Python 3.4에서 Argument Clinic을 사용하도록 변환되었으며, :mod:`pydoc`과 :mod:`inspect`도 이에 맞게 업데이트되었습니다.

프로그래밍적 검사를 위한 시그니처 메타데이터는 Python 3.4 유지보수 릴리스의 일부로 C에서 구현된 추가 호출 가능한 객체에 추가될 것으로 예상됩니다.

참고

Argument Clinic PEP는 구현 상태를 완전히 따라가지 못하고 있습니다. 이는 Argument Clinic이 Python 3.4의 서드파티 공개 API로 제공되지 않을 것이므로, 릴리스 관리자와 핵심 개발팀에 의해 허용된 것으로 간주되었습니다.

더 보기

PEP 436 – Argument Clinic DSL

Larry Hastings가 작성하고 구현한 PEP.

기타 빌드 및 C API 변경 사항

  • PyType_GetSlot() 함수가 안정적인 ABI에 추가되어, 제한된 API를 사용할 때 이름이 지정된 타입 슬롯에서 함수 포인터를 검색할 수 있게 되었습니다. (Martin von Löwis가 bpo-17162 에서 기여했습니다.)

  • Py_SetStandardStreamEncoding() 프리-초기화 API는 CPython 인터프리터를 임베딩하는 애플리케이션이 표준 스트림에 대한 특정 인코딩과 오류 처리기를 신뢰성 있게 강제할 수 있도록 합니다. (Bastien Montagne와 Nick Coghlan가 bpo-16129 에서 기여했습니다.)

  • 문자열 인수를 변경하지 않는 대부분의 Python C API가 이제 char * 대신 const char * 로 정확하게 표시되었습니다. (Serhiy Storchaka가 bpo-1772673 에서 기여했습니다.)

  • 더 이상 파이썬 인터프리터가 사용 가능한 경우에도 사용할 수 있는 새로운 셸 버전의 python-config 가 있습니다 (예를 들어, 크로스 컴파일 시나리오에서).

  • PyUnicode_FromFormat() 이 이제 %s, %A, %U, %V, %S, 및 %R 에 대한 너비 및 정밀도 사양을 지원합니다. (Ysj Ray와 Victor Stinner가 bpo-7330 에서 기여했습니다.)

  • 새 함수 PyStructSequence_InitType2() 는 기존의 PyStructSequence_InitType() 함수를 보완합니다. 차이점은 성공 시 0 을, 실패 시 -1 을 반환한다는 것입니다.

  • CPython 소스 코드를 이제 최신 버전의 GCC와 clang의 주소 무결성 검사 기능을 사용하여 컴파일할 수 있게 되었으며, 작은 객체 할당자에서 발생하던 오탐이 제거되었습니다. (Dhiru Kholia가 bpo-18596 에서 기여했습니다.)

  • The Windows build now uses Address Space Layout Randomization and Data Execution Prevention. (Contributed by Christian Heimes in bpo-16632.)

  • 새 함수 PyObject_LengthHint()operator.length_hint() 의 C API 에퀴벌런트입니다. (Armin Ronacher가 bpo-16148 에서 기여했습니다.)

기타 개선 사항

  • The python command has a new option, -I, which causes it to run in “isolated mode”, which means that sys.path contains neither the script’s directory nor the user’s site-packages directory, and all PYTHON* environment variables are ignored (it implies both -s and -E). Other restrictions may also be applied in the future, with the goal being to isolate the execution of a script from the user’s environment. This is appropriate, for example, when Python is used to run a system script. On most POSIX systems it can and should be used in the #! line of system scripts. (Contributed by Christian Heimes in bpo-16499.)

  • Tab 완성 기능이 readline`을 지원하는 시스템의 대화형 인터프리터에서 기본적으로 활성화되었습니다. 히스토리도 기본적으로 활성화되며, 파일 :file:`~/.python-history 에 기록되고(및 읽힙니다). (Antoine Pitrou와 Éric Araujo가 bpo-5845 에서 기여했습니다.)

  • 이제 파이썬 인터프리터를 --version 으로 호출하면 표준 에러 대신 표준 출력으로 버전을 출력합니다 (bpo-18338). 유사한 변경 사항이 argparse (bpo-18920) 및 다른 스크립트 같은 호출 기능을 가진 모듈에도 적용되었습니다 (bpo-18922).

  • CPython Windows 설치관리자는 이제 확장 기능이 등록될 때 .py``를 :envvar:`PATHEXT` 변수에 추가하여, 사용자가 명령어 프롬프트에서 ``.py 확장자 없이 이름만으로 파이썬 스크립트를 실행할 수 있게 합니다. (Paul Moore가 bpo-18569 에서 기여했습니다.)

  • make 타겟 coverage-report 는 파이썬을 빌드하고, 테스트 스위트를 실행하며, gcovlcov 를 사용하여 C 코드베이스에 대한 HTML 커버리지 보고서를 생성합니다.

  • python regression test suite 에 추가된 -R 옵션은 이제 sys.getallocatedblocks() 를 사용하여 메모리 할당 누수도 검사합니다. (Antoine Pitrou가 bpo-13390 에서 기여했습니다.)

  • python -m 이 이제 이름 공간 패키지에서 작동합니다.

  • The stat module is now implemented in C, which means it gets the values for its constants from the C header files, instead of having the values hard-coded in the python module as was previously the case.

  • Loading multiple python modules from a single OS module (.so, .dll) now works correctly (previously it silently returned the first python module in the file). (Contributed by Václav Šmilauer in bpo-16421.)

  • A new opcode, LOAD_CLASSDEREF, has been added to fix a bug in the loading of free variables in class bodies that could be triggered by certain uses of __prepare__. (Contributed by Benjamin Peterson in bpo-17853.)

  • A number of MemoryError-related crashes were identified and fixed by Victor Stinner using his PEP 445-based pyfailmalloc tool (bpo-18408, bpo-18520).

  • The pyvenv command now accepts a --copies option to use copies rather than symlinks even on systems where symlinks are the default. (Contributed by Vinay Sajip in bpo-18807.)

  • The pyvenv command also accepts a --without-pip option to suppress the otherwise-automatic bootstrapping of pip into the virtual environment. (Contributed by Nick Coghlan in bpo-19552 as part of the PEP 453 implementation.)

  • The encoding name is now optional in the value set for the PYTHONIOENCODING environment variable. This makes it possible to set just the error handler, without changing the default encoding. (Contributed by Serhiy Storchaka in bpo-18818.)

  • The bz2, lzma, and gzip module open functions now support x (exclusive creation) mode. (Contributed by Tim Heaney and Vajrasky Kok in bpo-19201, bpo-19222, and bpo-19223.)

Significant Optimizations

  • The UTF-32 decoder is now 3x to 4x faster. (Contributed by Serhiy Storchaka in bpo-14625.)

  • The cost of hash collisions for sets is now reduced. Each hash table probe now checks a series of consecutive, adjacent key/hash pairs before continuing to make random probes through the hash table. This exploits cache locality to make collision resolution less expensive. The collision resolution scheme can be described as a hybrid of linear probing and open addressing. The number of additional linear probes defaults to nine. This can be changed at compile-time by defining LINEAR_PROBES to be any value. Set LINEAR_PROBES=0 to turn-off linear probing entirely. (Contributed by Raymond Hettinger in bpo-18771.)

  • The interpreter starts about 30% faster. A couple of measures lead to the speedup. The interpreter loads fewer modules on startup, e.g. the re, collections and locale modules and their dependencies are no longer imported by default. The marshal module has been improved to load compiled Python code faster. (Contributed by Antoine Pitrou, Christian Heimes and Victor Stinner in bpo-19219, bpo-19218, bpo-19209, bpo-19205 and bpo-9548.)

  • bz2.BZ2File is now as fast or faster than the Python2 version for most cases. lzma.LZMAFile has also been optimized. (Contributed by Serhiy Storchaka and Nadeem Vawda in bpo-16034.)

  • random.getrandbits() is 20%-40% faster for small integers (the most common use case). (Contributed by Serhiy Storchaka in bpo-16674.)

  • By taking advantage of the new storage format for strings, pickling of strings is now significantly faster. (Contributed by Victor Stinner and Antoine Pitrou in bpo-15596.)

  • A performance issue in io.FileIO.readall() has been solved. This particularly affects Windows, and significantly speeds up the case of piping significant amounts of data through subprocess. (Contributed by Richard Oudkerk in bpo-15758.)

  • html.escape() is now 10x faster. (Contributed by Matt Bryant in bpo-18020.)

  • On Windows, the native VirtualAlloc is now used instead of the CRT malloc in obmalloc. Artificial benchmarks show about a 3% memory savings.

  • os.urandom() now uses a lazily opened persistent file descriptor so as to avoid using many file descriptors when run in parallel from multiple threads. (Contributed by Antoine Pitrou in bpo-18756.)

Deprecated

This section covers various APIs and other features that have been deprecated in Python 3.4, and will be removed in Python 3.5 or later. In most (but not all) cases, using the deprecated APIs will produce a DeprecationWarning when the interpreter is run with deprecation warnings enabled (for example, by using -Wd).

Deprecations in the Python API

  • As mentioned in PEP 451: A ModuleSpec Type for the Import System, a number of importlib methods and functions are deprecated: importlib.find_loader() is replaced by importlib.util.find_spec(); importlib.machinery.PathFinder.find_module() is replaced by importlib.machinery.PathFinder.find_spec(); importlib.abc.MetaPathFinder.find_module() is replaced by importlib.abc.MetaPathFinder.find_spec(); importlib.abc.PathEntryFinder.find_loader() and find_module() are replaced by importlib.abc.PathEntryFinder.find_spec(); all of the xxxLoader ABC load_module methods (importlib.abc.Loader.load_module, importlib.abc.InspectLoader.load_module, importlib.abc.FileLoader.load_module, importlib.abc.SourceLoader.load_module) should no longer be implemented, instead loaders should implement an exec_module method (importlib.abc.Loader.exec_module(), importlib.abc.InspectLoader.exec_module() importlib.abc.SourceLoader.exec_module()) and let the import system take care of the rest; and importlib.abc.Loader.module_repr(), importlib.util.module_for_loader(), importlib.util.set_loader(), and importlib.util.set_package() are no longer needed because their functions are now handled automatically by the import system.

  • The imp module is pending deprecation. To keep compatibility with Python 2/3 code bases, the module’s removal is currently not scheduled.

  • The formatter module is pending deprecation and is slated for removal in Python 3.6.

  • MD5 as the default digestmod for the hmac.new() function is deprecated. Python 3.6 will require an explicit digest name or constructor as digestmod argument.

  • The internal Netrc class in the ftplib module has been documented as deprecated in its docstring for quite some time. It now emits a DeprecationWarning and will be removed completely in Python 3.5.

  • The undocumented endtime argument to subprocess.Popen.wait() should not have been exposed and is hopefully not in use; it is deprecated and will mostly likely be removed in Python 3.5.

  • The strict argument of HTMLParser is deprecated.

  • The plistlib readPlist(), writePlist(), readPlistFromBytes(), and writePlistToBytes() functions are deprecated in favor of the corresponding new functions load(), dump(), loads(), and dumps(). Data() is deprecated in favor of just using the bytes constructor.

  • The sysconfig key SO is deprecated, it has been replaced by EXT_SUFFIX.

  • The U mode accepted by various open functions is deprecated. In Python3 it does not do anything useful, and should be replaced by appropriate uses of io.TextIOWrapper (if needed) and its newline argument.

  • The parser argument of xml.etree.ElementTree.iterparse() has been deprecated, as has the html argument of XMLParser(). To prepare for the removal of the latter, all arguments to XMLParser should be passed by keyword.

Deprecated Features

  • Running IDLE — 파이썬 편집기와 셸 with the -n flag (no subprocess) is deprecated. However, the feature will not be removed until bpo-18823 is resolved.

  • The site module adding a “site-python” directory to sys.path, if it exists, is deprecated (bpo-19375).

Removed

Operating Systems No Longer Supported

다음 운영 체제에 대한 지원이 소스 및 빌드 도구에서 제거되었습니다:

  • OS/2 (bpo-16135).

  • Windows 2000 (changeset e52df05b496a).

  • COMSPEC`이 `command.com`을 가리키는 Windows 시스템 (:issue:`14470).

  • VMS (bpo-16136).

API 및 기능 제거

다음의 더 이상 사용되지 않거나 이전에 지원 중단된 API 및 기능들이 제거되었습니다:

  • 유지보수되지 않는 Misc/TextMateMisc/vim 디렉토리가 제거되었습니다 (대신 사용할 수 있는 것에 대한 제안은 devguide 를 참조하십시오).

  • SO makefile 매크로가 제거되었습니다 (이는 SHLIB_SUFFIXEXT_SUFFIX 매크로로 대체되었습니다) (bpo-16754).

  • PyThreadState.tick_counter 필드가 제거되었습니다; 이 값은 “새로운 GIL”이 도입된 Python 3.2 이후로 무의미했습니다 (bpo-19199).

  • PyLoader and PyPycLoader have been removed from importlib. (Contributed by Taras Lyapun in bpo-15641.)

  • The strict argument to HTTPConnection and HTTPSConnection has been removed. HTTP 0.9-style “Simple Responses” are no longer supported.

  • 더 이상 사용되지 않는 urllib.request.Request 접근자 및 설정자 메서드 add_data, has_data, get_data, get_type, get_host, get_selector, set_proxy, get_origin_req_host, 및 `is_unverifiable`가 제거되었습니다 (대신 직접 속성 접근을 사용하십시오).

  • marshal`에서 이상 사용되지 않는 ``TYPE_INT64` 로드를 지원하지 않습니다. (Dan Riti가 :issue:`15480`에서 기여했습니다.)

  • inspect.Signature: positional-only parameters are now required to have a valid name.

  • object.__format__`은 이상 비어 있지 않은 포맷 문자열을 허용하지 않으며, 대신 :exc:`TypeError`를 발생시킵니다. 비어 있지 않은 문자열을 사용하는 것은 Python 3.2부터 지원 중단되었습니다. 변경은 이전에 작동했지만(잘못된) 코드가 객체가 `__format__() 메서드를 갖게 될 경우 실패하기 시작하는 상황을 방지하기 위해 이루어졌으며, 이는 객체가 핸들링하지 않는 포맷 코드로 인해 귀하의 코드가 이제 :exc:`TypeError`를 발생시킬 수 있음을 의미합니다. 배경은 :issue:`7994`를 참조하십시오.

  • difflib.SequenceMatcher.isbjunk() and difflib.SequenceMatcher.isbpopular() were deprecated in 3.2, and have now been removed: use x in sm.bjunk and x in sm.bpopular, where sm is a SequenceMatcher object (bpo-13248).

코드 정리

  • 내부 Scanner 클래스가 pydoc 모듈에서 제거되었습니다. 이 클래스는 사용되지 않으며 문서화되어 있지 않았습니다.

  • 사적이며 사실상 사용되지 않는 _gestalt 모듈과, 오직 심하게 손상된 OSX 시스템에서만 호출되었을 platform 의 사적인 함수인 _mac_ver_lookup, _mac_ver_gstalt, 및 _bcd2str 이 함께 제거되었습니다 (문제는 bpo-18393 를 참조하십시오).

  • tarfile 모듈 네임스페이스에 포함되었던 특정 stat 상수들의 하드코딩된 복사본이 제거되었습니다.

Python 3.4로 이식하기

이 섹션에서는 이전에 설명한 변경 사항과 코드를 수정해야 할 수도 있는 기타 버그 수정을 나열합니다.

‘python’ 명령어 동작의 변경 사항

  • posix 셸에서 PATH 환경 변수를 빈 값으로 설정하는 것은 기본적으로 아무것도 설정하지 않는 것과 동일합니다. 그러나 PYTHONPATH`를 값으로 설정하는 것이 그렇게 등가이지는 않았습니다. :envvar:`PYTHONPATH`를 값으로 설정하는 것은 `.`` 으로 설정하는 것과 등가했으며, 이는 :envvar:`PATH`가 작동하는 방식에 대한 유추를 할 때 혼란을 야기했습니다. 이제 동작은 :envvar:`PATH`의 posix 규칙을 따릅니다.

  • CPython 인터프리터의 디버그 (--with-pydebug) 빌드에서 “[X refs, Y blocks]” 출력이 기본적으로 비활성화되었습니다. -X showrefcount 옵션을 사용하여 다시 활성화할 수 있습니다. (Ezio Melotti가 :issue:`17323`에서 기여했습니다.)

  • python 명령어와 대부분의 표준 라이브러리 스크립트(그리고 argparse)는 이제 stderr 대신 stdout``에 ``--version 정보를 출력합니다 (이슈 목록은 위 :ref:`other-improvements-3.4`를 참조하십시오).

Python API의 변경 사항

  • `:mod:`importlib.abc`에 정의된 ABC들은 이제 임의로 :exc:`NotImplementedError`를 발생시키는 대신 해당 적절한 예외를 발생시키거나 기본값을 반환합니다. 이는 `:func:`super`를 호출하고 궁극적으로 ABC까지 도달하는 코드에만 영향을 미칩니다. 호환성을 위해 필요한 경우 :exc:`NotImplementedError`와 적절한 두 예외 모두를 포착하십시오.

  • 모듈 유형은 이제 가급적 기본적으로 __package____loader__ 속성을 None 으로 초기화합니다. 이 속성들이 하위 호환 방식으로 설정되었는지 확인하려면 등. getattr(module, '__loader__', None) is not None 을 사용하십시오. (bpo-17115).

  • importlib.util.module_for_loader`는 리로딩을 적절하게 지원하기 위해 ``__loader__``와 ``__package__``를 무조건 설정합니다. 이것이 원치 않는 경우, 속성들을 직접 수동으로 설정해야 합니다. 모듈 관리를 위해서는 :func:()!importlib.util.module_to_load`를 사용하실 수 있습니다.

  • 재로딩 시 임포트는 관련 속성들(예: __name__, __loader__, __package__, __file__, __cached__)을 무조건 재설정합니다. 이는 모듈이 다시 로드될 때 다시 발견됨을 의미하며 (bpo-19413), 3.3 이전의 동작을 복원한 것임을 유의하십시오.

  • 동결(Frozen) 패키지는 더 이상 패키지 이름을 포함하는 리스트로 __path__ 를 설정하지 않고, 빈 리스트로 설정합니다. 이전 동작은 동결된 패키지와 동일한 이름의 디렉터리가 있는 경우 서브모듈 가져오기 시 임포트 시스템이 잘못 작동하게 만들 수 있었습니다. 모듈이 패키지인지 아닌지를 판단하는 올바른 방법은 hasattr(module, '__path__') 를 사용하는 것입니다 (bpo-18065).

  • 동결 모듈은 더 이상 __file__ 속성을 정의하지 않습니다. 동결 모듈이 명시적인 위치에서 로드되는 것이 아니므로, 이 속성을 설정하는 것은 의미적으로 잘못입니다. 만약 모듈이 동결된 코드로부터 왔는지 알아야 한다면, 모듈의 __spec__.location'frozen' 으로 설정되어 있는지 확인하거나, 로더가 importlib.machinery.FrozenImporter 의 서브클래스인지 확인하십시오. 또는 Python 2 호환성이 필요한 경우 imp.is_frozen() 를 사용할 수 있습니다.

  • :func:`py_compile.compile`는 이제 파일을 쓸 경로가 심링크이거나 일반 파일이 아닌 경우 :exc:`FileExistsError`를 발생시킵니다. 이는 가져오기(import) 과정에서 해당 파일들이 원래 어떤 유형의 파일 경로였든지 관계없이 일반 파일로 덮어씌워진다는 경고 역할을 합니다.

  • :meth:`importlib.abc.SourceLoader.get_source`는 로드되는 소스 코드가 :exc:`SyntaxError`나 :exc:`UnicodeDecodeError`를 유발할 때 더 이상 :exc:`ImportError`를 발생시키지 않습니다. :exc:`ImportError`는 소스 코드를 찾을 수 없을 때만 발생하는 것이 원칙이지만, 소스 코드는 발견되었으나 형식이 올바르지 않을 때 해당 의미가 너무 광범위하게 적용된다고 판단되었기 때문입니다. 이전에는 ImportError를 포착했지만, 구문 오류나 디코딩 문제는 계속 무시하고 싶다면 이제 세 가지 예외 모두를 포착하십시오.

  • functools.update_wrapper`와 :deco:`functools.wraps`는 이제 해당 함수가 ``__wrapped__`() 속성을 가지고 있더라도 올바르게 감싸진(wrapping) 함수에 __wrapped__ 속성을 설정합니다. 이는 __wrapped__ 속성이 체인 내의 모든 것을 내부 함수를 가리키기보다는, 장식된 함수의 스택을 정확하게 연결한다는 의미입니다. 이전 동작이 의도적이라고 가정했던 introspection 라이브러리는 inspect.unwrap`를 사용하여 ``__wrapped__`() 속성이 없는 체인의 첫 번째 함수에 접근할 수 있습니다.

  • inspect.getfullargspec`는 이제 :func:`inspect.signature() 위에 재구현되었기 때문에 과거보다 훨씬 더 광범위한 사용 가능 객체(callable objects)를 처리합니다. Python 3.4 시리즈 전반에 걸쳐 추가적인 내장 및 확장 모듈 호출 가능한 것들이 시그니처 메타데이터를 얻을 것으로 예상됩니다. :func:`inspect.getfullargspec`이 비-Python 호출 가능 객체에서 실패할 것이라고 가정하는 코드는 그에 맞게 조정해야 할 수 있습니다.

  • :class:`importlib.machinery.PathFinder`가 이제 빈 문자열에 대해 현재 작업 디렉터리를 :data:`sys.path_hooks`의 객체들에 전달합니다. 이로 인해 :data:`sys.path_importer_cache`는 `’’ 절대 포함하지 않게 되어, :data:`sys.path`를 기반으로 :data:`sys.path_importer_cache`를 반복할 모든 키를 찾지 못하게 됩니다. 또한 인터프리터에서 ``-m``을 사용할 때(스크립트를 상대 경로로 직접 실행하는 경우의 ``__main__.__file__ 제외) 현재 작업 디렉터리에서 가져온 모듈의 __file__ 역시 절대 경로를 가지게 되었습니다 (Brett Cannon in bpo-18416 기여). 명령줄에 지정된 정보가 있습니다 (bpo-18416).`

  • :class:`~http.client.HTTPConnection`과 `:class:`~http.client.HTTPSConnection`에 대한 *strict* 인자를 제거함에 따라, 키워드가 아닌 위치 기반으로 지정할 경우 남아 있는 인수들의 의미가 변경됩니다. 비사용 신호(deprecation warnings)에 주의를 기울여 왔다면 이미 추가적인 모든 인수는 키워드를 통해 지정하고 있어야 합니다.

  • from __future__ import ... 구문 사이에 있는 문자열은 이제 항상 SyntaxError`를 발생시킵니다. 이전에는 선행 docstring이 없었을 경우, 개입된 문자열이 때때로 무시되곤 했습니다. 이는 CPython을 언어 사양에 맞게 만들었습니다. Jython과 PyPy는 이미 그러했습니다. (:issue:`17434).`

  • ssl.SSLSocket.getpeercert()ssl.SSLSocket.do_handshake() 는 이제 SSLSocket 이 연결되어 있지 않을 때 이전의 AttributeError 발생 대신 ENOTCONN 을 가진 OSError 를 발생시킵니다. 또한, getpeercert() 는 핸드셰이크가 아직 수행되지 않은 경우 ValueError 를 발생시킬 것입니다.`

  • base64.b32decode() now raises a binascii.Error when the input string contains non-b32-alphabet characters, instead of a TypeError. This particular TypeError was missed when the other TypeErrors were converted. (Contributed by Serhiy Storchaka in bpo-18011.) Note: this change was also inadvertently applied in Python 3.3.3.

  • file 속성은 이제 생성하는 cgi.FieldStorage 인스턴스가 가비지 컬렉션되면 자동으로 닫힙니다. 만약 파일 객체를 cgi.FieldStorage 인스턴스에서 별도로 가져오고 그 인스턴스를 살아있게 유지하지 않았다면, 전체 cgi.FieldStorage 인스턴스를 저장하거나 cgi.FieldStorage 인스턴스가 가비지 컬렉트되기 전에 파일의 내용을 읽어야 합니다.`

  • 닫힌 SSL 소켓에 대해 read 또는 write 를 호출하면 이전의 더 불가사의한 AttributeError 대신 정보가 담긴 ValueError 를 발생시킵니다 (bpo-9177).`

  • slice.indices() no longer produces an OverflowError for huge values. As a consequence of this fix, slice.indices() now raises a ValueError if given a negative length; previously it returned nonsense values (bpo-14794).

  • complex 생성자는, :mod:`cmath 함수들과 달리 객체의 __complex__ 특수 메서드가 float 값을 반환하는 경우 이를 잘못 허용했습니다. 이는 이제 TypeError`를 발생시킵니다 (:issue:`16290).`

  • 3.2 버전과 3.3 버전의 int 생성자는 base 파라미터로 float 값을 잘못 허용합니다. 이 기능을 사용하고 있는 사람이 있을 가능성은 낮지만, 그렇다면 이제 TypeError`가 발생할 것입니다 (:issue:`16772).`

  • 키워드 전용 인자의 기본값은 이전의 버그가 있는 동작에 의존하는 코드를 작성한 사람이 없기를 바랍니다 (bpo-16967), 이제 일반 키워드 인자의 기본값이 평가된 에 평가됩니다.

  • fork() 이후에는 오래된 스레드 상태가 이제 지워집니다. 이로 인해 이전에 잘못 영구적으로 유지되던 일부 시스템 리소스(예를 들어, 스레드 로컬 스토리지의 데이터베이스 연결)가 해제될 수 있습니다. (bpo-17094).`

  • __annotations__ 딕셔너리의 매개변수 이름이 이제 (Yury Selivanov in :issue:`20625 기여).`

  • hashlib.hash.name`은 이제 항상 식별자를 소문자로 반환합니다. 이전에 일부 내장 해시는 대문자 이름을 가졌었지만, 현재 공식 공개 인터페이스가 되었기 때문에 명명 규칙이 일관되게 변경되었습니다 (:issue:`18532).

  • Because unittest.TestSuite now drops references to tests after they are run, test harnesses that reuse a TestSuite to re-run a set of tests may fail. Test suites should not be re-used in this fashion since it means state is retained between test runs, breaking the test isolation that unittest is designed to provide. However, if the lack of isolation is considered acceptable, the old behavior can be restored by creating a TestSuite subclass that defines a _removeTestAtIndex method that does nothing (see TestSuite.__iter__()) (bpo-11798).

  • :mod:`unittest`는 이제 명령줄 구문 분석을 위해 :mod:`argparse`를 사용합니다. 이전에 작동했지만 더 이상 허용되지 않는 특정 유효하지 않은 명령어 형식이 있습니다. 이론적으로 이는 금지된 명령어 형식이 아무런 의미가 없었으며 사용될 가능성이 낮으므로 하위 호환성 문제를 일으키지 않아야 합니다.

  • re.split(), re.findall(), 및 re.sub() 함수와 match 객체의 group()groups() 메서드는 이제 일치시키려는 문자열이 바이트 같은 객체 인 경우 항상 bytes 객체를 반환합니다. 이전에는 반환 유형이 입력 유형과 일치했으므로, 만약 코드가 반환 값이 예를 들어 bytearray 일 것이라고 의존하고 있었다면 코드를 변경해야 합니다.

  • audioop 함수는 이제 문자열 입력을 받으면 나중에 무작위로 실패하는 대신 즉시 오류를 발생시킵니다 (bpo-16685).

  • HTMLParser 호출에 적절한 값을 가진 이 키워드를 추가하는 것을 권장합니다 (bpo-13633).

  • hmac.new() 함수에 대한 digestmod 인자가 미래에는 기본값이 없게 될 것이므로, 모든 hmac.new() 호출은 명시적으로 digestmod 를 지정하도록 변경해야 합니다 (bpo-17276).

  • SO 키를 사용하여 sysconfig.get_config_var() 를 호출하거나, sysconfig.get_config_vars() 호출 결과에서 SO 를 찾는 것은 더 이상 사용되지 않습니다(deprecated). 이 키는 컨텍스트에 따라 EXT_SUFFIX 또는 SHLIB_SUFFIX 로 대체해야 합니다 (bpo-19555).

  • U 를 지정하는 모든 open 함수 호출은 수정되어야 합니다. U 는 Python3에서 비효율적이며 궁극적으로 사용될 경우 오류가 발생할 것입니다. 함수에 따라, newline 인수를 사용하거나 필요한 경우 스트림을 TextIOWrapper 로 래핑하여 그 newline 인수를 사용하는 방식으로 이전 Python2 동작의 등가 기능을 구현할 수 있습니다 (bpo-15204).

  • 스크립트에서 pyvenv 를 사용하고 pip가 설치되지 않기를 원한다면, 명령어 호출에 --without-pip 를 추가해야 합니다.

  • 들여쓰기가 지정될 때 json.dump`와 :func:`json.dumps`의 기본 동작이 변경되었습니다: 이상 끝에서 쉼표로 구분된 항목 뒤에 후행 공백을 생성하지 않습니다. 이는 그러한 출력에 대한 공백 민감 비교를 수행하는 테스트가 있는 경우에만 관련이 있습니다 (:issue:`16333()).

  • doctest`는 이제 확장 모듈 ``__doc__` 문자열에서 doctest를 찾으므로, 만약 사용자의 doctest 테스트 발견에 그 안에 doctest처럼 보이는 것이 있는 확장 모듈이 포함되어 있다면 테스트 실행 시 이전에 보지 못했던 테스트 실패를 볼 수 있습니다 (bpo-3158).

  • collections.abc 모듈은 Python 시작 개선의 일부로 약간 리팩터링되었습니다. 그 결과, collections`을 임포트하는 것이 자동으로 :mod:`collections.abc`를 임포트하게 되는 것은 아닙니다. 만약 사용자의 프로그램이 (문서화되지 않은) 암시적 임포트에 의존했다면 명시적인 ``import collections.abc``를 추가해야 합니다 (:issue:`20784).

C API 변경 사항

  • PyEval_EvalFrameEx(), PyObject_Repr(), 그리고 PyObject_Str() 등 다른 내부 C API들도 이제 활성 예외를 조용히 폐기할 수 있는 상황에서 사용되지 않도록 보장하는 디버깅 어설션(assertion)을 포함합니다. 활성 예외를 폐기하는 것이 기대되고 원하는 경우 (예를 들어, PyErr_Fetch() 로 로컬에 이미 저장되었거나 다른 예외로 의도적으로 대체되는 경우), 이 작업을 호출하거나 간접적으로 실행하는 동안 어설션이 트리거되는 것을 방지하려면 명시적인 PyErr_Clear() 호출이 필요합니다.

  • PyErr_SetImportError() 는 이제 msg 인자가 설정되지 않았을 때 TypeError 를 설정합니다. 이전에는 예외가 설정되지 않은 경우 NULL 만 반환되었습니다.

  • PyOS_ReadlineFunctionPointer 콜백의 결과는 이제 PyMem_RawMalloc() 이나 PyMem_RawRealloc() 으로 할당된 문자열이거나, 오류가 발생한 경우 NULL 이어야 합니다. 이전에는 PyMem_Malloc() 이나 PyMem_Realloc() 으로 할당된 문자열이었기 때문입니다 (bpo-16742).

  • PyThread_set_key_value() 는 이제 항상 값을 설정합니다. Python 3.3에서는 키가 이미 존재하면 아무것도 하지 않았습니다 (현재 값이 NULL 이 아닌 포인터일 경우).

  • PyFrameObject 구조체의 f_tstate (스레드 상태) 필드가 버그를 수정하기 위해 제거되었습니다. 근거는 :issue:`14432`를 참조하십시오.

3.4.3 버전에서 변경됨

PEP 476: 표준 라이브러리 http 클라이언트에 기본적으로 인증서 검증 기능을 활성화하는 방법

http.client 및 이를 사용하는 urllib.request`와 :mod:`xmlrpc.client 같은 모듈들은 이제 서버가 플랫폼 신뢰 저장소에서 서명된 인증서를 제시하고 그 호스트 이름이 요청하는 호스트 이름과 일치하는지 기본적으로 검증함으로써, 많은 애플리케이션의 보안을 크게 향상시켰습니다.

기존 동작이 필요한 애플리케이션은 대체 컨텍스트를 전달할 수 있습니다:

import urllib.request
import ssl

# 이 코드는 모든 검증을 비활성화합니다.
context = ssl._create_unverified_context()

# 이는 호스트에 대한 특정 인증서 사용을 허용하며, 신뢰 저장소에 있을 필요가 없습니다.
context = ssl.create_default_context(cafile="/path/to/file.crt")

urllib.request.urlopen("https://invalid-cert", context=context)

분실물 보관소