Python을 시작할때 왜 switch가 없을까 했는데... 드디어 추가 되었다.
사용법은 다른 언어와 동일하게 case를 통해 비교 사용이 가능하다. if elif으로 처리하던 구문을 보다 유용하게 처리가 가능할 것으로 보인다.
>>> test = ["test2", "optionisbest"]
>>> debug = "dev"
>>> match test:
... case "test1":
... print('test1')
... case ["test2", option] if debug in ['dev', 'test']:
... print('test2', option)
... case _:
... print (f"Unknown test type '{test}'")
...
test2 optionisbest
필자의 경우 JSON을 많이 사용하는데 아래처럼 actions에 {'sleep': 5000}이 있는 경우 "sleep" key가 맞는 경우 durations 변수를 즉시 생성해서 활용할 수 있는 부분등이 코드 작성을 보다 유용하게 도와줄 것으로 보인다.
>>> actions = [{"sleep": 5000}]
>>>
>>> for action in actions:
... match action:
... case {"text": message, "color": c}:
... print(c)
... print(message)
... case {"sleep": duration}:
... print(duration)
... case {"sound": url, "format": "ogg"}:
... print(url)
... case {"sound": _, "format": _}:
... print("Unsupported audio format")
...
5000
이외에도 보다 정확한 코드 오류를 제공하는 부분도 코드 작성에 도움을 많이 줄 것으로 기대 된다.
#Python 3.9
>>> print("A"
... print("B"
File "<stdin>", line 2
print("B"
^
SyntaxError: invalid syntax
#Python 3.10
>>> print ("A"
... print ("B"
File "<stdin>", line 1
print ("A"
^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
변수 타입을 보다 명확히 표현할 수 있도록 ParamSpec 를 지원한다.
ParamSpec
이를 통해 데코레이터를 작성할 때 입력 값의 타입을 보다 정확이 알 수 있게 되었다.
Python의 장점이라고 할 수 있는 명확한 않은 타입 지정이 단점이 될 수 있는 부분을 개선되었다고 할 수 있다.
이는 다른 글에서 정리해 보겠다. 공식 글은 아래와 같다.
PEP 612 – Parameter Specification Variables | peps.python.org
Python Enhancement Proposals Python » PEP Index » PEP 612 Toggle light / dark / auto colour theme PEP 612 – Parameter Specification Variables Author: Mark Mendoza Sponsor: Guido van Rossum BDFL-Delegate: Guido van Rossum Discussions-To: Typing-SIG list
peps.python.org
'Python' 카테고리의 다른 글
Python - Log Decorator 활용 (0) | 2022.08.01 |
---|---|
Visual Studio Code - Python 자동 주석 생성 autoDocstring (0) | 2022.08.01 |
Python 인증서 오류 해결 - SSLError SSLCertVerificationError CERTIFICATE_VERIFY_FAILED (0) | 2022.07.29 |
Python - FastApi Cross-Origin Resource Sharing (CORS) 이해/해결 (0) | 2022.07.25 |
Python - __init__ arguments invalid 초기 파라미터 체크 (0) | 2022.07.22 |
댓글0