반응형

Python을 더 잘 알고 더 잘 사용하기 위해 참고하면 좋은 자료 공유 및 약간의 정리를 해보았다!


실수하기 쉬운 Python 문법

출처: https://yozm.wishket.com/magazine/detail/1605/

  1. import * 사용함

    • 비효율적일 수 있다. 모듈에 object 가 많을 경우 모든 항목을 불러올 때까지 오랜시간 기다려야함
    • 변수명 충돌을 일으킬 수 있다.
  2. except 절 예외 지정 안함

    : SystemExit과 KeyboadInterrupt를 잡아서 Control-C로 프로그램 중지를 어렵게 함

  3. 수학계산에 numpy 사용 안함

    : numpy는 작업을 벡터화하기 때문에 더 빠름

  4. 이전에 열었던 파일을 닫지 않음 (비슷한 예로 db connect close하지 않음)

  5. PEP8 가이드라인을 벗어남

    https://peps.python.org/pep-0008/

    적절한 띄어쓰기, 이해하기 쉬운 변수명

     # Bad
     my_list = [1,2,3,4,5]
     my_dict = {'key1':'value1','key2':'value2'}
     x = 'Euni'
    
     # Good
     my_list = [1, 2, 3, 4, 5]
     my_dict = {'key1': 'value1', 'key2': 'value2'}
     my_name = 'Euni'
  6. 딕셔너리 사용시에 .keys와 .values를 적절하게 사용하지 않음

     # Bad - euni: ..? 왜 bad인지 모르겠...다...
     for key in my_dict.keys():
         print(key)
    
     # Good
     for key in my_dict:
         print(key)
    
     # Bad
     for key in my_dict:
         print(my_dict[key])
    
     # Good
     for key, value in my_dict.items():
         print(value)
  7. 컴프리헨션(comprehension)을 사용하지 않음 (혹은 언제나 사용)

    • 컴프리헨션: list, dict 등을 생성하는 경우 for 루프 대신 더 짧은 코드로 해결할 수 있게 도와줌
  8. range(len()) 사용

    → enumerate로 대신 사용할 수 있음

  9. + 연산자를 사용한 문자열 연결

    → f-string로 대신 사용할 수 있음

  10. mutable value를 디폴트 매개변수로 사용할 때

    # Bad
    def my_function(i, my_list=[]):
        my_list.append(i)
        return my_list
    
    # Good
    def my_function(i, my_list=None):
        if my_list is None:
            my_list =[]
        my_list.append(i)
        return my_list


type hints

출처: https://realpython.com/python-type-checking/

  1. Function Annotations

     ## format
     # def func(arg: arg_type, optarg: arg_type = default) -> return_type:
    
     # ex) without return type
     import tensorflow as tf
     import numpy as np
    
     def parse_fn(row: np.array):
         row = row.decode('utf-8')  # type: str
         [...]
         return x, y
    
     dataset = dataset.map(lambda x: tf.numpy_function(parse_fn, inp=[x],
                                           Tout=[tf.float32, tf.int64]
                                          ),
                           num_parallel_calls=tf.data.experimental.AUTOTUNE)
    
     # ex2) type 에러 발생하도록 하려면 assert 이용하기
     def test_fn(text: str, status: bool = True) -> str:
         assert (isinstance(text, str) and isinstance(status, bool)), 'TypeError')
         [..]
         return text
  2. Variable Annotations

     name: str = "Euni"
     pi: float = 3.142
     centered: bool = False
    
     names: list = ["Euni", "PePe", "SHS"]
     version: tuple = (3, 7, 1)
     options: dict = {"centered": False, "capitalize": True}
    • 다른 type으로 재할당도 에러 발생하지 않음
  3. Typing Module

     from typing import Dict, List, Tuple  # 내장함수
    
     names: List[str] = ["Euni", "PePe", "SHS"]
     version: Tuple[int, int, int] = (3, 7, 1)
     options: Dict[str, bool] = {"centered": False, "capitalize": True}
반응형

+ Recent posts