본문 바로가기

전체 글845

Python Anti Pattern - Not using dict keys when formatting strings Not using dict keys when formatting strings딕셔너리의 값을 문자열로 사용할 때, 명시적으로 모든 값들을 적어줄 필요가 없다.예를 들어 아래와 같은 딕셔너리가 존재한다고 가정한다.person = { 'first': 'Tobin', 'age': 20 } Anti-patternperson = { 'first': 'Tobin', 'age':20 } print('{0} is {1} years old'.format( person['first'], person['age']) ) # Output: Tobin is 20 years old person = { 'first': 'Tobin', 'last': 'Brown', 'age':20 } # Bad: we have to change th.. 2019. 1. 28.
Python Anti Pattern - Not using dict comprehensions Not using dict comprehensions가끔씩 파이썬 2.7버전대 이전에 사용하던 오래된 방식으로 딕셔너리를 초기화하는 코드들이 있다.새로운 딕셔너리 접근법은 기능적으로 동일함은 물론 좀 더 읽기 쉬운 형태를 제고한다. Anti-patternnumbers = [1,2,3] # hard to read my_dict = dict([(number,number*2) for number in numbers]) print(my_dict) # {1: 2, 2: 4, 3: 6}위 코드는 오래된 스타일로 딕셔너리를 초기화하는 예제이다.문법적으로는 아무런 문제가 없지만 읽기 어렵다. Best practicenumbers = [1, 2, 3] my_dict = {number: number * 2 for numb.. 2019. 1. 28.
Python Anti Pattern - Using type() to compare types Using type() to compare typesisinstance 함수는 상속도 지원하기 때문에 타입을 검사할 때 최적화된 함수이다.따라서 타입 검사가 필요할때는 isinstance()를 사용해야한다. Anti-patternimport types class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height r = Rectangle(3, 4) # bad if type(r) is types.ListType: print("object r is a list")위 예제에서는 if문을 통해 Rectangle 클래스가 ListType 타입인지 검사한다.이러한 스타일은 권장되는 패턴이라고 볼 수 .. 2019. 1. 28.
Python Anti Pattern - Asking for permission instead of forgiveness Asking for permission instead of forgiveness파이썬 커뮤니티에서는 EAFP(easier to ask for forgiveness than permission) 코딩 스타일을 사용한다.이 코딩 스타일은 필요한 변수, 파일등이 존재한다고 가정하는 것이다.이외의 문제가 발생한다면 예외를 통해 처리한다.위와 같은 형태로 작업한다면 다수의 try~except문이 포함된 깔끔하고 일관적인 코딩 스타일을 유지할 수 있다. Anti-patternimport os # violates EAFP coding style if os.path.exists("file.txt"): os.unlink("file.txt")위 코드를 먼저 살펴본다.if문에서 파일에 접근하기전에 먼저 파일이 존재하는지 검.. 2019. 1. 28.
Python Anti Pattern - Returning more than one variable type from function call Returning more than one variable type from function call만약 함수가 list, tuple, dictionary등의 타입을 리턴한다면 함수를 호출하는 쪽에서는 항상 리턴값의 타입을 검사해야한다.이것은 코드의 복잡성을 증가시키는 일이다.따라서 호출하는 쪽에서 타입을 검사하는 방법보다는 함수에서 값을 리턴할 때 raise를 통해 오류를 발생시켜주는 것이 낫다. Anti-patterndef get_secret_code(password): if password != "bicycle": return None else: return "42" secret_code = get_secret_code("unicycle") if secret_code is None: print("W.. 2019. 1. 28.
AWS Lambda + API Gateway로 API 만드는 방법 AWS Lambda란 Amazon Web Service에서 제공하는 서버리스(Serverless) 기능이다.한마디로 서버가 없고 코드만 존재한다는 뜻이다.예를 들어서 크롤링을 진행하여 데이터베이스에 적재하는 코드의 경우 24시간 떠있을 필요가 없이Crontab등을 통해 주기적으로 실행하면 된다.이러한 경우 EC2를 사용하는것은 리소스 낭비이므로 lambda를 사용하는것이 적절하다.또한 100만건의 요청까지는 무료로 제공되므로 EC2보다 비용면에서도 이득이라고 볼 수 있다.먼저 AWS Lambda 콘솔로 - 함수로 들어간다. 새로 작성을 선택하고 이름과 런타임을 지정한다.나는 파이썬으로 작업할 예정이므로 Python 3.6을 선택했다. 또한 역할을 선택할 수 있는데, RDS와 통신해야하므로 RDS에 접근할.. 2019. 1. 21.