2019.8.8 Python 3.8에 추가되는 문법 미리보기1 - positional-only argument

Positional Only argument 

 파이썬은 def func(arg, * kwarg)로 positional argument의 제한 및 keyword argument 강제를 할 수 있다.

*이전의 arg는 positional arg이며 * 이후의 kwarg는 반드시 키워드 arg를 accept한다.

헌데 3.8에서는 보아하니 새로운 문법인 'Positional only' argument가 추가된 듯 하다.


def name(positional_only_parameters, /, positional_or_keyword_parameters,
         *, keyword_only_parameters):

/ 를 추가하면 / 이전의 arg들은 모두 positional argument로만 받겠다는 sign이다.

원문을 보면


The following would apply:
  • All parameters left of the / are treated as positional-only -> / 이전의 arg들은 모두 positional-only이다
  • If / is not specified in the function definition, that function does not accept any positional-only arguments -> 만약 함수가 받는 arg 리스트에 / 가 없다면 positional-only로 arg를 받지 않는다.
  • The logic around optional values for positional-only parameters remains the same as for positional-or-keyword parameters -> positional-only parameters의 로직은 기존과 같다는 것.
  • Once a positional-only parameter is specified with a default, the following positional-only and positional-or-keyword parameters need to have defaults as well. ->  positional-only parameter가 기본값과 함께 정의되면 뒤따라오는  positional-only,  positional-or-keyword parameter들도 역시 기본값이 필요하다.
  • Positional-only parameters which do not have default values are required positional-only parameters.->  기본값을 갖지 않는 positional-only parameter는 positional-only parameters이어야 한다. (기본값이 없는 경우엔 positional-param으로 전달해야한다는 뜻. positional_arg=None 과 같은 방식이 아니라.)


활용 예제는 아래와 같다. (공식 문서)

def name(p1, p2, /, p_or_kw, *, kw):
def name(p1, p2=None, /, p_or_kw=None, *, kw):
def name(p1, p2=None, /, *, kw):
def name(p1, p2=None, /):
def name(p1, p2, /, p_or_kw):
def name(p1, p2, /):
더 많은 예제는 https://docs.python.org/3.8/whatsnew/3.8.html 여기를 참고하자.


댓글

이 블로그의 인기 게시물

로컬 Tomcat 서버 실행속도 개선

2019.05.23 - SQLAlchemy 의 객체 상태 관리 (expire, refresh, flush, commit) 에 관한 이해

2020.02.17 Python의 multiprocessing 중 Pool.map(), chunksize에 관한 내용