클로저

Python으로 함수 작성하기

Shayne Miel

Software Architect @ Duo Security

중첩 함수에 비지역 변수 붙이기

def foo():
  a = 5
  def bar():
    print(a)
  return bar

func = foo()

func()
5

클로저!

type(func.__closure__)
<class 'tuple'>
len(func.__closure__)
1
func.__closure__[0].cell_contents
5
Python으로 함수 작성하기

클로저와 삭제

x = 25

def foo(value):
  def bar():
    print(value)
  return bar

my_func = foo(x)
my_func()
25
del(x)
my_func()
25
len(my_func.__closure__)
1
my_func.__closure__[0].cell_contents
25
Python으로 함수 작성하기

클로저와 덮어쓰기

x = 25

def foo(value):
  def bar():
    print(value)
  return bar

x = foo(x)
x()
25
len(x.__closure__)
1
x.__closure__[0].cell_contents
25
Python으로 함수 작성하기

정의 - 중첩 함수

중첩 함수: 함수 안에 정의된 함수.

# outer function
def parent():
  # nested function
  def child():
    pass
  return child
Python으로 함수 작성하기

정의 - 비지역 변수

비지역 변수: 자식 함수에서 사용하는 부모 함수의 변수.

def parent(arg_1, arg_2):
  # child() 관점에서
  # `value`와 `my_dict`는 비지역 변수이며
  # `arg_1`과 `arg_2`도 마찬가지입니다.
  value = 22
  my_dict = {'chocolate': 'yummy'}

  def child():
    print(2 * value)
    print(my_dict['chocolate'])
    print(arg_1 + arg_2)

  return child
Python으로 함수 작성하기

클로저: 반환된 함수에 붙은 비지역 변수들.

def parent(arg_1, arg_2):
  value = 22
  my_dict = {'chocolate': 'yummy'}

  def child():
    print(2 * value)
    print(my_dict['chocolate'])
    print(arg_1 + arg_2)

  return child

new_function = parent(3, 4)

print([cell.cell_contents for cell in new_function.__closure__])
[3, 4, 22, {'chocolate': 'yummy'}]
Python으로 함수 작성하기

왜 중요할까요?

데코레이터에는 다음이 필요합니다:

  • 객체로서의 함수
  • 중첩 함수
  • 비지역 범위
  • 클로저
Python으로 함수 작성하기

Passons à la pratique !

Python으로 함수 작성하기

Preparing Video For Download...