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

item-classes.mddocs/

0

# Item Classes and Types

1

2

Core item classes representing different TOML value types, containers, and formatting elements with full type safety. These classes provide the foundation for TOML Kit's type system and formatting preservation.

3

4

## Capabilities

5

6

### Document and Container Classes

7

8

Top-level classes for managing TOML documents and organizing items.

9

10

```python { .api }

11

class TOMLDocument(Container):

12

"""

13

Main TOML document class that preserves formatting and structure.

14

Inherits all Container functionality with document-specific behavior.

15

"""

16

17

class Container:

18

"""

19

Base container for TOML items with dict-like interface.

20

"""

21

22

def unwrap(self) -> dict[str, Any]:

23

"""Convert to pure Python dict, losing formatting."""

24

25

def value(self) -> dict[str, Any]:

26

"""Get wrapped dict value with type conversion."""

27

28

def add(self, key: Key | Item | str, item: Item | None = None) -> Container:

29

"""Add item to container."""

30

31

def append(self, key: Key | Item | str, item: Item | None = None) -> Container:

32

"""Append item to container."""

33

34

def remove(self, key: Key | Item | str) -> Container:

35

"""Remove item from container."""

36

```

37

38

### Scalar Value Classes

39

40

Classes representing individual TOML scalar values with type safety and formatting preservation.

41

42

```python { .api }

43

class Bool:

44

"""Boolean TOML item (true/false)."""

45

46

def __init__(self, value: bool, trivia: Trivia): ...

47

48

@property

49

def value(self) -> bool:

50

"""Get the boolean value."""

51

52

class Integer:

53

"""Integer TOML item with arbitrary precision support."""

54

55

def __init__(self, value: int, trivia: Trivia, raw: str): ...

56

57

@property

58

def value(self) -> int:

59

"""Get the integer value."""

60

61

class Float:

62

"""Floating-point TOML item with precision preservation."""

63

64

def __init__(self, value: float, trivia: Trivia, raw: str): ...

65

66

@property

67

def value(self) -> float:

68

"""Get the float value."""

69

70

class String:

71

"""String TOML item with type and formatting control."""

72

73

def __init__(self, value: str, trivia: Trivia, raw: str, multiline: bool): ...

74

75

@property

76

def value(self) -> str:

77

"""Get the string value."""

78

79

@classmethod

80

def from_raw(cls, value: str, type_: StringType = None, escape: bool = True) -> String:

81

"""Create string with specific formatting type."""

82

```

83

84

### Date and Time Classes

85

86

Classes for TOML date, time, and datetime values with RFC3339 compliance.

87

88

```python { .api }

89

class Date:

90

"""TOML date item (YYYY-MM-DD format)."""

91

92

def __init__(self, year: int, month: int, day: int, trivia: Trivia, raw: str): ...

93

94

@property

95

def value(self) -> datetime.date:

96

"""Get the date value."""

97

98

class Time:

99

"""TOML time item with optional microseconds and timezone."""

100

101

def __init__(self, hour: int, minute: int, second: int, microsecond: int,

102

tzinfo: tzinfo | None, trivia: Trivia, raw: str): ...

103

104

@property

105

def value(self) -> datetime.time:

106

"""Get the time value."""

107

108

class DateTime:

109

"""TOML datetime item with timezone support."""

110

111

def __init__(self, year: int, month: int, day: int, hour: int, minute: int,

112

second: int, microsecond: int, tzinfo: tzinfo | None,

113

trivia: Trivia, raw: str): ...

114

115

@property

116

def value(self) -> datetime.datetime:

117

"""Get the datetime value."""

118

```

119

120

### Collection Classes

121

122

Classes for TOML arrays, tables, and array of tables with nested structure support.

123

124

```python { .api }

125

class Array:

126

"""TOML array with type preservation and formatting control."""

127

128

def __init__(self, value: list, trivia: Trivia): ...

129

130

def append(self, item: Any) -> None:

131

"""Add item to end of array."""

132

133

def extend(self, items: Iterable[Any]) -> None:

134

"""Add multiple items to array."""

135

136

def insert(self, index: int, item: Any) -> None:

137

"""Insert item at specific index."""

138

139

@property

140

def value(self) -> list:

141

"""Get the array as Python list."""

142

143

class Table:

144

"""TOML table with key-value pairs and nested structure."""

145

146

def __init__(self, value: Container, trivia: Trivia, is_aot_element: bool,

147

is_super_table: bool | None = None): ...

148

149

def append(self, key: str | Key, item: Item) -> Table:

150

"""Add key-value pair to table."""

151

152

@property

153

def value(self) -> dict:

154

"""Get table as Python dict."""

155

156

class InlineTable:

157

"""TOML inline table for single-line table representation."""

158

159

def __init__(self, value: Container, trivia: Trivia, new: bool = False): ...

160

161

def update(self, other: dict) -> None:

162

"""Update with key-value pairs from dict."""

163

164

@property

165

def value(self) -> dict:

166

"""Get inline table as Python dict."""

167

168

class AoT:

169

"""Array of Tables - TOML's [[table]] syntax."""

170

171

def __init__(self, body: list[Table]): ...

172

173

def append(self, item: Table | dict) -> None:

174

"""Add table to array of tables."""

175

176

@property

177

def value(self) -> list[dict]:

178

"""Get array of tables as list of dicts."""

179

```

180

181

### Key Classes

182

183

Classes for representing TOML keys including simple and dotted keys.

184

185

```python { .api }

186

class Key:

187

"""Base class for TOML keys."""

188

189

@property

190

def key(self) -> str:

191

"""Get the key as string."""

192

193

class SingleKey(Key):

194

"""Simple TOML key without dots."""

195

196

def __init__(self, key: str): ...

197

198

class DottedKey(Key):

199

"""Dotted TOML key for nested access."""

200

201

def __init__(self, keys: list[Key]): ...

202

203

@property

204

def keys(self) -> list[Key]:

205

"""Get the individual key components."""

206

```

207

208

### Formatting Classes

209

210

Classes for whitespace, comments, and formatting preservation.

211

212

```python { .api }

213

class Whitespace:

214

"""Whitespace item for formatting control."""

215

216

def __init__(self, value: str, fixed: bool = False): ...

217

218

@property

219

def value(self) -> str:

220

"""Get the whitespace string."""

221

222

class Comment:

223

"""Comment item with formatting preservation."""

224

225

def __init__(self, trivia: Trivia): ...

226

227

@property

228

def value(self) -> str:

229

"""Get the comment text."""

230

231

class Trivia:

232

"""Formatting metadata for items."""

233

234

def __init__(self, indent: str = "", comment_ws: str = "",

235

comment: str = "", trail: str = ""): ...

236

237

class Null:

238

"""Represents null/empty values in TOML structure."""

239

240

@property

241

def value(self) -> None:

242

"""Always returns None."""

243

```

244

245

### Type Enums and Constants

246

247

Enums and constants for TOML type classification.

248

249

```python { .api }

250

class StringType(Enum):

251

"""String type classification for TOML strings."""

252

253

BASIC = "basic" # "string"

254

LITERAL = "literal" # 'string'

255

MLB = "multiline_basic" # """string"""

256

MLL = "multiline_literal" # '''string'''

257

258

@classmethod

259

def select(cls, literal: bool, multiline: bool) -> StringType:

260

"""Select appropriate string type based on flags."""

261

```

262

263

### Custom Encoders

264

265

Functions for registering and managing custom encoders to extend TOML Kit's type conversion capabilities.

266

267

```python { .api }

268

def register_encoder(encoder: Encoder) -> Encoder:

269

"""

270

Register a custom encoder function for converting Python objects to TOML items.

271

272

Parameters:

273

- encoder: Function that takes a Python object and returns a TOML Item

274

275

Returns:

276

The same encoder function (for decorator usage)

277

278

Raises:

279

ConvertError: If encoder returns invalid TOML item

280

"""

281

282

def unregister_encoder(encoder: Encoder) -> None:

283

"""

284

Remove a previously registered custom encoder.

285

286

Parameters:

287

- encoder: The encoder function to remove

288

"""

289

```

290

291

## Usage Examples

292

293

### Working with Document Structure

294

295

```python

296

import tomlkit

297

298

# Create document and inspect structure

299

doc = tomlkit.parse('''

300

title = "My App"

301

version = "1.0.0"

302

303

[server]

304

host = "localhost"

305

port = 8080

306

''')

307

308

# TOMLDocument inherits from Container

309

print(type(doc)) # <class 'tomlkit.toml_document.TOMLDocument'>

310

print(isinstance(doc, tomlkit.Container)) # True

311

312

# Access container methods

313

print(doc.value) # Pure Python dict

314

print(doc.unwrap()) # Same as .value

315

316

# Iterate over items

317

for key, item in doc.items():

318

print(f"{key}: {type(item)} = {item.value}")

319

```

320

321

### Scalar Type Inspection

322

323

```python

324

import tomlkit

325

326

doc = tomlkit.parse('''

327

name = "Example"

328

count = 42

329

price = 19.99

330

enabled = true

331

created = 2023-01-15

332

''')

333

334

# Inspect item types

335

name_item = doc._body[0][1] # First item

336

print(type(name_item)) # <class 'tomlkit.items.String'>

337

print(name_item.value) # "Example"

338

339

count_item = doc["count"]

340

print(type(count_item)) # <class 'tomlkit.items.Integer'>

341

print(count_item.value) # 42

342

343

# Check if item is specific type

344

if isinstance(count_item, tomlkit.items.Integer):

345

print("Found integer item")

346

```

347

348

### Array Operations

349

350

```python

351

import tomlkit

352

353

# Create and manipulate arrays

354

doc = tomlkit.document()

355

arr = tomlkit.array()

356

357

# Add various types

358

arr.append("hello")

359

arr.append(42)

360

arr.append(True)

361

arr.extend([1.5, "world"])

362

363

doc["items"] = arr

364

365

# Array methods

366

print(len(arr)) # 5

367

print(arr[0]) # "hello"

368

print(arr.value) # ["hello", 42, True, 1.5, "world"]

369

370

# Insert and modify

371

arr.insert(1, "inserted")

372

arr[0] = "modified"

373

```

374

375

### Table Manipulation

376

377

```python

378

import tomlkit

379

380

# Create nested table structure

381

doc = tomlkit.document()

382

383

# Standard table

384

server = tomlkit.table()

385

server["host"] = "localhost"

386

server["port"] = 8080

387

server["ssl"] = True

388

389

# Inline table

390

auth = tomlkit.inline_table()

391

auth["username"] = "admin"

392

auth["token"] = "secret123"

393

394

# Add to document

395

doc["server"] = server

396

doc["auth"] = auth

397

398

# Access table properties

399

print(server.value) # dict representation

400

print(type(server)) # <class 'tomlkit.items.Table'>

401

print(type(auth)) # <class 'tomlkit.items.InlineTable'>

402

```

403

404

### Array of Tables

405

406

```python

407

import tomlkit

408

409

# Create array of tables

410

doc = tomlkit.document()

411

users = tomlkit.aot()

412

413

# Add user tables

414

user1 = tomlkit.table()

415

user1["name"] = "Alice"

416

user1["role"] = "admin"

417

418

user2 = tomlkit.table()

419

user2["name"] = "Bob"

420

user2["role"] = "user"

421

422

users.append(user1)

423

users.append(user2)

424

425

doc["users"] = users

426

427

# Access AoT

428

print(type(users)) # <class 'tomlkit.items.AoT'>

429

print(users.value) # [{"name": "Alice", "role": "admin"}, ...]

430

print(len(users)) # 2

431

```

432

433

### Key Types and Access

434

435

```python

436

import tomlkit

437

438

# Different key types

439

simple = tomlkit.key("title")

440

dotted = tomlkit.key(["server", "database", "host"])

441

442

print(type(simple)) # <class 'tomlkit.items.SingleKey'>

443

print(type(dotted)) # <class 'tomlkit.items.DottedKey'>

444

445

print(simple.key) # "title"

446

print(dotted.key) # "server.database.host"

447

448

# Use keys with containers

449

doc = tomlkit.document()

450

doc.add(simple, "My Application")

451

doc.add(dotted, "db.example.com")

452

```

453

454

### Custom Types and Conversion

455

456

```python

457

import tomlkit

458

from datetime import datetime, date

459

460

# Custom encoder for datetime objects

461

def datetime_encoder(obj):

462

if isinstance(obj, datetime):

463

return tomlkit.datetime(obj.isoformat())

464

elif isinstance(obj, date):

465

return tomlkit.date(obj.isoformat())

466

raise tomlkit.ConvertError(f"Cannot convert {type(obj)}")

467

468

# Register custom encoder

469

tomlkit.register_encoder(datetime_encoder)

470

471

# Now datetime objects work with item()

472

doc = tomlkit.document()

473

doc["created"] = datetime.now()

474

doc["birthday"] = date(1990, 5, 15)

475

476

# Unregister when done

477

tomlkit.unregister_encoder(datetime_encoder)

478

```

479

480

### Formatting Control

481

482

```python

483

import tomlkit

484

485

# Create document with precise formatting

486

doc = tomlkit.document()

487

488

# Add comment

489

doc.add(tomlkit.comment("Configuration file"))

490

doc.add(tomlkit.nl())

491

492

# Add content with whitespace control

493

doc.add("title", tomlkit.string("My App"))

494

doc.add(tomlkit.ws(" ")) # Extra spacing

495

doc.add(tomlkit.comment("Application name"))

496

doc.add(tomlkit.nl())

497

doc.add(tomlkit.nl()) # Blank line

498

499

# Create table with formatting

500

server = tomlkit.table()

501

server.add("host", tomlkit.string("localhost"))

502

server.add(tomlkit.comment("Server configuration"))

503

504

doc.add("server", server)

505

506

print(doc.as_string())

507

# Outputs with preserved formatting and comments

508

```