or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-types.mddocument-operations.mderror-handling.mdfile-operations.mdindex.mditem-classes.mditem-creation.md

index.mddocs/

0

# TOML Kit

1

2

A 1.0.0-compliant TOML library for Python that preserves all comments, indentations, whitespace and internal element ordering while making them accessible and editable via an intuitive API. TOML Kit enables programmatic modification of TOML files while preserving their original formatting and structure.

3

4

## Package Information

5

6

- **Package Name**: tomlkit

7

- **Language**: Python

8

- **Installation**: `pip install tomlkit`

9

10

## Core Imports

11

12

```python

13

import tomlkit

14

```

15

16

For direct access to main functions:

17

18

```python

19

from tomlkit import parse, loads, load, dumps, dump, document

20

```

21

22

For creating TOML items:

23

24

```python

25

from tomlkit import integer, float_, boolean, string, array, table, inline_table

26

```

27

28

For file operations:

29

30

```python

31

from tomlkit.toml_file import TOMLFile

32

```

33

34

## Basic Usage

35

36

```python

37

import tomlkit

38

39

# Parse existing TOML content

40

content = '''

41

# This is a TOML document

42

title = "Example"

43

44

[database]

45

server = "192.168.1.1"

46

ports = [ 8001, 8001, 8002 ]

47

'''

48

49

doc = tomlkit.parse(content)

50

print(doc["title"]) # "Example"

51

52

# Modify while preserving formatting

53

doc["title"] = "Updated Example"

54

doc["database"]["ports"].append(8003)

55

56

# Output preserves original formatting

57

print(doc.as_string())

58

59

# Create new TOML document from scratch

60

doc = tomlkit.document()

61

doc["title"] = "New Document"

62

doc["server"] = {"host": "localhost", "port": 8080}

63

print(tomlkit.dumps(doc))

64

```

65

66

## Architecture

67

68

TOML Kit uses a layered architecture that separates parsing, item representation, and formatting:

69

70

- **Parser**: Converts TOML text into structured document with full formatting preservation

71

- **Items**: Type-safe representations of TOML values (Integer, String, Table, Array, etc.)

72

- **Container**: Dict-like interface for organizing and accessing TOML items

73

- **Trivia**: Metadata that captures whitespace, comments, and formatting details

74

- **TOMLDocument**: Top-level container that can be serialized back to formatted TOML

75

76

This design enables round-trip parsing where input formatting is perfectly preserved while providing a familiar dict-like interface for programmatic access and modification.

77

78

## Capabilities

79

80

### Document Operations

81

82

Core functions for parsing TOML from strings/files and serializing back to TOML format, maintaining perfect formatting preservation.

83

84

```python { .api }

85

def parse(string: str | bytes) -> TOMLDocument: ...

86

def loads(string: str | bytes) -> TOMLDocument: ...

87

def load(fp: IO[str] | IO[bytes]) -> TOMLDocument: ...

88

def dumps(data: Mapping, sort_keys: bool = False) -> str: ...

89

def dump(data: Mapping, fp: IO[str], *, sort_keys: bool = False) -> None: ...

90

def document() -> TOMLDocument: ...

91

```

92

93

[Document Operations](./document-operations.md)

94

95

### Item Creation

96

97

Functions for creating individual TOML items (integers, strings, tables, etc.) with proper type representation and formatting control.

98

99

```python { .api }

100

def integer(raw: str | int) -> Integer: ...

101

def float_(raw: str | float) -> Float: ...

102

def boolean(raw: str) -> Bool: ...

103

def string(raw: str, *, literal: bool = False, multiline: bool = False, escape: bool = True) -> String: ...

104

def array(raw: str = "[]") -> Array: ...

105

def table(is_super_table: bool | None = None) -> Table: ...

106

def inline_table() -> InlineTable: ...

107

```

108

109

[Item Creation](./item-creation.md)

110

111

### Advanced Item Types

112

113

Specialized TOML types including dates/times, keys, and complex data structures with full TOML 1.0.0 compliance.

114

115

```python { .api }

116

def date(raw: str) -> Date: ...

117

def time(raw: str) -> Time: ...

118

def datetime(raw: str) -> DateTime: ...

119

def key(k: str | Iterable[str]) -> Key: ...

120

def value(raw: str) -> Item: ...

121

def aot() -> AoT: ...

122

```

123

124

[Advanced Types](./advanced-types.md)

125

126

### File Operations

127

128

High-level interface for reading and writing TOML files with automatic encoding handling and line ending preservation.

129

130

```python { .api }

131

class TOMLFile:

132

def __init__(self, path: StrPath) -> None: ...

133

def read(self) -> TOMLDocument: ...

134

def write(self, data: TOMLDocument) -> None: ...

135

```

136

137

[File Operations](./file-operations.md)

138

139

### Item Classes and Types

140

141

Core item classes representing different TOML value types, containers, and formatting elements with full type safety.

142

143

```python { .api }

144

class TOMLDocument(Container): ...

145

class Container: ...

146

class Bool: ...

147

class Integer: ...

148

class Float: ...

149

class String: ...

150

class Array: ...

151

class Table: ...

152

class InlineTable: ...

153

```

154

155

[Item Classes](./item-classes.md)

156

157

### Error Handling

158

159

Comprehensive exception hierarchy for parsing errors, validation failures, and runtime issues with detailed error reporting.

160

161

```python { .api }

162

class TOMLKitError(Exception): ...

163

class ParseError(ValueError, TOMLKitError): ...

164

class ConvertError(TypeError, ValueError, TOMLKitError): ...

165

class NonExistentKey(KeyError, TOMLKitError): ...

166

class KeyAlreadyPresent(TOMLKitError): ...

167

```

168

169

[Error Handling](./error-handling.md)

170

171

## Types

172

173

```python { .api }

174

# Type aliases for file paths

175

StrPath = Union[str, os.PathLike]

176

177

# Generic item type

178

Item = Union[Bool, Integer, Float, String, Date, Time, DateTime, Array, Table, InlineTable, AoT]

179

180

# Encoder function type

181

Encoder = Callable[[Any], Item]

182

183

# Document type

184

TOMLDocument = Container

185

```