Python

Python 3.10 변경점 알아보기 - 1. Parenthesized context managers, Better error messages

r잡초처럼 2023. 1. 28. 20:17

Python 3.10 변경을 알아보려고 한다(3.11도 곧 할 거다.).

 

새로운 기능

Parenthesized context managers

콘텍스트 관리자에서 여러 줄에 걸쳐 계속하기 위해 괄호를 묶는 것이 지원된다. 이를 통해 이전에 Import문에서 가능했던 것과 유사한 방식으로 여러 줄에 긴 컨텍스트 관리자 컬렉션의 형식을 지정할 수 있다. 

with (CtxManager() as example):
    ...

with (
    CtxManager1(),
    CtxManager2()
):
    ...

with (CtxManager1() as example,
      CtxManager2()):
    ...

with (CtxManager1(),
      CtxManager2() as example):
    ...

with (
    CtxManager1() as example1,
    CtxManager2() as example2
):
    ...

Better error messages

SyntaxErrors

닫히지 않은 괄호 또는 대괄호가 포함된 코드를 구문 분석할 때 인터프리터는 구문 오류를 표시하는 대신 닫히지 않은 괄호와 괄호의 위치를 포함합니다. 

Error Code:

expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
            38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6,
some_other_code = foo()

이전 버전의 메시지 출력:

File "example.py", line 3
    some_other_code = foo()
                    ^
SyntaxError: invalid syntax

3.10 버전:

File "example.py", line 1
    expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
               ^
SyntaxError: '{' was never closed

이제 인터프리터에 의해 제기된 구문 오류 예외는 문제가 감지된 부분 대신 구문 오류 자체를 구성하는 표현식의 전체 오류 범위를 강조 표시한다. 

이전 버전에서는:

>>> foo(x, z for z in range(10), t, w)
  File "<stdin>", line 1
    foo(x, z for z in range(10), t, w)
           ^
SyntaxError: Generator expression must be parenthesized

3.10 버전에서는

>>> foo(x, z for z in range(10), t, w)
  File "<stdin>", line 1
    foo(x, z for z in range(10), t, w)
           ^^^^^^^^^^^^^^^^^^^^
SyntaxError: Generator expression must be parenthesized

 

더 다양한 케이스는 SyntaxError를  살펴보자

IndentationErrors

구문 위치를 포함하여 들여 쓰기가 예상되는 블록의 종류에 대한 더 많은 콘텍스트를 제공한다.

>>> def foo():
...    if lel:
...    x = 2
  File "<stdin>", line 3
    x = 2
    ^
IndentationError: expected an indented block after 'if' statement in line 2

AttributeErrors

특성 오류를 인쇄할 때, PyErr_Display()는 예외가 발생한 개체에서 유사한 특성 이름의 제안을 제공한다.

>>> collections.namedtoplo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'collections' has no attribute 'namedtoplo'. Did you mean: namedtuple?

NameErrors

인터프리터에서 발생한 NameError를 console에서 보여줄 때, PyErr_Display()는 다음과 같은 함수에서 발생한 유사한 변수 이름의 제안을 제공한다.

>>> schwarzschild_black_hole = None
>>> schwarschild_black_hole
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'schwarschild_black_hole' is not defined. Did you mean: schwarzschild_black_hole?