기본 콘텐츠로 건너뛰기

[git] pylint, pep8를 사용하여 코드스타일 검사





프로젝트의 규모가 커질수록 코드 스타일 통일이 매우 중요합니다.

python에서는 pylint와 pep8을 사용하여 스타일 검사가 다릅니다.
엄밀히 따지면 이둘은 약간 성격이 다릅니다.

우선 pylint에 대해서 먼저 알아보도록 하겠습니다.


$ vim app.py

import requests as rq

def test():
        print('test')

if __name__ == "__main__":
    test()


$ pylint app.py
************* Module app
W:  4, 0: Found indentation with tabs instead of spaces (mixed-indentation)
W:  7, 0: Found indentation with tabs instead of spaces (mixed-indentation)
C:  1, 0: Missing module docstring (missing-docstring)
C:  3, 0: Missing function docstring (missing-docstring)
W:  1, 0: Unused requests imported as rq (unused-import) ... 중략

3종류의 메시지가 출력이 됩니다.

1. 탭을 사용하지 않고 스페이스를 사용
2. docstring을 사용하지 않음
3. 사용하지 않는 모듈을 import

docstring이란?
docstring은 modlue, class, function의 설명을 작성하는 부분입니다. python에서는 
'''
설명...
:parameter {type} : 설명
:return {type} : 설명
'''
의 형태로 작성이 됩니다.


그럼 위의 메시지를 바탕으로 수정을 해보도록 하겠습니다.

$ vim app.py

'''
'''
def test():
    '''
    '''
    print('test')

if __name__ == "__main__":
    test()

$ pylint app.py
************* Module app
C:  1, 0: Empty module docstring (missing-docstring)
C:  3, 0: Empty function docstring (missing-docstring)
... 중략

이번에는 docstring이 비었다고 합니다.(참 까다로운 녀석입니다 ㅋㅋㅋ)

$ vim app.py

'''
2017.03.04
'''
def test():
    '''
    test function입니다.
    '''
    print('test')

if __name__ == "__main__":
    test()

$ pylint app.py
... 중략

이번에는 깨끗하게 출력이 됩니다.


이번에는 작명 표기법에 대한 테스트를 해보겠습니다
카멜 표기법과 스네이크 표기법을 구별을 해서 검사를 해줄지 궁금하네요


$ vim app.py

'''
2017.03.04
'''

class a_test:

    def __init__(self):
        self.aTest = 'asd'

def test():
    '''
    test function 입니다.
    '''
    print('test')

if__name__ == '__main__':
    test()
$ pylint app.py
************* Module app
C:  6, 0: Trailing whitespace (trailing-whitespace)
C:  5, 0: Invalid class name "a_test" (invalid-name)
C:  8, 8: Invalid attribute name "aTest" (invalid-name)
C:  5, 0: Missing class docstring (missing-docstring)
R:  5, 0: Too few public methods (0/2) (too-few-public-methods)
... 중략


클래스 이름과 속성에서 잘못된 이름을 사용했다고 나옵니다. 
클래스 내부에 public methods 적다고 나오네요 2개를 채워야 하나봅니다 

$ vim app.py

'''
2017.03.04
'''

class ATest:

    def __init__(self):
        self.a_test = 'te'

    def test(self):
        print('ATest test method')


def test():
    '''
    test function
    '''
    print('test')

if __name__ == '__main__':
    test():
$ pylint app.py
************* Module app
C:  6, 0: Trailing whitespace (trailing-whitespace)
C:  9, 0: Trailing whitespace (trailing-whitespace)
C:  5, 0: Missing class docstring (missing-docstring)
C: 10, 4: Missing method docstring (missing-docstring)
R: 10, 4: Method could be a function (no-self-use)
R:  5, 0: Too few public methods (1/2) (too-few-public-methods)
... 중략


카멜 케이스와 스네이크 케이스를 적절히 사용을 하니 작명에 대한 이수는 사라졌습니다. 
trailing whitespace는 라인 마지막에 스페이스를 의미 합니다. 

참고로 클래스 이름을 제외한 모든 이름은 스네이크 케이스를  pep8에서 권장을 하고 있습니다.


$ vim app.py

'''
2017.03.04
'''

class ATest:
    '''
    해당 클래스는 어쩌구 저쩌구
    '''

    def __init__(self):
        self.a_test = 'asd'

    def test(self):
        '''
        self.a_test를 어쩌구 저쩌구 함
        '''
        return self.a_test

    def test1(self):
        '''
        해당 메소드는 어쩌구 저쩌구
        '''
        return False

    def _test2(self):
        '''
        해당 메소든는 private입니다
        '''
        return True

def test():
    '''
    test function
    ''''
    print('test')

if __name__ == '__main__':
    test()


$ pylint app.py
... 중략


잘 됩니다. 

그리고 결과를 보면 중략이라고 해놓았는데 

Report
======
13 statements analysed.
Statistics by type
------------------
+---------+-------+-----------+-----------+------------+---------+
|type     |number |old number |difference |%documented |%badname |
+=========+=======+===========+===========+============+=========+
|module   |1      |1          |=          |100.00      |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|class    |1      |1          |=          |100.00      |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|method   |4      |4          |=          |100.00      |0.00     |
+---------+-------+-----------+-----------+------------+---------+
|function |1      |1          |=          |100.00      |0.00     |
+---------+-------+-----------+-----------+------------+---------+
Raw metrics
-----------
+----------+-------+------+---------+-----------+
|type      |number |%     |previous |difference |
+==========+=======+======+=========+===========+
|code      |15     |45.45 |15       |=          |
+----------+-------+------+---------+-----------+
|docstring |18     |54.55 |18       |=          |
+----------+-------+------+---------+-----------+
|comment   |0      |0.00  |0        |=          |
+----------+-------+------+---------+-----------+
|empty     |0      |0.00  |8        |-8.00      |
+----------+-------+------+---------+-----------+
Duplication
-----------
+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+
Messages by category
--------------------
+-----------+-------+---------+-----------+
|type       |number |previous |difference |
+===========+=======+=========+===========+
|convention |0      |0        |=          |
+-----------+-------+---------+-----------+
|refactor   |0      |0        |=          |
+-----------+-------+---------+-----------+
|warning    |0      |0        |=          |
+-----------+-------+---------+-----------+
|error      |0      |0        |=          |
+-----------+-------+---------+-----------+

아래에는 추가적이로 이러한 정보를 나타납니다.

단순하게 pep만 검사를 해보고 싶다. 그리고 new line에 대해서 좀더 엄격하게 검사를 하고 싶다면 . pylint가 아닌 pep8을 사용하시는 것을 권장합니다.

$ pep8 app.py
app.py:4:1: E302 expected 2 blank lines, found 0
app.py:10:5: E301 expected 1 blank line, found 0
app.py:15:5: E301 expected 1 blank line, found 0
app.py:20:5: E301 expected 1 blank line, found 0
app.py:25:1: E302 expected 2 blank lines, found 0

이것이 pep8의 결과입니다.

근데 pep8에서는 카멜 케이스, 스네이크 케이스에 대해서 검사가 엄격하지가 않네요

아무래도 이 두가지를 같이 쓰는것이 좋아보입니다.


댓글

이 블로그의 인기 게시물

[git] pull을 하여 최신코드를 내려받자

보면 먼가 로고가 다르게 뜨는것을 확인을 할 수가있다. C:\Users\mung\Desktop\etc\study\python-gene>git checkout remotes/origin/master Note: checking out 'remotes/origin/master'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example:   git checkout -b HEAD is now at 29e282a... fetch test C:\Users\mung\Desktop\etc\study\python-gene>git branch * (HEAD detached at origin/master)   master   test1   test2 깃이 잘 쓰면 참 좋은놈인데 어지간히 쓰기가 까다롭다. 처음에 깃을 푸시 성공하는데만 한달정도 걸렸던걸로 기억이 난다.. ㅋㅋㅋ 여담으로  깃 프로필을 가면 아래사진 처럼 보인다. 기여도에 따라서 초록색으로 작은 박스가 채워지는데 저걸 잔디라고 표현을 한다고 합니다 ㅎ 저 사진은 제 깃 기여도 사진입니당 ㅋㅋㅋㅋ 다시 본론으로 돌아와서 ㅋㅋ pull을 하면...

[kali linux] sqlmap - post요청 injection 시도

아래 내용은 직접 테스트 서버를 구축하여 테스트 함을 알립니다.  실 서버에 사용하여 얻는 불이익에는 책임을 지지 않음을 알립니다. sqlmap을 이용하여 get요청이 아닌 post요청에 대해서 injection공격을 시도하자. 뚀한 다양한 플래그를 이용하여 DB 취약점 테스트를 진행을 해보려고 한다. 서버  OS : windows 7 64bit Web server : X Server engine : node.js Framework : expresss Use modules : mysql Address : 172.30.1.30 Open port : 6000번 공격자 OS : kali linux 64bit use tools : sqlmap Address : 172.30.1.57 우선 서버측 부터  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 var  express  =  require( 'express' ); var  app  =  express(); var  mysql  =  require( 'mysql' ); var  ccc  =  mysql.createConnection({     host: '127.0.0.1' ,     user: 'root' ,     pos...

[node.js] 파일 리더기 만들기 - 사용 모듈 정리, pdf 구조, hwp 구조

pdf -> html 변환 가장 무난하다. 기본적으로 pdf는 htm와 비슷한 형태의 구조를 가지고 있다. 크게 header , body , xref table , trailer 의 구조로 되어있다. pdf는 환경에 상관없이 표현을 하기 위한 목적을 가지고 있는 파일이다. 이런 이유 때문에 무난히 진행이 된 것 같다. pdf2htmlex와 pdftohtmljs라는 모듈을 이용을 했다. var pdftohtml = require ( 'pdftohtmljs' ) ; var converter = new pdftohtml ( 'test.pdf' , "sample.html" ) ; converter . convert ( 'ipad' ) . then ( function ( ) { console . log ( "Success" ) ; } ) . catch ( function ( err ) { console . error ( "Conversion error: " + err ) ; } ) ; 이미지나, text같은 것들이 거의 100%로 변환이 된다. docx -> html 변환 docx파일을 html파일로 변환을 할 때는 style 적용과 한글이 깨지는 문제가 있다. 텍스트들을 전부 잘 읽기는 하는데 스타일 정보를 제대로 가져오지 못하기 때문에 좀 애매하다 - Headings. - Lists. - Customisable mapping from your own docx styles to HTML. For instance, you could convert WarningHeading to h1.warning by providing an appropriate style ...