파이썬은 언어 자체는 간단하지만, 많은 Convention 과 표준 라이브러리(Standard Library), 그리고 여러 개발을 할 때 사용하는 외부 라이브러리를 포함하면, 그 규모는 상상을 초월한다. 문제는 이들을 실제로 찾아서 사용해야 한다는 것인데, 이를 위해 제공되는 파이썬의 유틸리티 들을 정리해 본다. 영어로 되어 있는 내용들이지만, 개발자들이 습관만 붙이면 개발하는 데 도움이 될 것으로 생각한다.
본 문은 Learning Python(Mark Lutz) 4th Edition 의 15장을 바탕으로 작성하였다.
dir함수
Object 의 attributes를 명령어에서 쉽게 확인할 때 사용하는 내장 함수이다. attributes가 있는 모든 object에 쓸 수 있다. 특정 모듈에서 제공하는 attributes를 확인하는 데 요긴하다. 예를 들어 sys모듈에 무엇이 있는 지를 확인하기 위해서는:
>>> import sys >>> dir(sys) ['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'last_traceback', 'last_type', 'last_value', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'real_prefix', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
만약 리스트 데이터 형을 다루고 있을 때 해당 타입에서 제공하는 attributes 가 기억나지 않는 다면dir([]) 처럼 해당 데이터 형의 값을 파라미터로 제공하여 확인할 수 있다.
Docstrings __doc__
# comments외에, 파이썬은 Object 에 붙여지는 documentation 을 지원한다. Docstring이라고 하며 Runtime 에 확인할 수 있다. 이러한 documentation은 __doc__attribute 로 제공된다. 모든 기본 제공 모듈에 영문 docstring 이 있어 활용만 하면 편리하지만, 국내 개발자들은 잘 활용하지 않을 수 있다는 생각은 든다.
>>> import sys >>> print sys.__doc__ This module provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter. Dynamic objects: argv -- command line arguments; argv[0] is the script pathname if known path -- module search path; path[0] is the script directory, else '' modules -- dictionary of loaded modules
이렇게 개발중에 파이썬 쉘을 통해서 많은 정보를 즉각 확인하고 적용할 수 있다. 이 정도라면 크게 도움이 되지 않을 수 있는데 모든 표준 라이브러리 함수들이나 클래스의 정보는 다음의 방법을 쓸 수 있다.
PyDoc: help함수
Docstring 을 잘 정돈해서 보여주는 내장 함수이다. 해당 함수를 이용하여 여러 문서화 작업을 할 수도 있지만 개발자 입장에서 가장 잘 쓰는 방법은 역시 파이썬 쉘에서 바로 바로 확인하는 것이다. 다음의 예를 보자.
>>help(map) Help on built-in function map in module __builtin__: map(...) map(function, sequence[, sequence, ...]) -> list Return a list of the results of applying the function to the items of the argument sequence(s). If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence).
타입이나 함수, 클래스, 모듈 모두에 대해 활용할 수 있다. 파이썬 표준 라이브러리 소스코드에서 직접 생성되는 것이기 때문에 버전에 따라 달라지는 값에 대한 걱정도 필요없다. 외부 라이브러리를 쓰는 경우에도 해당 함수를 지원하는 경우가 많기 때문에 — 제대로 문서화 하는 개발자들도 많다. — 습관만 잘 들이면 파이썬 쉘을 활용하는 기회도 되고 웹을 뒤지지 않아도 된다.
보너스 – 파이썬 2.7의 새로운 집합(set) 기능 확인
지금 파이썬 쉘에서 help({1, 2})를 쳐보라. 3.X 버전에 보강된 set 기능이 2.7에 추가되었는데, 파이썬 버전이 2.7 이상이라면, set 에 대한 친절한 설명이 나오고 2.6 이하 버전에서는SyntaxError가 나올 것이다. 파이썬 2.7은 3.X 버전 이전 버전으로는 마지막 버전이 될 것으로 결정되었기 때문에 오랫동안 유지보수가 된다고 하니 2.7 버전을 기반으로 개발을 하는 것을 적극 권장한다.
