or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-models.mddataclasses-adapters.mderror-handling.mdindex.mdjson-schema.mdplugins.mdserialization-config.mdtype-system.mdvalidation-system.md

type-system.mddocs/

0

# Type System and Constraints

1

2

Specialized types for common data patterns including network addresses, file paths, dates, colors, and constrained types with built-in validation.

3

4

## Capabilities

5

6

### Network and URL Types

7

8

Specialized string types for network addresses, URLs, and email validation.

9

10

```python { .api }

11

class AnyUrl(Url):

12

"""

13

Base class for URL validation.

14

15

Validates URL format and structure.

16

"""

17

18

class AnyHttpUrl(AnyUrl):

19

"""

20

URL that must use HTTP or HTTPS scheme.

21

"""

22

23

class HttpUrl(AnyHttpUrl):

24

"""

25

HTTP or HTTPS URL with additional validation.

26

"""

27

28

class FileUrl(AnyUrl):

29

"""

30

File URL (file:// scheme).

31

"""

32

33

class PostgresDsn(AnyUrl):

34

"""

35

PostgreSQL data source name (DSN).

36

"""

37

38

class MySQLDsn(AnyUrl):

39

"""

40

MySQL data source name (DSN).

41

"""

42

43

class MariaDBDsn(AnyUrl):

44

"""

45

MariaDB data source name (DSN).

46

"""

47

48

class CockroachDsn(AnyUrl):

49

"""

50

CockroachDB data source name (DSN).

51

"""

52

53

class AmqpDsn(AnyUrl):

54

"""

55

AMQP (Advanced Message Queuing Protocol) DSN.

56

"""

57

58

class RedisDsn(AnyUrl):

59

"""

60

Redis data source name (DSN).

61

"""

62

63

class MongoDsn(AnyUrl):

64

"""

65

MongoDB data source name (DSN).

66

"""

67

68

class KafkaDsn(AnyUrl):

69

"""

70

Apache Kafka data source name (DSN).

71

"""

72

73

class NatsDsn(AnyUrl):

74

"""

75

NATS messaging system DSN.

76

"""

77

78

class ClickHouseDsn(AnyUrl):

79

"""

80

ClickHouse database DSN.

81

"""

82

83

class SnowflakeDsn(AnyUrl):

84

"""

85

Snowflake data warehouse DSN.

86

"""

87

88

class EmailStr(str):

89

"""

90

String that must be a valid email address.

91

"""

92

93

class NameEmail(str):

94

"""

95

Email address that can include a display name.

96

Format: "Display Name <email@example.com>" or "email@example.com"

97

"""

98

99

class IPvAnyAddress:

100

"""

101

IPv4 or IPv6 address.

102

"""

103

104

class IPvAnyInterface:

105

"""

106

IPv4 or IPv6 interface (address with network mask).

107

"""

108

109

class IPvAnyNetwork:

110

"""

111

IPv4 or IPv6 network.

112

"""

113

114

class UrlConstraints:

115

"""

116

Constraints for URL validation.

117

118

Allows customization of URL validation rules.

119

"""

120

121

def __init__(self, *, max_length=None, allowed_schemes=None, host_required=None,

122

default_host=None, default_port=None, default_path=None):

123

"""

124

Initialize URL constraints.

125

126

Args:

127

max_length (int): Maximum URL length

128

allowed_schemes (set): Set of allowed URL schemes

129

host_required (bool): Whether host is required

130

default_host (str): Default host if not provided

131

default_port (int): Default port if not provided

132

default_path (str): Default path if not provided

133

"""

134

```

135

136

### Constrained Types

137

138

Generic constrained types that add validation rules to base Python types.

139

140

```python { .api }

141

def constr(*, min_length=None, max_length=None, strict=None, strip_whitespace=None,

142

to_lower=None, to_upper=None, pattern=None):

143

"""

144

Create constrained string type.

145

146

Args:

147

min_length (int): Minimum string length

148

max_length (int): Maximum string length

149

strict (bool): Strict mode validation

150

strip_whitespace (bool): Strip leading/trailing whitespace

151

to_lower (bool): Convert to lowercase

152

to_upper (bool): Convert to uppercase

153

pattern (str): Regex pattern to match

154

155

Returns:

156

Constrained string type

157

"""

158

159

def conint(*, strict=None, gt=None, ge=None, lt=None, le=None, multiple_of=None):

160

"""

161

Create constrained integer type.

162

163

Args:

164

strict (bool): Strict mode validation

165

gt: Greater than constraint

166

ge: Greater than or equal constraint

167

lt: Less than constraint

168

le: Less than or equal constraint

169

multiple_of: Multiple of constraint

170

171

Returns:

172

Constrained integer type

173

"""

174

175

def confloat(*, strict=None, gt=None, ge=None, lt=None, le=None, multiple_of=None,

176

allow_inf_nan=None):

177

"""

178

Create constrained float type.

179

180

Args:

181

strict (bool): Strict mode validation

182

gt: Greater than constraint

183

ge: Greater than or equal constraint

184

lt: Less than constraint

185

le: Less than or equal constraint

186

multiple_of: Multiple of constraint

187

allow_inf_nan (bool): Allow infinity and NaN values

188

189

Returns:

190

Constrained float type

191

"""

192

193

def condecimal(*, strict=None, gt=None, ge=None, lt=None, le=None, multiple_of=None,

194

max_digits=None, decimal_places=None, allow_inf_nan=None):

195

"""

196

Create constrained decimal type.

197

198

Args:

199

strict (bool): Strict mode validation

200

gt: Greater than constraint

201

ge: Greater than or equal constraint

202

lt: Less than constraint

203

le: Less than or equal constraint

204

multiple_of: Multiple of constraint

205

max_digits (int): Maximum number of digits

206

decimal_places (int): Maximum decimal places

207

allow_inf_nan (bool): Allow infinity and NaN values

208

209

Returns:

210

Constrained decimal type

211

"""

212

213

def conlist(item_type, *, min_length=None, max_length=None, strict=None):

214

"""

215

Create constrained list type.

216

217

Args:

218

item_type: Type of list items

219

min_length (int): Minimum list length

220

max_length (int): Maximum list length

221

strict (bool): Strict mode validation

222

223

Returns:

224

Constrained list type

225

"""

226

227

def conset(item_type, *, min_length=None, max_length=None, strict=None):

228

"""

229

Create constrained set type.

230

231

Args:

232

item_type: Type of set items

233

min_length (int): Minimum set length

234

max_length (int): Maximum set length

235

strict (bool): Strict mode validation

236

237

Returns:

238

Constrained set type

239

"""

240

241

def confrozenset(item_type, *, min_length=None, max_length=None, strict=None):

242

"""

243

Create constrained frozenset type.

244

245

Args:

246

item_type: Type of frozenset items

247

min_length (int): Minimum frozenset length

248

max_length (int): Maximum frozenset length

249

strict (bool): Strict mode validation

250

251

Returns:

252

Constrained frozenset type

253

"""

254

255

class StringConstraints:

256

"""

257

Modern string constraints class (alternative to constr).

258

259

Provides more flexible string validation than the legacy constr function.

260

"""

261

262

def __init__(self, *, min_length=None, max_length=None, pattern=None,

263

strip_whitespace=None, to_lower=None, to_upper=None):

264

"""

265

Initialize string constraints.

266

267

Args:

268

min_length (int): Minimum string length

269

max_length (int): Maximum string length

270

pattern (str): Regex pattern to match

271

strip_whitespace (bool): Strip leading/trailing whitespace

272

to_lower (bool): Convert to lowercase

273

to_upper (bool): Convert to uppercase

274

"""

275

```

276

277

### Numeric Constraint Types

278

279

Pre-defined constrained numeric types for common use cases.

280

281

```python { .api }

282

class PositiveInt(int):

283

"""Integer that must be positive (> 0)."""

284

285

class NegativeInt(int):

286

"""Integer that must be negative (< 0)."""

287

288

class NonNegativeInt(int):

289

"""Integer that must be non-negative (>= 0)."""

290

291

class NonPositiveInt(int):

292

"""Integer that must be non-positive (<= 0)."""

293

294

class PositiveFloat(float):

295

"""Float that must be positive (> 0)."""

296

297

class NegativeFloat(float):

298

"""Float that must be negative (< 0)."""

299

300

class NonNegativeFloat(float):

301

"""Float that must be non-negative (>= 0)."""

302

303

class NonPositiveFloat(float):

304

"""Float that must be non-positive (<= 0)."""

305

306

class FiniteFloat(float):

307

"""Float that must be finite (not infinity or NaN)."""

308

```

309

310

### Date and Time Types

311

312

Enhanced date and time types with additional validation and parsing capabilities.

313

314

```python { .api }

315

class PastDate(date):

316

"""Date that must be in the past."""

317

318

class FutureDate(date):

319

"""Date that must be in the future."""

320

321

class PastDatetime(datetime):

322

"""Datetime that must be in the past."""

323

324

class FutureDatetime(datetime):

325

"""Datetime that must be in the future."""

326

327

class AwareDatetime(datetime):

328

"""Datetime that must be timezone-aware."""

329

330

class NaiveDatetime(datetime):

331

"""Datetime that must be timezone-naive."""

332

```

333

334

### File and Path Types

335

336

Types for file system paths and file validation.

337

338

```python { .api }

339

class FilePath(Path):

340

"""Path that must point to an existing file."""

341

342

class DirectoryPath(Path):

343

"""Path that must point to an existing directory."""

344

345

class NewPath(Path):

346

"""Path that must not exist (for creating new files/directories)."""

347

348

class SocketPath(Path):

349

"""Path that must point to a Unix socket file."""

350

```

351

352

### UUID Types

353

354

UUID validation with different version constraints.

355

356

```python { .api }

357

class UUID1(UUID):

358

"""UUID version 1."""

359

360

class UUID3(UUID):

361

"""UUID version 3."""

362

363

class UUID4(UUID):

364

"""UUID version 4."""

365

366

class UUID5(UUID):

367

"""UUID version 5."""

368

369

class UUID6(UUID):

370

"""UUID version 6."""

371

372

class UUID7(UUID):

373

"""UUID version 7."""

374

375

class UUID8(UUID):

376

"""UUID version 8."""

377

```

378

379

### JSON and Encoding Types

380

381

Types for JSON data and encoded strings.

382

383

```python { .api }

384

class Json:

385

"""

386

JSON string that gets parsed into Python objects.

387

"""

388

389

class Base64Str(str):

390

"""String that must be valid base64."""

391

392

class Base64Bytes(bytes):

393

"""Bytes that must be valid base64."""

394

395

class Base64UrlStr(str):

396

"""String that must be valid base64url."""

397

398

class Base64UrlBytes(bytes):

399

"""Bytes that must be valid base64url."""

400

401

class EncoderProtocol:

402

"""

403

Protocol for defining custom encoders.

404

405

Used with EncodedBytes and EncodedStr for custom encoding schemes.

406

"""

407

408

def encode(self, value):

409

"""

410

Encode value to bytes/string.

411

412

Args:

413

value: Value to encode

414

415

Returns:

416

Encoded value

417

"""

418

419

def decode(self, value):

420

"""

421

Decode bytes/string to original value.

422

423

Args:

424

value: Encoded value to decode

425

426

Returns:

427

Decoded value

428

"""

429

430

class EncodedBytes(bytes):

431

"""

432

Bytes type with custom encoding/decoding via EncoderProtocol.

433

"""

434

435

class EncodedStr(str):

436

"""

437

String type with custom encoding/decoding via EncoderProtocol.

438

"""

439

440

class Base64Encoder:

441

"""

442

Built-in encoder for base64 encoding.

443

"""

444

445

def encode(self, value):

446

"""Encode value using base64."""

447

448

def decode(self, value):

449

"""Decode base64 value."""

450

```

451

452

### Advanced Type Utilities

453

454

Utility types and annotations for advanced validation control and custom type creation.

455

456

```python { .api }

457

class GetPydanticSchema:

458

"""

459

Utility for creating custom type annotations with schema hooks.

460

461

Allows advanced customization of validation and serialization behavior.

462

"""

463

464

def __init__(self, get_schema):

465

"""

466

Initialize with schema generation function.

467

468

Args:

469

get_schema: Function to generate custom schema

470

"""

471

472

class Tag:

473

"""

474

Tag annotation for discriminated unions with custom logic.

475

476

Provides more control over union discrimination than simple string tags.

477

"""

478

479

def __init__(self, tag):

480

"""

481

Initialize with tag value.

482

483

Args:

484

tag: Tag identifier for discrimination

485

"""

486

487

class Discriminator:

488

"""

489

Advanced discriminator for union types.

490

491

Supports custom discrimination logic and field mapping.

492

"""

493

494

def __init__(self, discriminator, *, custom_error_type=None,

495

custom_error_message=None, custom_error_context=None):

496

"""

497

Initialize discriminator.

498

499

Args:

500

discriminator: Discriminator field name or function

501

custom_error_type (str): Custom error type

502

custom_error_message (str): Custom error message

503

custom_error_context (dict): Custom error context

504

"""

505

506

class JsonValue:

507

"""

508

Recursive type for JSON-serializable values.

509

510

Represents values that can be safely serialized to JSON.

511

"""

512

513

class Secret:

514

"""

515

Generic secret type that can wrap any type.

516

517

More flexible than SecretStr and SecretBytes, can wrap any type.

518

"""

519

520

def __init__(self, secret_value):

521

"""

522

Initialize with secret value.

523

524

Args:

525

secret_value: Value to keep secret (any type)

526

"""

527

528

def get_secret_value(self):

529

"""

530

Get the secret value.

531

532

Returns:

533

The wrapped secret value

534

"""

535

536

class OnErrorOmit:

537

"""

538

Annotation to omit invalid items from collections instead of failing.

539

540

Used with list/set validation to skip invalid items rather than raise errors.

541

"""

542

543

class FailFast:

544

"""

545

Annotation to stop validation at first error for performance.

546

547

Useful for large collections where you want to fail quickly.

548

"""

549

550

class Strict:

551

"""

552

Generic strict mode annotation.

553

554

Can be applied to any type to enable strict validation.

555

"""

556

557

class AllowInfNan:

558

"""

559

Annotation to control whether float types allow infinity/NaN values.

560

561

Can enable or disable inf/nan for specific float fields.

562

"""

563

564

def __init__(self, allow=True):

565

"""

566

Initialize with allow flag.

567

568

Args:

569

allow (bool): Whether to allow inf/nan values

570

"""

571

572

class ImportString(str):

573

"""

574

String type for dynamically importing Python objects.

575

576

Validates that the string represents a valid import path and can load the object.

577

"""

578

579

class PaymentCardNumber(str):

580

"""

581

String type for payment card number validation.

582

583

Note: Deprecated in favor of pydantic-extra-types

584

"""

585

```

586

587

### Color Types

588

589

Types for color representation and validation.

590

591

```python { .api }

592

class Color:

593

"""

594

Color representation supporting various formats.

595

596

Supports: hex, rgb, rgba, hsl, hsla, and named colors.

597

"""

598

599

def as_hex(self, format='long'):

600

"""

601

Return color as hex string.

602

603

Args:

604

format (str): 'long' or 'short' format

605

606

Returns:

607

str: Hex color string

608

"""

609

610

def as_rgb(self):

611

"""

612

Return color as RGB tuple.

613

614

Returns:

615

tuple: (r, g, b) values

616

"""

617

618

def as_rgb_tuple(self, alpha=None):

619

"""

620

Return color as RGB tuple.

621

622

Args:

623

alpha (bool): Include alpha channel

624

625

Returns:

626

tuple: RGB(A) values

627

"""

628

```

629

630

## Usage Examples

631

632

### Network Types

633

634

```python

635

from pydantic import BaseModel, EmailStr, HttpUrl

636

637

class UserProfile(BaseModel):

638

email: EmailStr

639

website: HttpUrl

640

avatar_url: HttpUrl

641

642

# Valid usage

643

profile = UserProfile(

644

email="user@example.com",

645

website="https://example.com",

646

avatar_url="https://example.com/avatar.jpg"

647

)

648

649

# Invalid email would raise ValidationError

650

# profile = UserProfile(email="invalid-email", ...)

651

```

652

653

### Constrained Types

654

655

```python

656

from pydantic import BaseModel, constr, conint, conlist

657

658

class Product(BaseModel):

659

name: constr(min_length=1, max_length=100, strip_whitespace=True)

660

price: confloat(gt=0, le=10000.0)

661

quantity: conint(ge=0)

662

tags: conlist(str, min_length=1, max_length=10)

663

664

# Usage

665

product = Product(

666

name=" Laptop ", # Will be stripped to "Laptop"

667

price=999.99,

668

quantity=5,

669

tags=["electronics", "computer"]

670

)

671

```

672

673

### Numeric Constraints

674

675

```python

676

from pydantic import BaseModel, PositiveInt, NonNegativeFloat

677

678

class Transaction(BaseModel):

679

id: PositiveInt

680

amount: NonNegativeFloat

681

fee: NonNegativeFloat

682

683

# Valid transaction

684

transaction = Transaction(id=123, amount=100.0, fee=2.50)

685

686

# Invalid - negative amount would raise ValidationError

687

# transaction = Transaction(id=123, amount=-100.0, fee=2.50)

688

```

689

690

### Date and Time Constraints

691

692

```python

693

from pydantic import BaseModel, PastDate, FutureDatetime

694

from datetime import date, datetime

695

696

class Event(BaseModel):

697

birth_date: PastDate

698

event_datetime: FutureDatetime

699

700

# Usage

701

event = Event(

702

birth_date=date(1990, 1, 1),

703

event_datetime=datetime(2024, 12, 31, 18, 0)

704

)

705

```

706

707

### File Path Types

708

709

```python

710

from pydantic import BaseModel, FilePath, DirectoryPath

711

from pathlib import Path

712

713

class Config(BaseModel):

714

config_file: FilePath

715

output_dir: DirectoryPath

716

717

# Usage (paths must exist)

718

config = Config(

719

config_file=Path("config.json"),

720

output_dir=Path("./output")

721

)

722

```

723

724

### UUID Types

725

726

```python

727

from pydantic import BaseModel, UUID4

728

import uuid

729

730

class Resource(BaseModel):

731

id: UUID4

732

name: str

733

734

# Usage

735

resource = Resource(

736

id=uuid.uuid4(),

737

name="My Resource"

738

)

739

740

# String UUIDs are automatically converted

741

resource2 = Resource(

742

id="123e4567-e89b-12d3-a456-426614174000",

743

name="Another Resource"

744

)

745

```

746

747

### JSON Types

748

749

```python

750

from pydantic import BaseModel, Json

751

752

class Settings(BaseModel):

753

config: Json

754

metadata: Json

755

756

# JSON strings are parsed automatically

757

settings = Settings(

758

config='{"debug": true, "port": 8000}',

759

metadata='["tag1", "tag2", "tag3"]'

760

)

761

762

# Access parsed data

763

print(settings.config) # {'debug': True, 'port': 8000}

764

print(settings.metadata) # ['tag1', 'tag2', 'tag3']

765

```