[Python] YAPF

Python 2017. 3. 11. 14:59

YAPF

구글에서 제공하는 python Formatter


원래는 기존에 제공하는 autopep8을 사용하려고 했지만, 좀더 효율적인 포멧터를 찾아보려고 찾는 중에, 구글에서 제공하는 yapf 라는 포맷터를 찾았다.


이 포맷터에 대해서 포스팅 해보려고 한다.


지금 현재 잘 알려진 포맷터는 autopep8이랑, pep8ify가 있는데, 기본적으로 lint에서 나오는 Error을 해결하려고 만들어 졌다.


그런데 해당 포맷터들은 제한적일 수 밖에없는데, 어떤 것이냐면, PEP 8의 가이드를 정확히 따르고 있는 코드라면, 해당 코드들은 포맷팅을 하지 않는다.


pep8의 가이드만 준수한다고 해당 코드가 좋다고 볼수 없다.


YAPF는 다른방법으로 포맷팅을 하는데, Daniel Jasper가 개발한 'clang-format'을 기반으로 한다.


이 알고리즘은 코드를 가지고 와서 스타일 가이드를 준수하는 최상의 포맷으로 다시 포맷한다.

즉, PEP8의 가이드를 정확히 따르고 있는 코드더라도 다시 Reformatting 을 할 수 있다는 뜻이다.


Installation


설치방법은 간단하다.


$ pip install yapf

해당 방법으로 설치하면 되지만 YAPF는 계속적으로 바뀔수 있으므로, 가장 최신 버전을 유지하는 가장 좋은 방법은 저장소를 복제하는 방법이다.


Usage

옵션은 아래와 같다.


usage: yapf [-h] [-v] [-d | -i] [-r | -l START-END] [-e PATTERN]
            [--style STYLE] [--style-help] [--no-local-style] [-p]
            [files [files ...]]

Formatter for Python code.

positional arguments:
  files

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         show version number and exit
  -d, --diff            print the diff for the fixed source
  -i, --in-place        make changes to files in place
  -r, --recursive       run recursively over directories
  -l START-END, --lines START-END
                        range of lines to reformat, one-based
  -e PATTERN, --exclude PATTERN
                        patterns for files to exclude from formatting
  --style STYLE         specify formatting style: either a style name (for
                        example "pep8" or "google"), or the name of a file
                        with style settings. The default is pep8 unless a
                        .style.yapf or setup.cfg file located in one of the
                        parent directories of the source file (or current
                        directory for stdin)
  --style-help          show style settings and exit
  --no-local-style      don't search for local style definition (.style.yapf)
  -p, --parallel        Run yapf in parallel when formatting multiple files.
                        Requires concurrent.futures in Python 2.X

Formatting style

YAPF에서 사용하는 STYLE은 얼마든지 설정을 구성할 수 있고, 서식을 지정하는 여러가지 방법들이 있습니다.

코드안에 style.py을 참조하면 전체리스트를 볼수 있습니다.


스타일을 제어하려면 --style 아규먼트를 사용하면 됩니다. 이미 구성되어진 사전 정의된 스타일 ( EX : pep8 또는 google )중 하나를 선택하거나 원하는 구성파일을 직접 지정해도 됩니다.


설정 파일은 [스타일] 표제가 있는 key = value 쌍의 간단한 목록입니다 . 아래를 보시죠.


[style]
based_on_style = pep8
spaces_before_comment = 4
split_before_logical_operator = true

아래와 같은 방법으로 사용가능합니다.


--style='{based_on_style: chromium, indent_width: 4}'

YAPF는 다음과 같은 방식으로 서식 스타일을 검색합니다.


1. 커맨드라인 

2. 현재나, 상위 디렉토리중 하나에 있는 .stype.yapf파일.


2개 찾는법이 있으나 생략 (보통 위2가지를 지정해서 사용할거 같으므로) 없으면


기본적으로 PEP8 방식을 사용함.


Example

어떤식으로 포맷팅 되는지 봅시다.


x = {  'a':37,'b':42,

'c':927}

y = 'hello ''world'
z = 'hello '+'world'
a = 'hello {}'.format('world')
class foo  (     object  ):
  def f    (self   ):
    return       37*-+2
  def g(self, x,y=42):
      return y
def f  (   a ) :
  return      37+-+a[42-x :  y**3]


포멧팅!


x = {'a': 37, 'b': 42, 'c': 927}

y = 'hello ' 'world'
z = 'hello ' + 'world'
a = 'hello {}'.format('world')


class foo(object):
    def f(self):
        return 37 * -+2

    def g(self, x, y=42):
        return y


def f(a):
    return 37 + -+a[42 - x:y**3]


'Python' 카테고리의 다른 글

Pycharm 에서 무조건 세팅해줘야 할것.  (0) 2017.05.18
[Flask] Flask - wsgi - nginx 연동.  (0) 2017.05.15
[Python] python getter setter  (0) 2017.02.16
[Python] 공부해야 할 것.  (0) 2017.02.15
[Python]pywin32 설치기.  (0) 2016.12.15
Posted by C마노
,