반응형

파이썬 3.9 추가 기능

 

글. 수알치 오상문

 

참조: https://docs.python.org/ko/dev/whatsnew/3.9.html

 

파이썬 3.8 최신버전에도 반영된 사항도 있습니다. 

아래 예제를 참고하기 바랍니다.


[ Ex39.py ]

# 1. 사전 결합 연산자 '|'
x = {"key1": "x value 1", "key2": "x value 2"}
y = {"key2": "y value 2", "key3": "y value 3"}

xy = x | y
print(xy)
# {'key1': 'x value 1', 'key2': 'y value 2', 'key3': 'y value 3'}

yx = y | x
print(yx)
# {'key2': 'x value 2', 'key3': 'y value 3', 'key1': 'x value 1'}

# 2. 사전 병합 복합대입 연산자 '|='
x |= y
print(x)
# {'key1': 'x value 1', 'key2': 'y value 2', 'key3': 'y value 3'}


# 3. 문자열의 접두어 접미어 제거 기능
text = "*** 우리나라 만세 ***"
print(text)

text = text.removeprefix('*** ')  
print(text)  # 우리나라 만세 ***

text = text.removesuffix(' ***')
print(text)  # 우리나라 만세


# 4. 타입 어노테이션 타이핑에서 list, dict 같은 내장 컬렉션 형을 제네릭 형으로 사용 
def greet_all(names: list[str]) -> None:
    for name in names:
        print("Hello", name)

greet_all(['길동', '영희', '철수'])


# 5. 절대 경로 모듈명 확인 __file__
import sys
print(greet_all.__code__.co_filename)  # C:/project_python/Ex39.py
print(sys.path[0])  # C:/project_python
print(__file__)  # C:/project_python/Ex39.py


# 6. zoneinfo
from zoneinfo import ZoneInfo
from datetime import datetime, timedelta

# Daylight saving time
dt = datetime(2023, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles"))
print(dt)
# 2023-10-31 12:00:00-07:00
print(dt.tzname())
# PDT

# Standard time
dt += timedelta(days=7)
print(dt)
#2023-11-07 12:00:00-08:00
print(dt.tzname())
# PST


# 7. 그래프 위상 정렬 (시작점과 끝점 기준으로 그래프 경로 생성)
from graphlib import TopologicalSorter 
graph = {"D": {"B", "C"}, "C": {"A"}, "B": {"A"}}
ts = TopologicalSorter(graph)
print(tuple(ts.static_order()))
# ('A', 'C', 'B', 'D')


# 8. ast의 dump()에서 indent 옵션 지원
import ast
node = ast.parse('spam(eggs, "and cheese")')
print(ast.dump(node))
# Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')], keywords=[]))], type_ignores=[])
print(ast.dump(node, indent=3))
'''
Module(
   body=[
      Expr(
         value=Call(
            func=Name(id='spam', ctx=Load()),
            args=[
               Name(id='eggs', ctx=Load()),
               Constant(value='and cheese')],
            keywords=[]))],
   type_ignores=[])
'''


# 9. asyncio 기능 추가 
# shutdown_default_executor()
# asyncio.PidfdChildWatcher
# asyncio.to_thread()


# 10. concurrent.futures
# cancel_futures 매개 변수를 concurrent.futures.Executor.shutdown()에 추가
 

# 11. IPv6 주소를 구성. address가 유효 IPv6 아니면 AddressValueError 발생
import ipaddress
print(ipaddress.IPv6Address('2001:db8::1000'))
# IPv6Address('2001:db8::1000')
print(ipaddress.IPv6Address('ff02::5678%1'))
# IPv6Address('ff02::5678%1')


# 12. math.gcd() 확장,
#     math.lcm(), math.nextafter(), math.ulp() 추가
import math
print('최대공약수:', math.gcd(36, 12, 75))  # 3
print('최소공배수:', math.lcm(5, 7))  # 35


# 13. randbytes() 무작위 랜덤 바이트열
import random
print(random.randbytes(5))
# b'\xe1\xc8\x113\x14'
print(random.getrandbits(10*8).to_bytes(10, "little"))
# b')\xf4\xf5\xec\x90\x8fw\xa0\xf4\xb2'

반응형

+ Recent posts