본문 바로가기
목차
CE

TOML 파일: 설정파일 형식

by ds31x 2026. 4. 10.
728x90
반응형

Overview

TOML(Tom's Obvious, Minimal Language)은 설정 파일(configuration file)을 위해 설계된 문서 형식임.

  • 단순함과 명확함을 최우선으로 설계됨
  • 대표 사용처:
    • Python의 pyproject.toml,
    • Rust의 Cargo.toml,
    • 각종 CLI 도구 설정

다음은 한국어로 지원되는 공식 문서 URL임:

https://toml.io/ko/v1.0.0

 

TOML: 한국어 v1.0.0

1/11/2021 에 게시됨 – 텍스트 버전 TOML v1.0.0 Tom's Obvious, Minimal Language. By Tom Preston-Werner, Pradyun Gedam, et al. 목표 TOML은 명확한 의미를 가져 읽기 쉬운 최소한의 구성 파일 포맷을 목표로 합니다. TOML은

toml.io

 

다른 형식과 비교 (Comparison)

형식 장점 단점
JSON 구조가 엄격하고 명확 주석 불가, 사람이 직접 편집하기 불편
YAML 유연하고 간결 들여쓰기 민감, 실수 발생 빈도 높음
TOML 설정 파일에 최적화, 가독성 우수 복잡한 데이터 표현에는 부적합

 

JSON과 YAML에 대해선 다음을 참고:


기본 문법 (Basic Syntax)

key = value

TOML의 핵심 구조는 key = value 형태임.

title   = "My App"   # string(문자열)
version = "1.0.0"    # string
debug   = true       # boolean(불리언)
port    = 8080       # integer(정수)

자료형 (Data Types)

문자열 (String)

  • 큰따옴표("): escape sequence 해석 가능
  • 작은따옴표('): raw string, 역슬래시 그대로 유지
line_break = "Hello\nWorld"   # 줄바꿈 처리됨
raw_text   = 'Hello\nWorld'   # \n 그대로 유지됨
win_path   = 'C:\temp\folder' # 경로 표기 시 유용

숫자 (Number)

count       = 10
temperature = 36.5
big_number  = 1_000_000  # 가독성을 위한 _ 구분자 사용 가능

불리언 (Boolean)

enabled = true
visible = false

반드시
소문자 (truefalse)로 작성해야 함.


날짜/시간 (Date / Datetime)

birthday     = 2026-04-10
meeting_time = 2026-04-10T14:30:00

배열 (Array)

  • 대괄호 [] 사용
  • 같은 타입끼리 묶는 것 이 원칙
ports = [8080, 8443]
names = ["Alice", "Bob", "Charlie"]
flags = [true, false, true]

타입이 혼합된 배열(mixed = [1, "hello", true])은
문법상 허용되더라도 실무에서는 사용하지 않길 적극 권함.


Table

관련 설정을 섹션(section)으로 묶는 구조임.

[server]
host = "0.0.0.0"
port = 8000

[database]
host = "localhost"
port = 5432
  • database.host, database.port 처럼 네임스페이스(namespace) 를 형성함
  • 서로 다른 목적의 설정을 분리할 때 유용함

중첩 Table (Nested Table)

.으로 하위 섹션 정의

[server]
host = "127.0.0.1"

[server.security]
use_ssl   = true
cert_file = "server.crt"

중첩을 3단계 이상 사용하지 말 것:
이 경우 읽기가 매우 어려워짐.
꼭 필요한 범위까지만 사용 권장.


Inline Table

Table 내 항목이 적은 경우 한 줄로 표현 가능

admin = { name = "Alice", email = "alice@example.com" }

Array of Tables

같은 구조의 항목이 여러 개 반복될 때 사용하는 구조.

다음과 같이 [[...]] 문법을 사용함.

[[servers]]
name = "web-1"
ip   = "192.168.0.10"

[[servers]]
name = "web-2"
ip   = "192.168.0.11"
  • servers라는 이름의 table 배열이 생성됨
  • 학생 목록, 서버 목록, 플러그인 목록 등에 적합

주석 (Comment)

# 을 이용.

# 서버 설정
port  = 8080
debug = true  # 개발 중에는 true

자주 하는 실수 (Common Mistakes)

1. 같은 key 중복 정의: 오류

# 잘못된 예
name = "Alice"
name = "Bob"

2. key를 값으로 쓰다가 table로 재사용: 충돌

# 잘못된 예
user = "Alice"

[user]       # 이미 문자열로 정의된 user를 table로 재사용 → 충돌
age = 30

3. 문자열에 따옴표 누락

name = Alice    # 오류: 문자열은 반드시 따옴표 필요
name = "Alice"  # 올바른 표기

Examples

pyproject.toml (Python)

[project]
name            = "my-package"
version         = "0.1.0"
requires-python = ">=3.10"

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts   = "-v"

Cargo.toml (Rust)

[package]
name    = "hello_toml"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = "1.0"
toml  = "0.8"

.gemini/commands/test/gen.toml

# 파일 위치: ~/.gemini/commands/test/gen.toml
# 호출 방법: /test:gen "로그인 버튼 클릭 시 인증 처리 테스트"

description = "Generates a unit test based on a requirement description."

prompt = """
You are an expert test engineer.
Based on the following requirement, write a comprehensive unit test using pytest.

Requirement:
{{args}}

Your response must include:
1. Complete test code with fixtures and assertions.
2. Brief explanation of the test strategy.
"""
  • gemini-cli에 custom command를 추가할 때도 toml 파일을 사용.
  • custom commnad에서 {{args}} placeholder를 사용하면 사용자가 명령 뒤에 입력한 텍스트가 그 위치에 그대로 주입됨.

종합 예제 (Full Example)

title   = "Example App"
version = "1.0.0"
debug   = true
tags    = ["web", "api"]

[server]
host = "127.0.0.1"
port = 8080

[database]
engine = "postgresql"
host   = "localhost"
port   = 5432

[database.pool]
min_size = 1
max_size = 10

admin = { name = "Alice", email = "alice@example.com" }

[[plugins]]
name    = "auth"
enabled = true

[[plugins]]
name    = "logging"
enabled = false

이 예제 하나에
TOML의 핵심 문법이 모두 포함되어 있음.


반드시 익혀야 할 핵심 5가지

우선순위 문법 형태
1 key-value key = value
2 배열 key = [...]
3 table [section]
4 중첩 table [section.sub]
5 array of tables [[items]]

참고: 관련 도구들

https://codeshack.io/toml-formatter-validator/

 

TOML Formatter & Validator - Free Online Tool

Easily format, beautify, and validate your TOML configuration files. Our free online tool provides instant, real-time syntax checking and pretty-printing.

codeshack.io

문법 오류 위치 등을 확인 가능한 온라인 검증 사이트임.

 

tomplo

pip로 설치하는 Rust 기반 CLI 도구.

pip install taplo
taplo check config.toml

 

 

tomllib (Python 3.11+)

Python 3.11부터 표준 라이브러리에 포함된 것으로 TOML파일을 읽어들임.

import tomllib

with open("config.toml", "rb") as f:
    try:
        data = tomllib.load(f)
        print("Valid TOML:", data)
    except tomllib.TOMLDecodeError as e:
        print("Invalid TOML:", e)

읽기만 가능.

 

tomli-w (third pary module)

다음의 명령어로 설치: pip install toml-w

다음과 같이 dict 객체를 toml로 저장:

import tomli_w

data = {
    "server": {"host": "127.0.0.1", "port": 8080},
    "debug": True
}

with open("config.toml", "wb") as f:
    tomli_w.dump(data, f)

같이 보면 좋은 자료들

2025.08.06 - [CE] - [Term] Serialization-Data Exchanged Format

 

[Term] Serialization-Data Exchanged Format

Serialization의 일반적 의미메모리 객체 및 데이터를저장/전송 가능한 형태로변환하는 일반적인 개념메모리의 객체/데이터 구조를 "저장/전송 가능한 형태"로 변환하는 과정컴퓨터 메모리에 흩어

ds31x.tistory.com

 

2025.04.06 - [utils] - [Tool] Builder System (or Packaging System)

 

[Tool] Builder System (or Packaging System)

빌더 시스템이란?빌더 시스템은 소스 코드들을 실행 파일 또는 라이브러리로 만들어주는 자동화된 처리 과정을 담당하는 도구를 가리킴.소스 코드를 실행 가능한 프로그램 또는 라이브러리 (or

ds31x.tistory.com

 

2026.03.26 - [개발환경] - Gemini-cli: Custom Slash Command 만들기

 

Gemini-cli: Custom Slash Command 만들기

이 문서는Gemini CLI에서슬래시(/)로 시작하는 custom slash command 정의하고 사용하는 방법을 기술.1. OverviewCustom slash command 를 추가하면복잡한 프롬프트를 짧은 명령어로 저장해 두고 필요할 때마다 호

ds31x.tistory.com

 

2025.12.21 - [Python] - PyPI에 wheel을 업로드하기

 

PyPI에 wheel을 업로드하기

0. 전체 workflow 개요PyPI에 wheel을 업로드하는 과정은 다음 단계로 구성됨.PyPI account 생성project metadata 준비wheel build 수행upload tool 준비PyPI로 upload 수행각 단계는 독립적으로 수행됨. 1-3 은 다음을 참

ds31x.tistory.com

 

728x90

'CE' 카테고리의 다른 글

[CE] Routine 이란  (1) 2026.06.11
OS Platform and CPU Architecture  (0) 2026.05.24
동기 처리 및 비동기 처리  (1) 2026.04.10
CE: Independent vs Agnostic  (0) 2026.03.17
Machine 이란?  (0) 2026.03.03