Writing functions in Python

All We Need is Data, itself !·2022년 3월 20일
0

DataCamp

목록 보기
1/13
post-thumbnail

Docstring formats

  • google style
args:
	arg_1 (str) : ..
	arg_2 (int, optional) : ...
    
returns:
	bool: ...
  • Numpydoc
  • reStructuredText
  • EpyText
# Add a docstring to count_letter()
def count_letter(content, letter):
  """Count the number of times `letter` appears in `content`."""
  if (not isinstance(letter, str)) or len(letter) != 1:
    raise ValueError('`letter` must be a single character string.')
  return len([char for char in content if char == letter])

call docstring in function

[function_name].__doc__
docstring = inspect.getdoc(count_letter)

open file with python

# Open "alice.txt" and assign the file to "file"
with open('alice.txt') as file:
  text = file.read()

python 'with'

python에서 with 문은 자원을 반납해야 할 때에 주로 쓰인다.

  1. 자원을 획득한다.
  2. 자원을 사용한다.
  3. 자원을 반납한다.
image = get_image_from_instagram()

# Time how long process_with_numpy(image) takes to run
with timer():
  print('Numpy version')
  process_with_numpy(image)

# Time how long process_with_pytorch(image) takes to run
with timer():
  print('Pytorch version')
  process_with_pytorch(image)

refs: https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=wideeyed&logNo=221653260516


python 'decorator'

python decorator란 무엇인가에 대해

refs: https://hello-bryan.tistory.com/214

  • decorator 선언: @ [decorator_name]

같이 사용되는 yield는?

  • yieldreturn처럼 함수의 리턴값을 주는데, 여러번 줄 수 있다는 차이가 있음.
def yield_test():
	return list("arg")
def yield_test(arg):
	yield "a"
    yield "r"
    yield "g"

refs: https://www.daleseo.com/python-yield/

  • 개인적으로? 여기까지? 라는 느낌이 있음.
profile
분명히 처음엔 데린이었는데,, 이제 개린이인가..

0개의 댓글