Python
-
python - async def, asyncio개발 2023. 6. 3. 16:26
async def 비동기 함수를 정의하기 위한 파이썬 문법. async def 키워드를 사용하여 정의된 함수는 비동기적으로 실행될 수 있고 내부의 비동기 함수도 병렬로 실행할 수 있다 async def convert_int(a: str): await asyncio.sleep(1) return int(a) async def calc_add(str_a: str, str_b: str): now = datetime.now() int_a, int_b = await asyncio.gather(convert_int(str_a), convert_int(str_b)) print(datetime.now() - now) # 0:00:01.001219 return int_a + int_b loop = asyncio.get_e..
-
Python - namedtuple개발 2023. 2. 14. 18:23
namedtuple 파이썬에서 튜플은 컴마로 나눠진 데이터의 집합을 말한다. 예로 이런 것들은 모두 튜플이다 data: Tuple[str | int, ...] = (1, 2, 4, "Geek") 튜플은 배열처럼 index로 접근할 수 있으나 Dict처럼 개별 값에 대한 키 값이 없다보니 관리하는게 쉽지 않다. 그래서 파이썬에서는 namedtuple 걸 사용해 필드 값을 설정할 수 있게 했다. from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) point = Point(x=3, y=4) 결과 값은 다음과 같이 나온다. 필드 명에 따라서 값 접근이 가능하기 때문에 더 직관적으로 값을 받을 수 있다. print(point) pr..
-
Python - 데코레이터개발 2023. 2. 14. 16:09
Decorator 파이썬에서는 함수에 데코레이터라는 기능을 추가할 수 있다. 함수가 실행 될 때 다른 함수를 타도록 만드는 기능이다. def to_upper_text(func): text = func() if not isinstance(text, str): raise TypeError("not a string type") return text.upper() @to_upper_text def say(): return "welcome" say 함수 위에 @to_upper_text 라는 데코레이터를 추가했다. 데코레이터 안에서는 전달 받은 func() 함수의 결과 값이 str인지 확인하고 아니면 에러를 호출, 맞으면 upper 함수를 호출해서 대문자로 리턴한다. WELCOME 실행하면 대문자로 바뀌어서 출력된..