내가 만든 프로젝트를 오픈소스로 공개하기로 했다.
https://github.com/AutoPipo/pypipo
GitHub - AutoPipo/pypipo: Python Library based on EasyPipo
Python Library based on EasyPipo. Contribute to AutoPipo/pypipo development by creating an account on GitHub.
github.com
오픈소스로 공개하기 이전에 내 코드들을 정리할 필요가 있었다.
코드 정리하기
우선 오픈소스를 컨트리뷰션 하기 위해서는 참고할만한 많은 것들이 필요하다.
하지만 그것보다 더 중요한 것은, 내 소스코드가 이해하기 쉬운가? 가독성이 좋은가?
남들이 보고 한 눈에 알아보거나 이해할 수 있는 소스코드인가?
당연히 나 혼자서 개발할 때는
주석을 어찌 작성하든, 함수명을 어떻게 하든 크게 중요하지 않다.
왜냐면 나 혼자 보고 나 혼자 이해하면 되니까. (물론 이것도 좋진 않다. 나중에 내가 봐도 이해가 안될 가능성이 농후하다.)
그래서 소스코드를 정리하기로 했다. 어떻게?
1. PEP8 Style 적용하기
PEP8은 거의 표준화된 파이썬 스타일 가이드이다.
🔗PEP8 Style Guide
PEP 8 – Style Guide for Python Code | peps.python.org
PEP 8 – Style Guide for Python Code Author: Guido van Rossum , Barry Warsaw , Nick Coghlan Status: Active Type: Process Created: 05-Jul-2001 Post-History: 05-Jul-2001, 01-Aug-2013 Table of Contents This document gives coding conventions for the Python co
peps.python.org
이 중에서도 내가 중요하게 생각한 부분은
- Snake, Camel을 적절하게 사용하여 변수명, 함수명 스타일을 통일하자
- 각 이름을 누가봐도 무엇인지 알 수 있게, 자세하게 네이밍 하자
- 주석을 적절하게 사용하여, 처음 코드를 보는 사람도 이해할 수 있도록 돕자
그래서 우선 네이밍을 전부 바꾸기로 했다.
- class : Camel style, start with upper (ThisIsClassName)
- method, variables : Snake style (this_is_method)
- const variable : Upper Snake style (THIS_IS_CONST_VARIABLE)
2. Numpy Style guide 적용하기
파이썬 주석이나 네이밍 스타일도 여러 종류가 있는데
내가 처음 오픈소스를 분석할 때 참고한 프로젝트가 numpy style guide를 참고하고 있었기에
나도 따라서 하기로 했다.
Style guide — numpydoc v1.6.0rc2.dev0 Manual
Style guide This document describes the syntax and best practices for docstrings used with the numpydoc extension for Sphinx. Note For an accompanying example, see example.py. Some features described in this document require a recent version of numpydoc. F
numpydoc.readthedocs.io
특히 주석을 신경써서 작성하려 노력했는데
대충 이런식이다
'''
Parameters
----------
filename : str
copy : bool
dtype : data-type
iterable : iterable object
Attributes
----------
x : float
The X coordinate.
y : float
The Y coordinate.
Returns
-------
int
Description of anonymous integer return value.
'''
class라면 Attr이 있어야할 것이고
functions이라면 Returns가 있어야할 것이다.
아무튼 이 외에도 Note와 Warning 등 다양한 항목을 추가하여 작성하면 되는데
가독성이 좋을 뿐만 아니라, vscode에서 마우스 over 했을 때 보여지기도 한다.
변수 type과 설명을 명확하게 명시해서 소스코드를 분석하는 사람들의 이해를 높임이 목적이다.
3. public과 private 구분하기
파이썬에는 public과 private 개념이 모호하지만
그래도 함수나 변수에 언더바 _ 하나 또는 2개를 사용함으로서 구분할 수 있다.
class 내부에서만 사용하는 private에는 under bar 2개를 사용해서 외부에서 사용하는 것을 방지했고
변수 또한 마찬가지로 적용시켰다.
public과 private를 구분함으로서 외부에서 사용을 막는 용도도 있지만, 그 자체로 함수의 기능 또는 목적을 알릴 수 있다.
그렇게 해서 탄생한 코드는 아래와 같다
class Painting:
"""Change image to painting image.
Parameters
----------
filepath : str
File path that you want to convert
Attributes
----------
original_img : np.array
Input original image
painting : np.array
Color clustered image (Applied K-Means Algorithm)
color_rbg_values : np.array
Clustered color data list
"""
def __init__(self, filepath):
self.original_img = cv2.imread(filepath)
self.clustered_colors = np.array([])
return
def run(self,
number = 16,
attempts = 1,
is_upscale = False,
target_size = 3,
div = 8,
sigma = 20):
"""Cluster image color with k-means algorithm.
Parameters
----------
number : int, optional (default: 16)
Number of color clustered
attempts : int, optional (default: 1)
How many iterate try to k-means clustering
is_upscale : bool, optional (default: False)
Expand size of image
target_size : int, optional (default: 3)
Size that want to expand image.
If you want to guess the proper size, set size value under 1.
div : int, optional (default: 8)
Reducing numbers of color on image
sigma : int, optional (default: 20)
bilateralFilter Parameter
Returns
----------
painting : np.ndarray
Color clustered image
color_index_map : np.ndarray
a Array that contains clustered color indexs.
"""
target_image = self.__blurring(div, sigma)
if is_upscale:
target_image = self.__expand_image(target_image, target_size = target_size)
painting, color_index_map = self.__cluster_color_with_kmeans(target_image,
number_of_color = number,
attempts = attempts)
return painting, color_index_map
def __blurring(self, div, sigma):
"""Image blurring
Parameters
----------
div : int
Reducing numbers of color on image
sigma : int
bilateralFilter Parameter
Returns
-------
blurred_image : np.ndarray
blurred Image
"""
BILATERAL_FILTER_RADIUS = -1 # Auto decision by sigmaSpace
BILATERAL_FILTER_SIGMACOLOR_MIN = 10
BILATERAL_FILTER_SIGMACOLOR_MAX = 120
... 이하 생략
- Numpy style guide를 사용하여 class, method 주석을 정리하였다
- camel, snake 스타일을 class, variable, function, const 별로 통일하였다.
- private, public을 구분하였다.
- parameter에 default 값을 설정해주어, 사용자에게 자율성을 부여했다.
- 변수명이나 함수명을 더 구체화하였다.
'Open Source 개발' 카테고리의 다른 글
[오픈소스 개발기] pypipo는 어떻게 만들었을까? (0) | 2023.08.06 |
---|---|
[Visual Python] 오픈소스 컨트리뷰션을 위한 개선점 찾기 (0) | 2023.08.05 |
[오픈소스 개발기] 내가 만든 오픈소스 pip 등록하기 (0) | 2023.07.10 |
[오픈소스 개발기] pypipo : CLI 만들기 (0) | 2023.07.08 |
[Git] Forked repository update 하기 (0) | 2023.02.26 |