728x90
반응형
Python 처음 접하는 사람들이 하는 흔한 실수
1) try ~ except~ 구문
구문 사용할 때 error문을 직접 그것도 이상하게 작성하는 경우가 많다. python에서 사용하는 error 구문을 사용하면 될 일을 나만이 알아보게 해놓는것이 큰 실수로 이어진다.
[Worse]
total: float = 0
while True:
user_input: str = input("Add: ")
try:
total += float(user_input)
except:
print('숫자만 입력해주시오.')
print(f"Current: {total}")
[Better]
total: float = 0
while True:
user_input: str = input("Add: ")
try:
total += float(user_input)
except Exception as e:
print(repr(e))
print(f"Current: {total}")
2) type 선언
static 변수를 사용해 append 함수를 만들어 보자.
[Worse]
from typing import Iterable, TypeVar, Any
T = TypeVar('T') # static type checking
def append_to_list(elements: Iterable[T], target: list[T]=[]) -> list[Any]:
target.extend(elements)
return target
print(append_to_list([1, 2])) # [1, 2]
print(append_to_list([3, 4])) # [1, 2, 3, 4]
print(append_to_list([5, 6],[])) # ??? [5, 6]
print(append_to_list(["a","b"])) # [1, 2, 3, 4, 5, 6, 'a', 'b']
위 결과 기존의 변수가 남아 List append가 되는 것을 볼 수 있다.
append_to_list의 target이 있을 때 없을때 나누어 함수를 만들면 기존 list를 참조하지 않고 넘길 수 있다.
[Better]
from typing import Iterable, TypeVar, Any
T = TypeVar('T') # static type checking
def append_to_list(elements: Iterable[T], target: list[T]=None) -> list[Any]:
if target is None:
target = []
target.extend(elements)
return target
print(append_to_list([1, 2])) # [1, 2]
print(append_to_list([3, 4])) # [3, 4]
print(append_to_list([5, 6],[])) # [5, 6]
print(append_to_list(["a","b"],["c"])) # ["a", "b", "c"]
3) 더 이상 range를 무시하지 마라
range를 다시 list로 받아 사용하는 경우가 있다. 이 경우 range에서 사용할 iteration을 모두 list에 담아야하기 때문에 메모리가 상당히 늘어난다.
from sys import getsizeof
my_range : range = range(10**6)
print(type(my_range))
print(getsizeof(my_range), 'bytes')
# <class 'range'>
# 48 bytes
my_range : list[int] = list(range(10**6))
print(type(my_range))
print(getsizeof(my_range), 'bytes')
# <class 'list'>
# 8000056 bytes
range, map, filter 이 처럼 iteration을 사용하는 함수의 경우 변환을 하지 않고 사용하는 것이 가장 빠르다.
반응형
'Python' 카테고리의 다른 글
string method. 1~20 (0) | 2024.04.28 |
---|---|
[Python] f-string trick (2) (0) | 2024.03.17 |
[Python] f-string trick (1) (0) | 2024.03.02 |
FastAPI - starlette.routing.NoMatchFound: No route exists for name (0) | 2024.01.19 |
[pip] WARNING: Skipping due to invalid metadata entry 'name' (0) | 2023.12.30 |