toml-python
БесплатноБез исполняемых скриптовНе проверенWhen reading or writing pyproject.toml or .toml config files in Python. When editing TOML while preserving comments and formatting. When designing…
Об этом скилле
TOML Python Integration
Work with TOML configuration files using the tomlkit library, which preserves comments and formatting during read-modify-write cycles.
When to Use This Skill
Use this skill when:
- Reading or writing TOML configuration files (config.toml, pyproject.toml)
- Modifying existing TOML files while preserving comments and formatting
- Parsing TOML into Python data structures
- Creating TOML documents programmatically
- Handling TOML syntax errors and validation
- Implementing config file management for Python applications
- Working with XDG Base Directory specification for config locations
Core Capabilities
Library Selection: tomlkit vs tomllib
Use tomlkit when:
- Modifying existing config files (preserves comments and formatting)
- Building applications that write configuration
- Need single library for both reading and writing
- Python 3.8+ compatibility required
Use tomllib (stdlib) when:
- Python 3.11+ only
- Read-only access sufficient (no writing capability)
- Minimal dependencies preferred
For config file management, tomlkit is the recommended choice.
Installation
# Using uv (recommended)
uv add tomlkit
# Using pip
pip install tomlkit
Requirements: Python >=3.8, tomlkit >=0.12.0
tomlkit API Reference
Reading TOML
import tomlkit
# From string
doc = tomlkit.parse(toml_string)
doc = tomlkit.loads(toml_string) # Alias for parse()
# From file object
with open('config.toml', 'r') as f:
doc = tomlkit.load(f)
# Using TOMLFile class (convenient)
from tomlkit import TOMLFile
toml_file = TOMLFile('config.toml')
doc = toml_file.read()
Returns: TOMLDocument object (dict-like, preserves formatting)
Writing TOML
import tomlkit
# To string
toml_string = tomlkit.dumps(data)
# To file object
with open('config.toml', 'w') as f:
tomlkit.dump(data, f)
# Using TOMLFile class
from tomlkit import TOMLFile
toml_file = TOMLFile('config.toml')
toml_file.write(doc)
Creating TOML Documents
from tomlkit import document, table, comment, nl, array, inline_table
# Create document
doc = document()
doc.add(comment("Configuration file"))
doc.add(nl())
doc.add("title", "My Config")
# Create table
db_config = table()
db_config["host"] = "localhost"
db_config["port"] = 5432
doc["database"] = db_config
# Create inline table
point = inline_table()
point.update({'x': 1, 'y': 2})
doc["point"] = point
# Create array
numbers = array()
numbers.extend([1, 2, 3])
doc["numbers"] = numbers
Document Manipulation
# Dict-like access
doc["section"]["key"] = "value"
value = doc["section"]["key"]
# Get with default
value = doc.get("key", "default")
# Check existence
if "key" in doc:
pass
# Iterate
for key, value in doc.items():
print(key, value)
# Remove key
doc.pop("key")
doc.remove("key")
# Convert to pure Python dict
pure_dict = doc.unwrap()
# Get as TOML string
toml_str = doc.as_string()
Value Creation Helpers
from tomlkit import (
item, # Auto-detect type
string, # String with options
integer, # Integer
float_, # Float
boolean, # Boolean
datetime, # Datetime
date, # Date
time, # Time
)
# Auto-detect type
doc["key"] = item(42)
doc["key"] = item([1, 2, 3])
doc["key"] = item({'nested': 'table'})
# Explicit string types
doc["basic"] = string("text")
doc["literal"] = string("text", literal=True) # Single quotes
doc["multiline"] = string("line1\nline2", multiline=True)
Error Handling
Exception Types
from tomlkit.exceptions import (
TOMLKitError, # Base exception
ParseError, # Syntax errors (has .line and .col)
NonExistentKey, # Missing key access
KeyAlreadyPresent, # Duplicate key
ConvertError, # Type conversion failure
)
# Handle parse errors
try:
doc = tomlkit.parse(toml_string)
except ParseError as e:
print(f"Parse error at line {e.line}, column {e.col}: {e}")
# Handle missing keys
try:
value = doc["nonexistent"]
except (KeyError, NonExistentKey):
value = "default"
# Handle file not found
try:
with open('config.toml', 'r') as f:
doc = tomlkit.load(f)
except FileNotFoundError:
# Create default config
doc = create_default_config()
Common Patterns
Pattern 1: Load or Create Config
import tomlkit
from pathlib import Path
def load_or_create_config(path: Path) -> tomlkit.TOMLDocument:
"""Load existing config or create default if missing."""
if path.exists():
with open(path, 'r') as f:
return tomlkit.load(f)
# Create default
doc = tomlkit.document()
doc.add(tomlkit.comment("Default configuration"))
doc.add(tomlkit.nl())
doc["app"] = tomlkit.table()
doc["app"]["name"] = "myapp"
doc["app"]["version"] = "1.0.0"
path.parent.mkdir(parents=True, exis
Установить toml-python в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл toml-python?
When reading or writing pyproject.toml or .toml config files in Python. When editing TOML while preserving comments and formatting. When designing configuration file format for a Python tool. When code uses tomlkit or tomllib. When implementing atomic config file updates.
Как установить скилл toml-python?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл toml-python запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic