Skip to main content

helper-dev-utils

PyPI version Python License: MIT

Python 개발 시 자주 사용하는 유틸리티 모음 라이브러리

주요 기능

  • helper_logger: 로깅 유틸리티 (콘솔/파일 핸들러, 타임존 설정, 기본 KST)
  • helper_pandas: Pandas 확장 기능 (한글 컬럼 설명, 데이터 출력, HTML/콘솔 지원)
  • helper_utils_print: 출력 유틸리티 (디렉토리/JSON/딕셔너리 트리 구조 출력)
  • helper_utils_colab: 경로 관리 유틸리티 (로컬/Colab 환경 경로 자동 탐색)
  • helper_colab_auth: Google Colab 인증 유틸리티 (사용자 인증, Secrets 조회, Drive 마운트 상태 확인)
  • helper_google_driver: Google Drive 경로 관리 유틸리티 (경로 조회/결합, 휴지통 비우기)
  • helper_help: 도움말 유틸리티 (함수/메서드 시그니처·docstring 출력, 모듈 함수 검색)

설치

기본 설치

pip install helper-dev-utils

# 테스트 서버
pip install --index-url https://test.pypi.org/simple/ helper-dev-utils

선택적 의존성 설치

# .env 파일 지원
pip install helper-dev-utils[dotenv]

# Jupyter/Colab 지원
pip install helper-dev-utils[jupyter]

# PyTorch Tensor 지원
pip install helper-dev-utils[torch]

# Google Drive 관리 기능 지원 (empty_drive_trash 등, Colab 전용)
pip install helper-dev-utils[google]

# 모든 선택적 의존성 설치
pip install helper-dev-utils[all]

사용법

1. Logger (helper_logger)

콘솔(및 선택적 파일) 로깅을 위한 최소 유틸리티입니다. 레벨은 한 글자로 축약 출력되고, 같은 이름으로 재호출해도 핸들러가 중복 등록되지 않습니다.

from helper_dev_utils import get_logger
import logging

# name을 생략하면 호출자 모듈명을 로거 이름으로 자동 사용
logger = get_logger()
logger.info("Hello World")
logger.warning("경고 메시지")
logger.error("에러 메시지")

# 레벨/타임존 설정
logger = get_logger(level=logging.DEBUG, tz="UTC")
logger.debug("디버그 메시지")

# 파일 저장 활성화 (기본은 비활성화)
# logs/YYYY/MM/DD/YYYYMMDD_HHMMSS.log 에 기록되며, 같은 프로세스의 로거들이 파일을 공유
logger = get_logger(enable_file_write=True, log_dir="logs")
  • name: 로거 이름. 생략(None)하면 LOGGER_NAME 환경 변수 → 호출자 모듈명 순으로 자동 결정. 이름 없는(anonymous) 로거가 필요하면 name=""을 명시적으로 전달.
  • level: 로그 레벨, int 또는 문자열 (기본: INFO)
  • tz: 타임스탬프에 적용할 타임존 (기본: Asia/Seoul)
  • enable_file_write: 파일 저장 활성화 여부 (기본: False)
  • log_dir: 파일 저장 활성화 시 사용할 기준 디렉토리 (기본: "logs")
  • enable_file / enable_fnc / enable_line: 로그를 호출한 소스 파일명/함수명/라인 번호 표시 여부 (셋 다 미지정 시 기본: True, 하나라도 명시하면 나머지는 False로 취급). 활성화된 항목은 파일명:함수명:라인번호 순으로 (...) 안에 연결되어 출력되며, 파일명-함수명 사이는 ::(콜론 2개), 그 외 조합은 :(콜론 1개)로 구분한다. 활성화된 항목이 하나뿐이면 구분자 없이 출력된다 (예: (main.py::run:10), (main.py:10), (run), (10)).

level을 제외한 각 인자를 생략하면 아래 환경 변수(.env 포함, python-dotenv 설치 시)를 우선 사용합니다. 명시적으로 전달한 인자는 항상 환경 변수보다 우선합니다.

환경 변수 대응 인자
LOGGER_NAME name
LOGGER_LEVEL level
LOGGER_TZ tz
LOGGER_ENABLE_FILE_WRITE enable_file_write
LOGGER_LOG_DIR log_dir
LOGGER_ENABLE_FILE enable_file
LOGGER_ENABLE_FNC enable_fnc
LOGGER_ENABLE_LINE enable_line

2. Pandas Extension (helper_pandas)

DataFrame과 Series에 한글 컬럼 설명 기능을 추가합니다.

from helper_dev_utils import set_pandas_extension
import pandas as pd

# Pandas 확장 등록
set_pandas_extension()

# DataFrame 생성
df = pd.DataFrame({
    'name': ['Alice', 'Bob', 'Charlie'],
    'age': [25, 30, 35],
    'city': ['Seoul', 'Busan', 'Incheon']
})

# 컬럼 설명 추가 (개별)
df.set_head_att('name', '사용자 이름')
df.set_head_att('age', '나이')
df.set_head_att('city', '거주 도시')

# 컬럼 설명 추가 (딕셔너리)
df.set_head_att({
    'name': '사용자 이름',
    'age': '나이',
    'city': '거주 도시'
})

# 한글 컬럼명과 함께 출력
df.head_att()
# 출력:
# 사용자 이름    나이  거주 도시
# name          age   city
# Alice          25   Seoul
# Bob            30   Busan
# Charlie        35   Incheon

# 또는 head() 메서드 오버라이드 사용 (enable_head_override=True일 때)
df.head()

# 다양한 출력 형식
df.head_att(rows=10)              # 10행 출력
df.head_att(rows='all')           # 전체 출력
df.head_att(out='html')           # HTML 형태로 출력
df.head_att(out='str')            # 문자열로 반환

# 컬럼 설명 조회
print(df.get_head_att('name'))    # 출력: 사용자 이름
print(df.get_head_att())          # 전체 딕셔너리 출력

# 컬럼 설명 삭제
df.remove_head_att('age')         # 단일 삭제
df.remove_head_att(['name', 'city'])  # 여러 개 삭제
df.clear_head_att()               # 전체 초기화

3. Print Utilities (helper_utils_print)

디렉토리, JSON, 딕셔너리를 트리 구조로 출력합니다.

from helper_dev_utils import print_dir_tree, print_json_tree, print_dic_tree

# 디렉토리 트리 출력
print_dir_tree('/path/to/directory', max_depth=3)

# JSON/딕셔너리 트리 출력 (파이프 스타일)
data = {
    'users': [
        {'name': 'Alice', 'age': 25},
        {'name': 'Bob', 'age': 30}
    ],
    'config': {'debug': True}
}
print_json_tree(data, max_depth=5, max_list_items=10)

# 딕셔너리 트리 출력 (박스 드로잉 스타일)
print_dic_tree(data, max_depth=5, show_values=True)

4. Colab/Path Utilities (helper_utils_colab)

로컬 및 Google Colab 환경에서 경로를 자동으로 관리합니다.

from helper_dev_utils import my_driver, my_cache

# Google Drive 경로 가져오기 (Colab에서 자동 마운트)
drive_path = my_driver()
print(drive_path)  # /content/drive/MyDrive (Colab) 또는 로컬 경로

# 캐시 디렉토리 가져오기 (OS별 자동 탐색)
cache_path = my_cache()
print(cache_path)  # ~/.cache (Linux/Mac) 또는 로컬 경로

# 하위 경로 지정
model_cache = my_cache('models/bert')
data_drive = my_driver('datasets/images')

환경변수 우선 지원:

MY_DRIVER_PATH=/custom/drive/path
MY_CACHE_PATH=/custom/cache/path

5. Help Utilities (helper_help)

함수·메서드의 시그니처와 docstring을 출력하고, 모듈에서 이름으로 함수를 검색합니다.

from helper_dev_utils import helper_help, helper_search
import pandas as pd
import matplotlib.pyplot as plt

# 함수 도움말 출력 (시그니처 + docstring)
helper_help(pd.DataFrame.groupby)
helper_help(plt.plot)

# 출력 예시:
# Signature : DataFrame.groupby(self, by=None, ...)
# Docstring :
# Group DataFrame using a mapper or by a Series of columns.
# ...
# 모듈에서 이름에 query가 포함된 함수 검색
helper_search(pd, "merge")
# 출력:
# [pandas] 'merge' 검색 결과 (3건)
#   - merge
#   - merge_asof
#   - merge_ordered

# query=None 이면 전체 목록 출력
helper_search(pd)
함수 설명
helper_help(fdn) 함수/메서드의 시그니처와 docstring 출력
helper_search(lbn, query=None) 모듈 내 함수/클래스 중 이름에 query가 포함된 항목 출력. query 생략 시 전체 목록

6. Google Colab 인증 및 Drive 관리 (helper_colab_auth / helper_google_driver)

Google Colab 환경에서 사용자 인증, Secrets 조회, Drive 마운트 상태 확인, 경로 관리, 휴지통 비우기를 지원합니다. Colab이 아닌 환경에서는 google_authenticate()/empty_drive_trash()RuntimeError를 발생시키고, google_is_drive_mounted()False를 반환합니다.

from helper_dev_utils import (
    google_authenticate,
    google_get_secret,
    google_is_drive_mounted,
    google_driver,
    google_driver_path,
    empty_drive_trash,
)

# Google 서비스 인증 (Colab 전용)
creds, project_id = google_authenticate()
# PyDrive2, gspread, googleapiclient 등 인증이 필요한 라이브러리와 함께 사용

# Colab Secrets(등록된 값)에서 비밀값 조회, 없으면 환경변수로 폴백
api_key = google_get_secret('OPENAI_API_KEY')
db_pass = google_get_secret('DB_PASSWORD', default='')

# Drive 마운트 상태 확인
if google_is_drive_mounted():
    print("Drive가 마운트되어 있습니다")

# Drive 루트 경로 가져오기 (Colab에서는 자동 마운트 후 경로 반환)
drive_path = google_driver()
print(drive_path)  # /content/drive/MyDrive (Colab) 또는 로컬 경로

# 루트 하위 경로 결합 (기본적으로 디렉토리를 생성하고 존재를 검증)
data_path = google_driver_path('datasets', 'images')
print(data_path)

# Drive 휴지통 비우기 (Colab 전용, google-api-python-client 필요)
result = empty_drive_trash(force=True)
print(result['message'])
함수 설명
google_authenticate(scopes=None, force=False) Colab 사용자 인증 수행, (credentials, project_id) 반환
google_get_secret(key, default=None, fallback_env=True) Colab Secrets에서 값 조회, 없으면 환경변수로 폴백
google_is_drive_mounted(mount_point='/content/drive') Drive 마운트 여부 반환
google_driver(google_driver_local=None, google_driver_colab=None, auto_mount=True) 환경에 맞는 Drive 루트 경로 반환 (Colab은 자동 마운트)
google_driver_path(*subpaths, create=True, validate=True, allow_escape=False, ...) google_driver() 루트에 하위 경로를 결합한 절대 경로 반환
empty_drive_trash(force=False) Drive 휴지통 비우기. force=False면 실제로 비우지 않고 확인 메시지만 반환

empty_drive_trashgoogle-api-python-client가 필요합니다: pip install helper-dev-utils[google]

로컬/Colab 루트 경로 통일 (google_driver_local / google_driver_colab)

같은 노트북·스크립트를 로컬 PC와 Colab에서 코드 수정 없이 그대로 돌리기 위한 경로 추상화입니다. "로컬에서는 이 폴더, Colab에서는 이 폴더를 Drive 루트로 써라"를 한 번 등록해두면, 이후 google_driver_path()는 실행 환경을 자동으로 판별해 그에 맞는 루트 밑에 경로를 만들어줍니다.

  • google_driver_local: 로컬 환경에서 사용할 루트 (예: Google Drive 데스크톱 앱 동기화 폴더). 생략 시 helper_path_finder.find_google_drive()가 자동 탐색한 경로가 기본값으로 사용됩니다.
  • google_driver_colab: Colab 환경에서 사용할 루트 (기본값 /content/drive/MyDrive).
  • 두 값 모두 google_driver()/google_driver_path() 호출 시 한 번만 넘기면 모듈에 캐시되어, 이후 인자 없이 호출해도 계속 재사용됩니다.
from helper_dev_utils import google_driver, google_driver_path

# 루트를 한 번 등록 (프로젝트 시작 시 1회만 호출하면 됨)
google_driver(
    google_driver_local="D:/my_drive_sync/MyDrive",   # 로컬 PC의 Drive 동기화 폴더
    google_driver_colab="/content/drive/MyDrive",      # Colab 마운트 경로 (기본값과 동일해도 명시 가능)
)

# 이후로는 환경을 신경 쓰지 않고 상대 경로만 지정
# 로컬: D:/my_drive_sync/MyDrive/project/dataset/train.csv
# Colab: /content/drive/MyDrive/project/dataset/train.csv
train_csv = google_driver_path("project", "dataset", "train.csv", create=False)

# 여러 곳에서 동일한 루트를 계속 사용 (재등록 불필요)
model_dir = google_driver_path("project", "models")       # 디렉토리 자동 생성
log_dir = google_driver_path("project", "logs")

google_driver_local/google_driver_colab으로 "환경별 루트"를 등록하고, google_driver_path는 그 루트를 기준으로 하위 경로를 조립·생성·검증해 로컬/Colab 어디서 실행되든 동일한 상대 경로 인터페이스를 제공합니다.

자동 마운트 제어 (auto_mount)

google_driver_local/google_driver_colab이 "어떤 경로를 쓸지" 등록하는 인자라면, auto_mount는 그와 별개로 Colab에서 Drive를 지금 실제로 마운트할지를 결정하는 인자입니다 (기본값 True).

  • auto_mount=True (기본): Colab 환경에서 google_driver()/google_driver_path()를 호출하는 순간 자동으로 drive.mount()를 시도합니다. 이미 마운트돼 있으면 건너뛰고, 아니면 그 자리에서 Colab 인증 팝업이 뜹니다.
  • auto_mount=False: 마운트를 시도하지 않고 등록된 경로 문자열만 반환합니다. 아직 파일 접근이 필요 없는 시점(예: 초기 설정 단계에서 경로 문자열만 미리 구성)에 마운트 팝업이 뜨는 걸 피하고 싶을 때 사용합니다.
# 경로 문자열만 미리 구성 — 마운트 팝업을 띄우지 않음
path = google_driver(auto_mount=False)

# ... 다른 초기화 작업 ...

# 실제로 파일이 필요한 시점에 호출하면 그때 마운트됨 (auto_mount 기본값 True)
train_csv = google_driver_path("project", "dataset", "train.csv")

의존성

필수 의존성

  • matplotlib >= 3.2.0
  • numpy >= 1.16.0
  • pandas >= 1.0.0
  • backports.zoneinfo >= 0.2.1 (Python < 3.9 에서만; 3.9+ 는 표준 라이브러리 zoneinfo 사용)

선택적 의존성

  • python-dotenv >= 0.19.0 - .env 파일 지원
  • IPython >= 7.0.0 - Jupyter/Colab 지원
  • torch >= 1.0.0 - PyTorch Tensor 지원
  • google-api-python-client >= 2.0.0 - empty_drive_trash() (Colab 전용)

개발 및 테스트

개발 환경 설정

# 저장소 클론
git clone https://github.com/c0z0c-helper/helper_dev_utils.git
cd helper_dev_utils

# 개발 의존성 설치
pip install -r requirements-dev.txt

# 편집 가능 모드로 설치
pip install -e .

테스트 실행

# 전체 테스트 실행
pytest tests -v

# 특정 테스트 파일 실행
pytest tests/test_helper_logger.py -v
pytest tests/test_helper_utils_colab.py -v

# 커버리지 포함 실행
pytest tests --cov=helper_dev_utils --cov-report=html

테스트를 실행하면 tests/conftest.py가 결과를 자동으로 수집하여 tests/report/YYYYMMDD_HHMMSS.md에 통과/실패/스킵 여부가 포함된 표 형태의 리포트를 생성합니다.

테스트 환경 설정

테스트에서 helper_utils_colab 함수를 검증하려면 .env.test 파일을 사용합니다:

  1. .env.test 파일을 프로젝트 루트에 생성 (이미 샘플이 제공됨)
  2. 테스트용 캐시 및 드라이버 경로 설정:
# Windows
MY_CACHE_LOCAL=C:/Users/YOUR_USERNAME/AppData/Local/Temp/helper_dev_utils_test_cache
MY_DRIVER_PATH=C:/Users/YOUR_USERNAME/AppData/Local/Temp/helper_dev_utils_test_driver

# Linux/macOS
# MY_CACHE_LOCAL=/tmp/helper_dev_utils_test_cache
# MY_DRIVER_PATH=/tmp/helper_dev_utils_test_driver

conftest.py가 자동으로 .env.test를 로드하여 테스트 실행 전 환경을 설정합니다.

라이선스

MIT License - 자세한 내용은 LICENSE 파일을 참조하세요.

기여

이슈 리포트 및 풀 리퀘스트는 GitHub Repository에서 환영합니다!

작성자

c0z0c - c0z0c.dev@gmail.com

관련 라이브러리


버전 히스토리

0.7.0

  • helper_logger: get_loggerenable_fnc 옵션 추가 — 로그를 호출한 함수명을 출력할 수 있다. enable_file/enable_fnc/enable_line 중 활성화된 항목만 (파일명::함수명:라인번호) 형태로 연결되어 출력되며(파일명-함수명 사이는 ::, 그 외 조합은 :), 하나만 활성화되면 구분자 없이 출력된다.

0.6.7

  • 코랩 설치 세션 리셋 수정 (2026-08-06)

0.6.6

  • helper_logger: get_loggername 자리에 로그 레벨(int 또는 "DEBUG"/"INFO" 등 문자열)을 전달하면 자동으로 level로 인식하도록 개선

0.6.5

  • get_logger()가 더 이상 load_dotenv를 자동 호출하지 않음 — .env 로딩은 호출자(외부 코드) 책임으로 이관. 패키지 레벨 DOTENV_AVAILABLE export도 제거됨.

0.6.4

  • get_aoto_logger (제거)
  • get_logger 통합 .env 적용

0.6.3

  • print_xxx_tree 오류 버그 수정

0.6.2

  • print_xxx_tree 의 출력 설정 가능

0.6.1

  • PEP 561 py.typed 적용

0.6.0

  • helper_logger: 콘솔(+선택적 파일) 출력을 위한 최소 구현으로 리팩토링. 회전 로깅/중앙집중 파일/.env 우선순위 시스템/reconfigure_logger/sample_logger_env를 제거하고 get_logger, get_auto_logger만 유지
  • helper_logger: 레벨 축약을 %(levelname).1s 포맷으로 단순화, tz 인자로 타임존 설정 가능(기본 Asia/Seoul)
  • helper_logger: file(기본 False)/log_dir(기본 "logs") 옵션 추가 — 활성화 시 {log_dir}/YYYY/MM/DD/YYYYMMDD_HHMMSS.log에 기록되며 같은 프로세스의 로거들이 파일을 공유
  • __init__.py: sample_logger_env, reconfigure_logger 패키지 레벨 노출 제거
  • tests: conftest.py에 pytest 훅 추가 — 테스트 실행 시 tests/report/YYYYMMDD_HHMMSS.md에 결과 표 자동 생성

0.5.10

  • helper_utils_print: set_print_tree() / set_log_tree() 함수 추가 - 트리 출력 시 print 또는 logger.info 전환 가능
  • helper_utils_print: print_json_tree, print_dic_treemax_depth, list_count 기본값을 None(무한대)으로 변경
  • __init__.py: set_print_tree, set_log_tree 패키지 레벨 노출 추가
  • tests: test_helper_utils_colab.py 실제 API(google_driver, google_driver_path, cache, cache_path)에 맞게 수정
  • tests: test_helper_utils_print.pyset_print_tree/set_log_tree 전환 및 None 기본값 테스트 추가 (총 31개)

0.5.9

  • helper_help: 함수/메서드 시그니처 및 docstring 출력 기능 추가
  • helper_search: 모듈 내 함수·클래스 이름 기반 검색 기능 추가

0.5.8

  • helper_cache: 캐시 유틸리티 모듈 추가
  • helper_colab_auth: Google 인증 관련 함수 추가 (google_authenticate, google_get_secret, google_is_drive_mounted)

0.5.7 이하

  • helper_logger: 로깅 유틸리티 초기 구현 및 환경변수 기반 설정 지원
  • helper_pandas: Pandas 확장 기능 (한글 컬럼 설명, head_att, show 등)
  • helper_utils_print: print_dir_tree, print_json_tree, print_dic_tree 구현
  • helper_utils_colab: 로컬/Colab 환경 경로 자동 탐색 구현

Release files for helper-dev-utils 0.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for helper-dev-utils 0.7.0
File Size Uploaded
helper_dev_utils-0.7.0.tar.gz 52.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for helper-dev-utils 0.7.0
File Interpreter ABI Platform
helper_dev_utils-0.7.0-py3-none-any.whl Python 3 none any Details

Total release size: 93.4 kB

Release files / helper_dev_utils-0.7.0.tar.gz

Download URL helper_dev_utils-0.7.0.tar.gz
Size 52.2 kB
Tags Source
SHA-256 checksum
How to use checksums
5fc6f6cf78c518b86c60b1df092e75e06ff1e6e91aa26b275c3fa3a2e5773873
BLAKE2b-256 checksum
How to use checksums
2554b77a12aaebe7d82c2fa3a8fa59af84e0259f6ba3a21539c7fc3ce5fb4f0f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.20

Release files / helper_dev_utils-0.7.0-py3-none-any.whl

Download URL helper_dev_utils-0.7.0-py3-none-any.whl
Size 41.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0bb0a799c35e5f8ee1d020ebf91745398eb8282ac5f56f428c6e51e62bdf1bb2
BLAKE2b-256 checksum
How to use checksums
d22602283afd378cf0d58999e70e3f006d86368f5229ca41c642f2753b193b55
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.20

Release history Release notifications | RSS feed

This release

0.7.0 This release

2 release files

0.6.7

2 release files

0.6.6

2 release files

0.6.5

2 release files

0.6.4

2 release files

0.6.3

2 release files

0.6.2

2 release files

0.6.1

2 release files

0.6.0

2 release files

0.5.10

2 release files

0.5.9

2 release files

0.5.8

2 release files

0.5.7

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page