TIL | Python | Lambda

이도운·2021년 12월 30일
0

TIL

목록 보기
14/73
post-thumbnail

Lambda

람다는 이해하는 내용보다 규칙을 숙지하는 것이 우선이다. 하나의 문법이기 때문이다.

람다는 함수의 이름을 제거하고 내용을 반환하는 형태이다.

아래는 람다식의 모습이다

ref = lambda s: print(s)
ref("Hello") # Hello 출력

상단의 코드를 보듯이 람다식은 함수의 이름이 없는 것을 알 수 있다. 다만 매개변수와 함수의 몸체는 존재한다.

또한 주의할 점은 람다식을 쓸 때 몸체에 return 을 넣어주면 안 된다. 애당초 return 이 적용된 문법이기 때문이다.

그렇다면 람다식은 언제 유용하게 사용될 수 있을까? 보통은 간단한 인라인 콜백 함수를 만들 때 유용하게 사용될 수 있다. 다른 컴포넌트에서 사용되지 않는다면 해당 컴포넌트만을 위한 람다식이 적절할 것이다.

types 모듈에 어떤 타입들이 있는가

types.FunctionType

types.LambdaType

types.GeneratorType

  • 제너레이터 함수가 만든, 제너레이터-이터레이터 객체의 형.

types.CoroutineType

  • async def 함수가 만든 코루틴 객체의 형.

class types.CodeType(kwargs)

  • compile()이 반환하는 것과 같은 코드 객체의 형.

types.CellType

  • 셀 객체의 형 : 이러한 객체는 함수의 자유 변수(free variables)에 대한 컨테이너로 사용됩니다.

types.MethodType

  • 사용자 정의 클래스 인스턴스의 메서드 형.

types.BuiltinFunctionType

types.BuiltinMethodType

  • len()이나 sys.exit() 와 같은 내장 함수와 내장 클래스의 메서드의 형. (여기서, 《내장》이라는 용어는 《C로 작성된》을 의미합니다.)

types.WrapperDescriptorType

  • object.__init__()object.__lt__()와 같은, 일부 내장 데이터형과 베이스 클래스의 메서드의 형.

types.MethodWrapperType

  • 일부 내장 데이터형과 베이스 클래스의 연결된(bound) 메서드의 형. 예를 들어 object().__str__의 형입니다.

types.MethodDescriptorType

  • str.join()과 같은 일부 내장 데이터형의 메서드의 형.

types.ClassMethodDescriptorType

  • dict.__dict__['fromkeys']와 같은 일부 내장 데이터형의 연결되지 않은(unbound) 클래스 메서드의 형.

class types.ModuleType(name, doc=None)

  • 모듈의 형. 생성자는 만들 모듈의 이름과 선택적으로 독스트링을 취합니다.

class types.GenericAlias(t_origin, t_args)

  • list[int]와 같은 매개 변수화된 제네릭의 형입니다.

class types.TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)

  • sys.exc_info()[2]에서 발견되는 것과 같은 트레이스백 객체의 형.

types.FrameType

  • tb가 트레이스백 객체일 때 tb.tb_frame에서 발견되는 것과 같은 프레임 객체의 형.

types.GetSetDescriptorType

types.MemberDescriptorType

class types.MappingProxyType(mapping)

람다식으로 표현

def check_password(password):
    if len(password) < 8:
        return 'SHORT_PASSWORD'

    if not any(c.isupper() for c in password):
        return 'NO_CAPITAL_LETTER_PASSWORD'

    return True

상단의 코드를 람다식으로 표현해보자.

lambdas = [ 
   lambda pw: 'SHORT_PASSWORD' if len(pw) < 8 else None
   lambda pw: 'NO_CAPITAL_LETTER_PASSWORD' if not any(c.isupper() for c in pw) else None
]

def check_password_using_lambda(password):
    for f in lambdas:
        if f(password) is not None:
            return f(password)

    return True


print( check_password_using_lambda('123') )            # SHORT_PASSWORD
print( check_password_using_lambda('12356789f') )      # NO_CAPITAL_LETTER_PASSWORD
print( check_password_using_lambda('123456789F') )    # True

참고

1. 윤성우 열혈 파이썬 중급
2. 파이썬 공식 문서
https://docs.python.org/ko/3.9/library/types.html
3. 이것저것 공부하자
https://king-minwook.tistory.com/45?category=790107

profile
⌨️ 백엔드개발자 (컴퓨터공학과 졸업)

0개의 댓글