목적 : "하나의 명확한 방법"으로 코드 포맷을 표준화
사용 용도 : 파이썬 코드를 일관된 스타일로 자동 포매팅
사용시 장점 :
사용 예시 :
""" 파이썬 해당 파일만 포매팅 할때 """ black my_script.py """ 디렉토리 전체 포매팅 할때""" black src/ """ 설정 파일 (pyproject.toml) """ [tool.black] line-length = 88 target-version = ['py39']
출력 예시 :
적용 전
user_info={'name':'김철수','age':25,'skills':['python','django','react']} filtered_skills=[skill.upper() for skill in user_info['skills'] if len(skill)>5] print(f"User: {user_info['name']}, Skills: {', '.join(filtered_skills)}")
적용 후
user_info = {"name": "김철수", "age": 25, "skills": ["python", "django", "react"]} filtered_skills = [ skill.upper() for skill in user_info["skills"] if len(skill) > 5 ] print(f"User: {user_info['name']}, Skills: {', '.join(filtered_skills)}")
목적 : 모든 코드 품질 검사를 하나의 빠른 도구로 통합
사용 용도 : 파이썬 코드의 스타일, 버그, 복잡성을 초고속으로 분석
사용시 장점 :
사용 예시 :
""" 코드 검사 """ ruff check . """ 자동 수정 """ ruff check --fix . """ 설정 파일 (pyproject.toml) """ [tool.ruff] line-length = 88 select = ["E", "F", "W", "B", "I"]
출력 예시 :
src/main.py:12:1: F401 [*]
sys
imported but unused
src/main.py:23:80: E501 Line too long (95 > 88 characters)
src/main.py:45:1: I001 [*] Import block is un-sorted or un-formatted
Found 3 errors (2 fixable with--fix
)
목적 : 코드 품질의 종합적 평가 및 개선점 제시
사용 용도 : 코드 품질, 스타일, 잠재적 버그를 종합적으로 분석
사용시 장점 :
사용 예시 :
""" 파일 분석 """ pylint my_script.py """ 설정 파일 생성 """ pylint --generate-rcfile > .pylintrc
출력 예시 :
************* Module main main.py:1:0: C0114: Missing module docstring (missing-module-docstring) main.py:5:0: C0116: Missing function or method docstring (missing-function-docstring) main.py:12:4: W0613: Unused argument 'args' (unused-argument) Your code has been rated at 7.50/10
목적 : 코드 레벨에서의 보안 위험 사전 제거
사용 용도 : 파이썬 코드에서 보안 취약점을 자동으로 탐지
사용시 장점 :
사용 예시 :
# 보안 스캔 bandit -r src/ # JSON 리포트 생성 bandit -r src/ -f json -o security_report.json
출력 예시 :
> Issue: [B105:hardcoded_password_string] Possible hardcoded password: 'admin123' Severity: Medium Confidence: Medium Location: ./src/config.py:15
목적 : 서드파티 패키지의 보안 위험 관리
사용 용도 : 설치된 패키지들의 알려진 보안 취약점 검사
사용시 장점 :
사용 예시 :
# 현재 환경 검사 safety check # requirements.txt 검사 safety check -r requirements.txt
출력 예시 :
╒══════════════════════════════════════════════════════════════════════════════╕ │ found 2 known security vulnerabilities in 156 packages │ ╘══════════════════════════════════════════════════════════════════════════════╛ ╒══════════════════════════════════════════════════════════════════════════════╕ │ VULNERABILITY ID: 42194 │ │ PACKAGE NAME: urllib3 │ │ INSTALLED VERSION: 1.25.6 │ │ AFFECTED VERSIONS: <1.26.5 │ │ VULNERABILITY: CVE-2021-33503 │ ╘══════════════════════════════════════════════════════════════════════════════╛
목적 : 성능 병목 지점의 정확한 식별
사용 용도 : 실행 중인 파이썬 프로세스의 성능을 실시간으로 프로파일링
사용시 장점 :
사용 예시 :
# 실행 중인 프로세스 프로파일링 py-spy record -o profile.svg --pid 12345 # 스크립트 실행과 동시에 프로파일링 py-spy record -o profile.svg -- python my_script.py
출력 예시 :
Sampling process 100 times a second. Press Control-C to exit. Total Samples 1000 GIL: 89.00%, Active: 11.00%, Threads: 1 %Own %Total OwnTime TotalTime Function (filename:line) 89.00% 89.00% 0.89s 0.89s slow_function (main.py:15) 8.00% 97.00% 0.08s 0.97s main (main.py:5)
목적 : 함수 레벨에서의 성능 병목 식별
사용 용도 : 파이썬 내장 프로파일러로 함수별 실행 시간 분
사용시 장점 :
사용 예시 :
# 스크립트 프로파일링 python -m cProfile -s cumulative my_script.py # 결과를 파일로 저장 python -m cProfile -o profile.stats my_script.py
출력 예시 :
ncalls tottime percall cumtime percall filename:lineno(function) 16/1 0.000 0.000 43.451 43.451 {built-in method builtins.exec} 1 0.000 0.000 43.451 43.451 my_script.py:1(<module>) 1 0.000 0.000 43.424 43.424 my_script.py:518(main) 1 0.000 0.000 42.251 42.251 my_script.py:396(run) 6 39.477 6.579 39.477 6.579 {built-in method builtins.input}
목적 : 코드 품질 보장 및 리그레션 방지
사용 용도 : 파이썬 코드의 단위 테스트, 통합 테스트 작성 및 실행
사용시 장점 :
사용 예시 :
# 테스트 실행 pytest # 커버리지와 함께 실행 pytest --cov=src tests/
출력 예시 :
================================= test session starts ================================= platform darwin -- Python 3.9.7, pytest-7.1.2, pluggy-1.0.0 rootdir: /Users/project plugins: cov-3.0.0 collected 8 items tests/test_main.py::test_add_function PASSED [ 12%] tests/test_main.py::test_subtract_function PASSED [ 25%] tests/test_utils.py::test_validate_input PASSED [ 37%] tests/test_utils.py::test_process_data FAILED [ 50%] tests/test_api.py::test_get_user PASSED [ 62%] tests/test_api.py::test_create_user PASSED [ 75%] tests/test_api.py::test_delete_user PASSED [ 87%] tests/test_integration.py::test_full_workflow PASSED [100%] ================================== FAILURES =================================== _________________________ test_process_data ________________________ def test_process_data(): result = process_data([1, 2, 3]) assert result == [2, 4, 6] E assert [1, 4, 9] == [2, 4, 6] E At index 0 diff: 1 != 2 tests/test_utils.py:15: AssertionError ========================= short test summary info ========================== FAILED tests/test_utils.py::test_process_data - assert [1, 4, 9] == [2, 4, 6] ========================= 1 failed, 7 passed in 0.12s =========================
목적 : 테스트의 완성도 평가
사용 용도 : 테스트가 코드의 어느 부분을 실행했는지 측정
사용시 장점 :
사용 예시 :
# 커버리지 실행 coverage run -m pytest coverage report coverage html
출력 예시 :
Name Stmts Miss Cover Missing -------------------------------------------------- src/__init__.py 0 0 100% src/main.py 45 3 93% 78-80 src/utils.py 32 8 75% 45-52, 67 src/api.py 28 0 100% src/database.py 67 15 78% 89-95, 102-108, 125 -------------------------------------------------- TOTAL 172 26 85% Coverage HTML written to dir htmlcov
목적 : 프로젝트 의존성의 체계적 관리
사용 용도 : 파이썬 프로젝트의 의존성 관리 및 패키징
사용시 장점 :
사용 예시 :
""" 설치 """ curl -sSL https://install.python-poetry.org | python3 - """ 새 프로젝트 생성 """ poetry new my-project """ 의존성 설치 """ poetry add requests poetry add pytest --group dev