파이썬 3.7의 새로운 변경사항

2023년 05월 06일

Python

# 파이썬# 3.7

📕 목차

개요

이 글은 파이썬 3.7 버전의 새로운 변경사항을 소개합니다.

파이썬 3.7 배포 주요 사항

파이썬 3.7 버전은 2018년 6월 28일에 릴리즈 되었습니다.

PEP 563: Postponed Evaluation of Annotations

파이썬에 타입 힌트가 도입되면서 어노테이션 기능과 관련해서 크게 두 가지 문제가 발견되었습니다. (PEP 3107, PEP 526)

  • 어노테이션은은 현재 스코프 내에서 정의된 이름만 사용할 수 있습니다. 달리말해, 정방향 참조를 할 수 없습니다.
  • 소스 코드에 어노테이션을 다는 것은 파이썬 프로그램의 시작 시간에 영향을 미첬습니다.

정방향 참조(forwrad reference)란, 아직 정의되지 않은 클래스, 함수, 변수 등을 참조하는 것을 말합니다. 즉, 코드의 순서상으로 나중에 정의될 객체를 먼저 참조하려고 할 때 발생하는 문제입니다.

PEP 563은 위의 주요한 문제를 해결하기 위해 어노테이션의 평가를 지연시킴으로써 문제를 해결합니다.

이제, 어노테이션이 전방 참조를 지원하므로 다음과 같은 코드가 가능해졌습니다.

class C:
    @classmethod
    def from_string(cls, source: str) -> C:
        ...

    def validate_b(self, obj: B) -> bool: # obj: B는 전방 참조 (이전에는 동작 X)
        ...

class B:
    ...

이 제안이 도입되면서 호환성이 깨지기 때문에, 파이썬 3.7에서 새 동작은 __future__ 임포트를 사용하여 모듈별로 새로운 동작을 활성화해야 합니다.

from __future__ import annotations

PEP 538: Legacy C Locale Coercion

파이썬 3에서 계속해서 진행 중인 것중 하나는, 현재 C나 POSIX 로케일을 사용하는 비-윈도우 플랫폼에서의 “7비트 ASCII” 텍스트 인코딩 가정을 처리하기 위한 합리적인 기본 전략을 결정하는 것입니다. PEP 538은 기본 인터프리터 CLI가 자동으로 새로운 PYTHONCOERCELOCALE 환경변수의 문서 안에 명시된 사용가능한 UTF-8 기반의 로케일로 강제 변환되도록 합니다.

자동으로 LC_CTYPE을 설정하는 것은 코어 인터프리터와 로케일-인식 C 확장(예: readline)이 모두 아스키 코드가 아닌 UTF-8을 기본 텍스트 인코딩으로 하도록 가정하도록 합니다. 또한 PEP 11의 플랫폼 지원 정의가 업데이트되어 전체 텍스트 처리 지원이 적절하게 구성된 비-아스키 기반 로케일로 제한되었습니다.

이 변화의 일부로써, C.UTF-8, C.utf8, UTF-8을 사용할 때, stdin과 stdout을 위한 기본 에러 핸들러가 이제는 surrogateescape를 사용합니다. stderr 을 위한 기본 에러 핸들러는 로케일(locale)에 상관없이 계속해서 backslashreplace를 사용합니다.

로케일 변환은 기본적으로는 조용하게 처리됩니다. 하지만, 로케일과 관련된 잠재적인 문제를 디버깅을 위해, PYTHONCOERCELOCALE=warn 설정을 함으로써 명시적인 경고를 요청할 수 있습니다. 이 설정은 또한 코어 인터프리터가 초기화될 때, 레거시 C 로케일이 여전히 활성화되어 있는 경우에도 경고를 발생시킵니다.

PEP 538의 로케일 강제 변환은 확장 모듈(ex: readline)과 하위 프로세스(비 파이썬 애플리케이션 및 이전 버전의 파이썬을 실행하는 것을 포함)에 영향을 미치지만, 실행 중인 시스템에 적합한 대상 로케일이 있어야 한다는 단점이 있습니다. 적합한 대상 로케일이 없는 경우를 처리하기 위해, 파이썬 3.7은 PEP 540: 강제 UTF-8 런타임 모드를 구현합니다.

PEP 540: Forced UTF-8 Runtime Mode

위의 PEP 538의 마지막에서 언급했듯이, 로케일 강제 변환은 확장 모듈과 하위 프로세스에 영향을 미치지만, 실행 중인 시스템에 적합한 로케일이 있어야한다고 했습니다. PEP 540에서는 적합한 로케일이 없는 경우를 처리하기 위해, 파이썬 3.7은 강제된 UTF-8 런타임 모드를 구현합니다.

새로운 -X utf8 커맨드 라인 옵션과 PYTHONUTF8 환경 변수가 Python UTF-8 Mode 를 활성화 하기 위해서 사용될 수 있습니다.

UTF-8 모드를 활성화 하면, CPython은 로케일 설정을 무시하고, UTF-8 인코딩을 기본으로 사용합니다. 그리고, 에러 핸들러를 위한 sys.stdinsys.stdout 스트림은 surrogateescape로 설정됩니다.

강제된 UTF-8 모드는 내장된 애플리케이션의 로케일 설정의 변경 없이 내장된 파이썬 인터프리터에서 텍스트를 핸들링 동작을 변경하는 데 사용될 수 있습니다.

PEP 540의 UTF-8 모드는, 실행 중인 시스템에서 사용가능한 로케일과 상관없이 동작할 수 있는 이점이 있지만, UTF-8 모드는 확장 모듈과 하위 프로세스에 영향을 미치지 않습니다.

To reduce the risk of corrupting text data when communicating with such components, Python 3.7 also implements PEP 540: Forced UTF-8 Runtime Mode.

The UTF-8 mode is enabled by default when the locale is C or POSIX, and the PEP 538 locale coercion feature fails to change it to a UTF-8 based alternative (whether that failure is due to PYTHONCOERCECLOCALE=0 being set, LC_ALL being set, or the lack of a suitable target locale).

PEP 553: Built-in breakpoint()

파이썬의 내장 디버거 pdb를 사용하기위해서는 관용구로 import pdb; pdb.set_trace()를 통해 파이썬 디버거로 진입을 해서 디버깅을 합니다. 이 관용구는 27글자나 입력을 해야하고, 오타가 나기쉽습니다. 그래서 이 PEP에서는 새로운 내장 함수인 breakpoint()를 도입합니다.

이 PEP를 통해서 해결하는 주요 문제는 다음과 같습니다.

  • 관용적인 표현에 의존하지 않고 breakpoint() 함수를 사용해서 디버거에 진입합니다.
  • breakpoint() 함수는 디버거에 진입하기 위한 표준화된 방법을 제공함으로써 디버거의 종류에 상관없이 동작합니다. (pdb 말고 다른 디버거 선택 가능)

Built-in breakpoint() calls sys.breakpointhook(). By default, the latter imports pdb and then calls pdb.set_trace(), but by binding sys breakpointhook() to the function of your choosing, breakpoint() can enter any debugger. Additionally, the environment variable PYTHONBREAKPOINT can be set to the callable of your debugger of choice. Set PYTHONBREAKPOINT=0 to completely disable built-in breakpoint().

PEP 539: New C API for Thread-Local Storage

파이썬은 thread-local storage를 지원하기 위한 C API를 제공하지만, 기존 Thread Local Storage (TLS) API는 모든 플랫폼에서 TLS 키를 표현하기 위해서 정수를 사용해왔습니다. 이는 일반적으로 공식적으로 지원하는 플랫폼에서는 문제가 되지않지만, POSIX 호환이 되자않거나, TLS 키를 정수로 표현할 수 없는 플랫폼에서는 문제가 됩니다.

PEP 539는 새로운 Thread Specific Storage (TSS) API를 제공하고 기존 TLS API를 대체합니다. 새로운 TSS API는 TLS 키를 표현하기 위해서 int 대신에 Py_tss_t 타입을 사용합니다. 이는 TLS 키를 안전하게 int로 캐스팅할 수 없는 플랫폼에서 CPython을 빌드할 수 있도록 합니다.

native TLS 키가 안전하게 int로 캐스팅할 수 없는 플랫폼에서는 기존 TLS API의 모든 함수가 no-op이고, 즉시 실패를 반환합니다. 이는 기존 API가 안전하게 사용할 수 없는 플랫폼에서는 지원되지 않는다는 것을 명확하게 나타내고, 이러한 지원을 추가하기 위해서 노력하지 않는다는 것을 나타냅니다.

Native TLS: TLS 키를 플랫폼에서 제공하는 기능을 사용해서 표현하는 것을 의미합니다.

Py_tss_t: This data structure represents the state of a thread key, the definition of which may depend on the underlying TLS implementation, and it has an internal field representing the key’s initialization state. There are no public members in this structure.

PEP 562: Customization of Access to Module Attributes

파이썬 3.7은 모듈에서 __getattr__()을 정의할 수 있고, 모듈의 속성(attribute)가 없을 때마다 호출됩니다. 이제 모듈에서 __dir__() 도 정의할 수 있습니다.

모듈 속성이 deprecate 되었거나 지연 로딩 시 유용합니다.

PEP 564: New Time Functions With Nanosecond Resolution

현대 시스템 체계에서 시간 해석은 time.time() 함수와 그 변형이 반환하는 부동 소수점 수의 제한된 정밀도를 초과할 수 있습니다. 정밀도 손실을 피하기 위해서, PEP 564는 time 모듈에 기존 타이머 함수의 6가지 새로운 ”나노초(nanosecond)” 변형을 추가합니다.

  • time.clock_gettime_ns()
  • time.clock_settime_ns()
  • time.monotonic_ns()
  • time.perf_counter_ns()
  • time.process_time_ns()
  • time.time_ns()

이 새로운 함수들은 정수 형태의 나노초를 반환합니다.

리눅스와 윈도우의 time.time_ns() 함수의 측정을 보면 time.time() 보다 약 3배 정도의 높은 정밀도를 가진 것을 확인할 수 있습니다.

PEP 565: Show DeprecationWarning in __main__

DeprecationWarning의 기본 처리 방식이 다시 변경되어 이 경고는 다시 기본적으로 표시되지만, 이 경고를 트리거하는 코드가 __main__ 모듈에서 직접 실행될 때만 표시됩니다. 결과적으로 단일 파일 스크립트를 개발하거나 Python을 대화식으로 사용하는 사람들은 다시 사용하는 API에 대한 사용 중단 경고를 보게 될 것입니다. 그러나 가져온 응용 프로그램, 라이브러리 및 프레임 워크 모듈에서 트리거 된 사용 중단 경고는 계속 기본적으로 숨겨집니다.

이러한 변경의 결과로써, 표준 라이브러리는 이제 개발자가 세 가지 다른 사용 중단 경고 동작 중 하나를 선택할 수 있도록 허용합니다.

  1. FutureWarning: 항상 경고를 보여 줍니다.
  2. DeprecationWarning: __main__ 모듈과 테스트를 실행할 때만 경고를 보여줍니다. 이 동작은 버전 업그레이드로 동작이나 에러가 발생할 때 경고를 보여질 수 있도록 의도할 때 추천됩니다.
  3. PendingDeprecationWarning: 테스트를 실행할 때만 기본적으로 표시합니다. 새로운 버전으로 업그레이드하는 곳에서 경고 범주를 DeprecationWarning 또는 FutureWarning으로 변경할 경우에 사용됩니다.

이전에는 DeprecationWarning과 PendingDeprecationWarnin은 테스트를 실행할 때만 표시되었기 때문에, 주로 단일 파일 스크립트를 작성하거나 Python을 대화식으로 사용하는 개발자들은 사용하는 API에서 발생하는 변경 사항에 놀라게 될 수 있었습니다.

PEP 560: Core Support for typing module and Generic Types

초기에 PEP 484는 코어 CPython 인터프리터에 어떠한 변경도 도입하지 않도록 설계되었습니다. 이제는 타입 힌트와 typing 모듈이 커뮤니티에서 널리 사용되므로 이러한 제약이 사라졌습니다. 이 PEP 560은 새로운 두 개의 매직 메서드 __class_getitem()__()와 __mro_entries__를 도입합니다. 이 메서드들은 현재 typing 모듈에서 대부분의 클래스와 특수 생성자에서 사용됩니다. 이러한 함수들의 도입의 결과로써, 타입과 관련된 다양한 연산의 성능이 7배까지 증가하였고, 제네릭 타입은 메타 클래스 충돌없이 사용할 수 있게 되었습니다. 또한 typing 모듈의 여러 오래된 버그들이 수정되었습니다.

PEP 552: Hash-based .pyc Files

Python has traditionally checked the up-to-dateness of bytecode cache files (i.e., .pyc files) by comparing the source metadata (last-modified timestamp and size) with source metadata saved in the cache file header when it was generated. While effective, this invalidation method has its drawbacks. When filesystem timestamps are too coarse, Python can miss source updates, leading to user confusion. Additionally, having a timestamp in the cache file is problematic for build reproducibility and content-based build systems.

PEP 552 extends the pyc format to allow the hash of the source file to be used for invalidation instead of the source timestamp. Such .pyc files are called “hash-based”. By default, Python still uses timestamp-based invalidation and does not generate hash-based .pyc files at runtime. Hash-based .pyc files may be generated with py_compile or compileall.

Hash-based .pyc files come in two variants: checked and unchecked. Python validates checked hash-based .pyc files against the corresponding source files at runtime but doesn’t do so for unchecked hash-based pycs. Unchecked hash-based .pyc files are a useful performance optimization for environments where a system external to Python (e.g., the build system) is responsible for keeping .pyc files up-to-date.

See Cached bytecode invalidation for more information.

PEP 545: Python Documentation Translations

PEP 545는 파이썬 문서 번역을 생성하고 유지보수하는 절차를 설명합니다. 아래 3개의 번역이 추가되었습니다.

Python Development Mode (-X dev)

파이썬 개발 모드를 활성화할 수 있는 새로운 커맨드 라인 옵션과 환경변수가 추가되었습니다.

  • 커맨드 라인 옵션: -X dev
  • 환경변수: PYTHONDEVMODE=1

이 개발 모드가 활성화되어있다면 파이썬은 기본으로 활성화하기에는 부담스러운 런타임 체크를 추가적으로 수행합니다.

자세한 내용은 https://docs.python.org/3/library/devmode.html#devmode 이 문서를 읽어보면 됩니다.

기타 언어 변경사항

  1. async for 절을 포함하는 await 식과 컴프리헨션은 구현의 문제로 인해 형식화된 문자열 리터럴 식에서 사용이 불가능했는데요. Python 3.7에서는 이 제한이 해제되었습니다.

    • f'{x async for x in y}'는 이제 유효한 표현식입니다.
    • f'{await x}'도 이제 유효한 표현식입니다.
  2. 255개 이상의 인자를 함수에 전달할 수 있게 되었습니다. 또한 함수는 255개 이상의 파라미터를 가질 수 있게 되었습니다.

  3. bytes.fromhex()와 bytearray.fromhex()는 공백뿐만아니라, 모든 ASCII 공백을 무시합니다.

  4. str, bytes, 그리고 bytearray는 새로운 isascii() 메서드를 위한 지원을 얻습니다. isascii() 메서드는 문자열 혹은 바이트가 아스키 문자들을 포함하는지 테스트하는데 사용될 수 있습니다.

  5. ImportError는 이제 from … import … 구문이 실패할 때 모듈 이름과 모듈 file 경로를 표시합니다.

  6. 서브모듈에 이름을 바인딩한 절대경로 임포트를 포함하는 순환 임포트가 이제 지원됩니다.

  7. object.__format__(x, ”)은 format(str(self), ”)가 아니라 str(x)와 동일하게 동작합니다.

  8. 스택 트레이스의 동적 생성을 더 잘 지원하기 위해서, types.TracebackType은 이제 파이썬 코드로부터 인스턴스화 될 수 있고, traceback의 tb_next 속성은 쓰기가 가능해집니다.

  9. -m 스위치를 사용할 때, sys.path[0]은 이제 시작 디렉토리의 전체 경로로 미리 확장됩니다. 이전에는 빈 디렉토리로 남아있었습니다. (이전에는 import가 발생할 때 현재 작업 디렉토리에서 import가 가능했습니다.)

예시) python -m foo.bar를 실행할 때, sys.path[0]은 이제 foo/bar 디렉토리의 전체 경로로 확장됩니다. 이전에는 빈 디렉토리로 남아있었습니다.

>> python3 -m foo.bar
['/Users/pakmingi/workspace/test', # 이전에는 여기가 빈 디렉토리였습니다.
'/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python311.zip',
'/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11',
'/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/lib-dynload',
'/opt/homebrew/lib/python3.11/site-packages']
  1. 새로운 -X importtime 옵션 혹은 PYTHONPROFILEIMPORTTIME 환경 변수가 각 모듈의 임포트 시간을 보여주기 위해 사용됩니다.
>> python3 -X importtime -m foo.bar
import time: self [us] | cumulative | imported package
import time:       127 |        127 |   _io
import time:        21 |         21 |   marshal
import time:       251 |        251 |   posix
... 중략
import time:        64 |       2230 | runpy
import time:       333 |        333 | foo

새로운 모듈

contextvars

The new contextvars module and a set of new C APIs introduce support for context variables. Context variables are conceptually similar to thread-local variables. Unlike TLS, context variables support asynchronous code correctly.

The asyncio and decimal modules have been updated to use and support context variables out of the box. Particularly the active decimal context is now stored in a context variable, which allows decimal operations to work with the correct context in asynchronous code.

dataclasses

The new dataclass() decorator provides a way to declare data classes. A data class describes its attributes using class variable annotations. Its constructor and other magic methods, such as repr(), eq(), and hash() are generated automatically.

@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0

p = Point(1.5, 2.5)
print(p)   # produces "Point(x=1.5, y=2.5, z=0.0)"

importlib.resources

The new importlib.resources module provides several new APIs and one new ABC for access to, opening, and reading resources inside packages. Resources are roughly similar to files inside packages, but they needn’t be actual files on the physical file system. Module loaders can provide a get_resource_reader() function which returns a importlib.abc.ResourceReader instance to support this new API. Built-in file path loaders and zip file loaders both support this.

개선된 모듈

argparse

The new ArgumentParser.parse_intermixed_args() method allows intermixing options and positional arguments. (Contributed by paul.j3 in bpo-14191.)

asyncio

The asyncio module has received many new features, usability and performance improvements. Notable changes include:

The new provisional asyncio.run() function can be used to run a coroutine from synchronous code by automatically creating and destroying the event loop. (Contributed by Yury Selivanov in bpo-32314.)

asyncio gained support for contextvars. loop.call_soon(), loop.call_soon_threadsafe(), loop.call_later(), loop.call_at(), and Future.add_done_callback() have a new optional keyword-only context parameter. Tasks now track their context automatically. See PEP 567 for more details. (Contributed by Yury Selivanov in bpo-32436.)

The new asyncio.create_task() function has been added as a shortcut to asyncio.get_event_loop().create_task(). (Contributed by Andrew Svetlov in bpo-32311.)

The new loop.start_tls() method can be used to upgrade an existing connection to TLS. (Contributed by Yury Selivanov in bpo-23749.)

The new loop.sock_recv_into() method allows reading data from a socket directly into a provided buffer making it possible to reduce data copies. (Contributed by Antoine Pitrou in bpo-31819.)

The new asyncio.current_task() function returns the currently running Task instance, and the new asyncio.all_tasks() function returns a set of all existing Task instances in a given loop. The Task.current_task() and Task.all_tasks() methods have been deprecated. (Contributed by Andrew Svetlov in bpo-32250.)

The new provisional BufferedProtocol class allows implementing streaming protocols with manual control over the receive buffer. (Contributed by Yury Selivanov in bpo-32251.)

The new asyncio.get_running_loop() function returns the currently running loop, and raises a RuntimeError if no loop is running. This is in contrast with asyncio.get_event_loop(), which will create a new event loop if none is running. (Contributed by Yury Selivanov in bpo-32269.)

The new StreamWriter.wait_closed() coroutine method allows waiting until the stream writer is closed. The new StreamWriter.is_closing() method can be used to determine if the writer is closing. (Contributed by Andrew Svetlov in bpo-32391.)

The new loop.sock_sendfile() coroutine method allows sending files using os.sendfile when possible. (Contributed by Andrew Svetlov in bpo-32410.)

The new Future.get_loop() and Task.get_loop() methods return the instance of the loop on which a task or a future were created. Server.get_loop() allows doing the same for asyncio.Server objects. (Contributed by Yury Selivanov in bpo-32415 and Srinivas Reddy Thatiparthy in bpo-32418.)

It is now possible to control how instances of asyncio.Server begin serving. Previously, the server would start serving immediately when created. The new start_serving keyword argument to loop.create_server() and loop.create_unix_server(), as well as Server.start_serving(), and Server.serve_forever() can be used to decouple server instantiation and serving. The new Server.is_serving() method returns True if the server is serving. Server objects are now asynchronous context managers:

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.

Callback objects returned by loop.call_later() gained the new when() method which returns an absolute scheduled callback timestamp. (Contributed by Andrew Svetlov in bpo-32741.)

The loop.create_datagram_endpoint() method gained support for Unix sockets. (Contributed by Quentin Dawans in bpo-31245.)

The asyncio.open_connection(), asyncio.start_server() functions, loop.create_connection(), loop.create_server(), loop.create_accepted_socket() methods and their corresponding UNIX socket variants now accept the ssl_handshake_timeout keyword argument. (Contributed by Neil Aspinall in bpo-29970.)

The new Handle.cancelled() method returns True if the callback was cancelled. (Contributed by Marat Sharafutdinov in bpo-31943.)

The asyncio source has been converted to use the async/await syntax. (Contributed by Andrew Svetlov in bpo-32193.)

The new ReadTransport.is_reading() method can be used to determine the reading state of the transport. Additionally, calls to ReadTransport.resume_reading() and ReadTransport.pause_reading() are now idempotent. (Contributed by Yury Selivanov in bpo-32356.)

Loop methods which accept socket paths now support passing path-like objects. (Contributed by Yury Selivanov in bpo-32066.)

In asyncio TCP sockets on Linux are now created with TCP_NODELAY flag set by default. (Contributed by Yury Selivanov and Victor Stinner in bpo-27456.)

Exceptions occurring in cancelled tasks are no longer logged. (Contributed by Yury Selivanov in bpo-30508.)

New WindowsSelectorEventLoopPolicy and WindowsProactorEventLoopPolicy classes. (Contributed by Yury Selivanov in bpo-33792.)

Several asyncio APIs have been deprecated.

binascii

The b2a_uu() function now accepts an optional backtick keyword argument. When it’s true, zeros are represented by ’`’ instead of spaces. (Contributed by Xiang Zhang in bpo-30103.)

calendar

The HTMLCalendar class has new class attributes which ease the customization of CSS classes in the produced HTML calendar. (Contributed by Oz Tiram in bpo-30095.)

collections

collections.namedtuple()이 이제 기본 값을 지원합니다.

스택 오버플로우의 답변에서 볼 수 있듯이, 기본값을 지정하려면 defaults 키워드 인자를 사용하면 됩니다.

>>> from collections import namedtuple
>>> fields = ('val', 'left', 'right')
>>> Node = namedtuple('Node', fields, defaults=(None,) * len(fields))
>>> Node()
Node(val=None, left=None, right=None)

compileall

compileall.compile_dir() learned the new invalidation_mode parameter, which can be used to enable hash-based .pyc invalidation. The invalidation mode can also be specified on the command line using the new —invalidation-mode argument. (Contributed by Benjamin Peterson in bpo-31650.)

concurrent.futures

ProcessPoolExecutor and ThreadPoolExecutor now support the new initializer and initargs constructor arguments. (Contributed by Antoine Pitrou in bpo-21423.)

The ProcessPoolExecutor can now take the multiprocessing context via the new mp_context argument. (Contributed by Thomas Moreau in bpo-31540.)

contextlib

The new nullcontext() is a simpler and faster no-op context manager than ExitStack. (Contributed by Jesse-Bakker in bpo-10049.)

The new asynccontextmanager(), AbstractAsyncContextManager, and AsyncExitStack have been added to complement their synchronous counterparts. (Contributed by Jelle Zijlstra in bpo-29679 and bpo-30241, and by Alexander Mohr and Ilya Kulakov in bpo-29302.)

cProfile

The cProfile command line now accepts -m module_name as an alternative to script path. (Contributed by Sanyam Khurana in bpo-21862.)

crypt

The crypt module now supports the Blowfish hashing method. (Contributed by Serhiy Storchaka in bpo-31664.)

The mksalt() function now allows specifying the number of rounds for hashing. (Contributed by Serhiy Storchaka in bpo-31702.)

datetime

The new datetime.fromisoformat() method constructs a datetime object from a string in one of the formats output by datetime.isoformat(). (Contributed by Paul Ganssle in bpo-15873.)

The tzinfo class now supports sub-minute offsets. (Contributed by Alexander Belopolsky in bpo-5288.)

dbm

dbm.dumb now supports reading read-only files and no longer writes the index file when it is not changed.

dis

The dis() function is now able to disassemble nested code objects (the code of comprehensions, generator expressions and nested functions, and the code used for building nested classes). The maximum depth of disassembly recursion is controlled by the new depth parameter. (Contributed by Serhiy Storchaka in bpo-11822.)

distutils

README.rst is now included in the list of distutils standard READMEs and therefore included in source distributions. (Contributed by Ryan Gonzalez in bpo-11913.)

enum

The Enum learned the new ignore class property, which allows listing the names of properties which should not become enum members. (Contributed by Ethan Furman in bpo-31801.)

In Python 3.8, attempting to check for non-Enum objects in Enum classes will raise a TypeError (e.g. 1 in Color); similarly, attempting to check for non-Flag objects in a Flag member will raise TypeError (e.g. 1 in Perm.RW); currently, both operations return False instead and are deprecated. (Contributed by Ethan Furman in bpo-33217.)

functools

functools.singledispatch() now supports registering implementations using type annotations. (Contributed by Łukasz Langa in bpo-32227.)

gc

The new gc.freeze() function allows freezing all objects tracked by the garbage collector and excluding them from future collections. This can be used before a POSIX fork() call to make the GC copy-on-write friendly or to speed up collection. The new gc.unfreeze() functions reverses this operation. Additionally, gc.get_freeze_count() can be used to obtain the number of frozen objects. (Contributed by Li Zekun in bpo-31558.)

hmac

The hmac module now has an optimized one-shot digest() function, which is up to three times faster than HMAC(). (Contributed by Christian Heimes in bpo-32433.)

http.client

HTTPConnection and HTTPSConnection now support the new blocksize argument for improved upload throughput. (Contributed by Nir Soffer in bpo-31945.)

http.server

SimpleHTTPRequestHandler now supports the HTTP If-Modified-Since header. The server returns the 304 response status if the target file was not modified after the time specified in the header. (Contributed by Pierre Quentel in bpo-29654.)

SimpleHTTPRequestHandler accepts the new directory argument, in addition to the new —directory command line argument. With this parameter, the server serves the specified directory, by default it uses the current working directory. (Contributed by Stéphane Wirtel and Julien Palard in bpo-28707.)

The new ThreadingHTTPServer class uses threads to handle requests using ThreadingMixin. It is used when http.server is run with -m. (Contributed by Julien Palard in bpo-31639.)

profile

박민기

단순하게 살아라. 현대인은 쓸데없는 절차와 일 때문에 얼마나 복잡한 삶을 살아가는가? - 이드리스 샤흐

© 2023, 미나리와 함께 만들었음