or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

class-integration.mdconfiguration.mdcore-serialization.mdcustomization.mdindex.mdkey-transformation.mdtype-system.md

configuration.mddocs/

0

# Configuration & Control

1

2

Advanced configuration options for controlling jsons behavior, including fork management for separate serializer configurations, warning control, verbosity settings, and object transformation utilities.

3

4

## Capabilities

5

6

### Fork Management

7

8

```python { .api }

9

def fork(fork_inst=StateHolder, name=None):

10

"""

11

Create a separate "fork" of serializers and deserializers with independent configuration.

12

13

Parameters:

14

- fork_inst: Base StateHolder class to fork from (defaults to main StateHolder)

15

- name: Optional name for the new fork (auto-generated if not provided)

16

17

Returns:

18

type: New fork class that can be used as fork_inst parameter in other functions

19

"""

20

```

21

22

### Object Transformation

23

24

```python { .api }

25

def transform(obj, cls, *, mapper=None, dump_cls=None, dump_args=None, dump_kwargs=None, **kwargs):

26

"""

27

Transform an object to a different type via JSON serialization/deserialization.

28

29

Parameters:

30

- obj: Object to be transformed

31

- cls: Target type to transform into

32

- mapper: Optional callable to modify the intermediate JSON dict

33

- dump_cls: Optional type to use when dumping obj (instead of obj's actual type)

34

- dump_args: Optional list of positional args for dump operation

35

- dump_kwargs: Optional dict of keyword args for dump operation

36

- **kwargs: Additional arguments passed to load operation

37

38

Returns:

39

Instance of cls created by transforming obj through JSON

40

"""

41

```

42

43

### Warning Control

44

45

```python { .api }

46

def suppress_warnings(do_suppress=True, fork_inst=None):

47

"""

48

Suppress or enable jsons warnings globally.

49

50

Parameters:

51

- do_suppress: Bool to control warning suppression (True = suppress, False = enable)

52

- fork_inst: Optional fork instance to configure (defaults to main StateHolder)

53

54

Returns:

55

None

56

"""

57

58

def suppress_warning(code, fork_inst=None):

59

"""

60

Suppress a specific warning by its warning code.

61

62

Parameters:

63

- code: String code of the specific warning to suppress

64

- fork_inst: Optional fork instance to configure

65

66

Returns:

67

None

68

"""

69

```

70

71

### Verbosity Control

72

73

```python { .api }

74

class Verbosity:

75

"""

76

Enum-like class defining levels of verbosity for serialization output.

77

"""

78

WITH_NOTHING = 0

79

WITH_CLASS_INFO = 10

80

WITH_DUMP_TIME = 20

81

WITH_EVERYTHING = WITH_CLASS_INFO | WITH_DUMP_TIME

82

83

@staticmethod

84

def from_value(value):

85

"""

86

Convert various value types to Verbosity instance.

87

88

Parameters:

89

- value: Value to convert (bool, int, Verbosity, or other)

90

91

Returns:

92

Verbosity: Corresponding Verbosity level

93

"""

94

```

95

96

## Usage Examples

97

98

### Fork Management for Different Configurations

99

100

```python

101

import jsons

102

from jsons import JsonSerializable

103

from datetime import datetime

104

from dataclasses import dataclass

105

106

# Create separate forks for different use cases

107

APIFork = jsons.fork(name="APIConfig")

108

DebugFork = jsons.fork(name="DebugConfig")

109

110

# Configure API fork with timestamp serialization

111

def api_datetime_serializer(dt: datetime, **kwargs) -> int:

112

return int(dt.timestamp())

113

114

# Configure debug fork with verbose datetime serialization

115

def debug_datetime_serializer(dt: datetime, **kwargs) -> str:

116

return f"DateTime({dt.isoformat()}, weekday={dt.strftime('%A')})"

117

118

# Register different serializers for each fork

119

jsons.set_serializer(api_datetime_serializer, datetime, fork_inst=APIFork)

120

jsons.set_serializer(debug_datetime_serializer, datetime, fork_inst=DebugFork)

121

122

@dataclass

123

class Event:

124

name: str

125

timestamp: datetime

126

127

event = Event("Meeting", datetime(2023, 12, 1, 14, 30, 0))

128

129

# Use different forks for different serialization styles

130

api_json = jsons.dump(event, fork_inst=APIFork)

131

debug_json = jsons.dump(event, fork_inst=DebugFork)

132

default_json = jsons.dump(event) # Uses default fork

133

134

print("API format:", api_json)

135

# {'name': 'Meeting', 'timestamp': 1701435000}

136

137

print("Debug format:", debug_json)

138

# {'name': 'Meeting', 'timestamp': 'DateTime(2023-12-01T14:30:00, weekday=Friday)'}

139

140

print("Default format:", default_json)

141

# {'name': 'Meeting', 'timestamp': '2023-12-01T14:30:00'}

142

```

143

144

### JsonSerializable with Fork Integration

145

146

```python

147

import jsons

148

from jsons import JsonSerializable

149

150

# Create specialized JsonSerializable classes using forks

151

APISerializable = JsonSerializable.fork("APISerializable")

152

InternalSerializable = JsonSerializable.fork("InternalSerializable")

153

154

# Configure API fork for external communication

155

def external_id_serializer(obj_id: int, **kwargs) -> str:

156

return f"EXT_{obj_id:08d}" # External IDs are string-formatted

157

158

jsons.set_serializer(external_id_serializer, int, fork_inst=APISerializable)

159

160

class APIUser(APISerializable):

161

def __init__(self, user_id: int, name: str):

162

self.user_id = user_id

163

self.name = name

164

165

class InternalUser(InternalSerializable):

166

def __init__(self, user_id: int, name: str):

167

self.user_id = user_id

168

self.name = name

169

170

# Same data, different serialization based on fork

171

api_user = APIUser(12345, "Alice")

172

internal_user = InternalUser(12345, "Alice")

173

174

print("API serialization:", api_user.json)

175

# {'user_id': 'EXT_00012345', 'name': 'Alice'}

176

177

print("Internal serialization:", internal_user.json)

178

# {'user_id': 12345, 'name': 'Alice'}

179

```

180

181

### Object Transformation

182

183

```python

184

import jsons

185

from dataclasses import dataclass

186

from typing import Dict, Any

187

188

@dataclass

189

class Person:

190

first_name: str

191

last_name: str

192

age: int

193

194

@dataclass

195

class Employee:

196

name: str

197

employee_age: int

198

department: str = "Unassigned"

199

200

# Transform Person to Employee with field mapping

201

def person_to_employee_mapper(person_dict: Dict[str, Any]) -> Dict[str, Any]:

202

return {

203

'name': f"{person_dict['first_name']} {person_dict['last_name']}",

204

'employee_age': person_dict['age'],

205

'department': 'New Hire'

206

}

207

208

person = Person("John", "Doe", 30)

209

210

# Transform using mapper function

211

employee = jsons.transform(person, Employee, mapper=person_to_employee_mapper)

212

print(employee)

213

# Employee(name='John Doe', employee_age=30, department='New Hire')

214

215

# Transform with different dump class

216

@dataclass

217

class PersonSummary:

218

first_name: str

219

age: int

220

# Note: missing last_name field

221

222

summary = jsons.transform(person, PersonSummary, dump_cls=PersonSummary)

223

print(summary)

224

# PersonSummary(first_name='John', age=30)

225

```

226

227

### Advanced Transformation Examples

228

229

```python

230

import jsons

231

from dataclasses import dataclass

232

from typing import List

233

from datetime import datetime

234

235

@dataclass

236

class LogEntry:

237

timestamp: datetime

238

level: str

239

message: str

240

module: str

241

242

@dataclass

243

class AlertSummary:

244

alert_time: str

245

severity: str

246

description: str

247

source: str

248

249

# Transform log entries to alert summaries

250

def log_to_alert_mapper(log_dict):

251

severity_map = {'ERROR': 'HIGH', 'WARNING': 'MEDIUM', 'INFO': 'LOW'}

252

return {

253

'alert_time': log_dict['timestamp'],

254

'severity': severity_map.get(log_dict['level'], 'UNKNOWN'),

255

'description': f"Alert: {log_dict['message']}",

256

'source': f"Module: {log_dict['module']}"

257

}

258

259

log_entries = [

260

LogEntry(datetime.now(), "ERROR", "Database connection failed", "db_manager"),

261

LogEntry(datetime.now(), "WARNING", "High memory usage detected", "monitor"),

262

LogEntry(datetime.now(), "INFO", "User login successful", "auth")

263

]

264

265

# Transform list of logs to list of alerts

266

alerts = [

267

jsons.transform(log, AlertSummary, mapper=log_to_alert_mapper)

268

for log in log_entries

269

]

270

271

for alert in alerts:

272

print(f"{alert.severity}: {alert.description} ({alert.source})")

273

# HIGH: Alert: Database connection failed (Module: db_manager)

274

# MEDIUM: Alert: High memory usage detected (Module: monitor)

275

# LOW: Alert: User login successful (Module: auth)

276

```

277

278

### Warning Control

279

280

```python

281

import jsons

282

from dataclasses import dataclass

283

284

@dataclass

285

class TestClass:

286

value: str

287

288

# Suppress all warnings

289

jsons.suppress_warnings(True)

290

291

# Code that might generate warnings runs silently

292

test_obj = TestClass("test")

293

result = jsons.dump(test_obj)

294

295

# Re-enable warnings

296

jsons.suppress_warnings(False)

297

298

# Suppress specific warning by code

299

jsons.suppress_warning("JSONS001") # Example warning code

300

301

# Fork-specific warning control

302

debug_fork = jsons.fork("DebugFork")

303

jsons.suppress_warnings(False, fork_inst=debug_fork) # Enable warnings for debug fork

304

jsons.suppress_warnings(True) # But keep main fork warnings suppressed

305

```

306

307

### Verbosity Control

308

309

```python

310

import jsons

311

from jsons import Verbosity, JsonSerializable

312

from dataclasses import dataclass

313

from datetime import datetime

314

315

@dataclass

316

class DataPoint:

317

value: float

318

recorded_at: datetime

319

320

# Different verbosity levels

321

data = DataPoint(42.5, datetime.now())

322

323

# Minimal output (default)

324

minimal = jsons.dump(data, verbosity=Verbosity.WITH_NOTHING)

325

print("Minimal:", minimal)

326

# {'value': 42.5, 'recorded_at': '2023-12-01T14:30:00.123456'}

327

328

# With class information

329

with_class = jsons.dump(data, verbosity=Verbosity.WITH_CLASS_INFO)

330

print("With class info:", with_class)

331

# {'value': 42.5, 'recorded_at': '2023-12-01T14:30:00.123456', '-jsons-class': 'DataPoint'}

332

333

# With timestamp

334

with_time = jsons.dump(data, verbosity=Verbosity.WITH_DUMP_TIME)

335

print("With dump time:", with_time)

336

# {'value': 42.5, 'recorded_at': '2023-12-01T14:30:00.123456', '-jsons-dump-time': '2023-12-01T14:30:01.000000'}

337

338

# With everything

339

with_all = jsons.dump(data, verbosity=Verbosity.WITH_EVERYTHING)

340

print("With everything:", with_all)

341

# {

342

# 'value': 42.5,

343

# 'recorded_at': '2023-12-01T14:30:00.123456',

344

# '-jsons-class': 'DataPoint',

345

# '-jsons-dump-time': '2023-12-01T14:30:01.000000'

346

# }

347

348

# Verbosity from different value types

349

print(Verbosity.from_value(True)) # Verbosity.WITH_EVERYTHING

350

print(Verbosity.from_value(False)) # Verbosity.WITH_NOTHING

351

print(Verbosity.from_value(None)) # Verbosity.WITH_NOTHING

352

```

353

354

### Advanced Fork Configuration with JsonSerializable

355

356

```python

357

import jsons

358

from jsons import JsonSerializable, Verbosity

359

360

# Create a specialized debug configuration

361

DebugSerializable = JsonSerializable.with_dump(

362

fork=True, # Create new fork

363

verbosity=Verbosity.WITH_EVERYTHING,

364

strict=True

365

).with_load(

366

strict=True,

367

fork=False # Use same fork as dump

368

)

369

370

class DebugModel(DebugSerializable):

371

def __init__(self, data: str, version: int):

372

self.data = data

373

self.version = version

374

375

debug_obj = DebugModel("test data", 2)

376

377

# Automatically includes verbose information due to fork configuration

378

debug_json = debug_obj.json

379

print("Debug JSON includes metadata:", '-jsons-class' in debug_json) # True

380

381

# Deserialization uses same fork configuration

382

restored = DebugModel.from_json(debug_json)

383

print("Restored:", restored.data, restored.version)

384

```

385

386

### Complete Configuration Example

387

388

```python

389

import jsons

390

from jsons import JsonSerializable, Verbosity, KEY_TRANSFORMER_CAMELCASE

391

from datetime import datetime

392

from dataclasses import dataclass

393

394

# Create a fully configured fork for web API integration

395

WebAPIFork = jsons.fork("WebAPIConfig")

396

397

# Configure datetime serialization for web APIs

398

def web_datetime_serializer(dt: datetime, **kwargs) -> str:

399

return dt.isoformat() + 'Z' # ISO format with Z suffix

400

401

# Configure custom validation for web objects

402

def web_string_validator(s: str, **kwargs) -> bool:

403

if len(s.strip()) == 0:

404

raise jsons.ValidationError("Web API strings cannot be empty or whitespace")

405

return True

406

407

# Register configurations for the web fork

408

jsons.set_serializer(web_datetime_serializer, datetime, fork_inst=WebAPIFork)

409

jsons.set_validator(web_string_validator, str, fork_inst=WebAPIFork)

410

jsons.suppress_warnings(False, fork_inst=WebAPIFork) # Enable warnings for debugging

411

412

# Create a specialized base class

413

WebAPISerializable = JsonSerializable.fork("WebAPISerializable").with_dump(

414

fork_inst=WebAPIFork,

415

key_transformer=KEY_TRANSFORMER_CAMELCASE,

416

verbosity=Verbosity.WITH_CLASS_INFO

417

).with_load(

418

fork_inst=WebAPIFork,

419

key_transformer=jsons.snakecase,

420

strict=True

421

)

422

423

@dataclass

424

class WebUser(WebAPISerializable):

425

user_name: str

426

email_address: str

427

last_login: datetime

428

is_active: bool

429

430

user = WebUser(

431

user_name="alice_smith",

432

email_address="alice@example.com",

433

last_login=datetime.now(),

434

is_active=True

435

)

436

437

# Serialization uses all configured settings

438

web_json = user.json

439

print("Web API JSON:")

440

print(web_json)

441

# {

442

# 'userName': 'alice_smith',

443

# 'emailAddress': 'alice@example.com',

444

# 'lastLogin': '2023-12-01T14:30:00.123456Z', # Custom format with Z

445

# 'isActive': True,

446

# '-jsons-class': 'WebUser' # Class info due to verbosity setting

447

# }

448

449

# Deserialization handles validation and key transformation

450

camel_input = {

451

'userName': 'bob_jones',

452

'emailAddress': 'bob@example.com',

453

'lastLogin': '2023-12-01T15:30:00.000000Z',

454

'isActive': False

455

}

456

457

restored_user = WebUser.from_json(camel_input)

458

print("Restored user:", restored_user.user_name, restored_user.email_address)

459

```