0
# Type System
1
2
PyKwalify provides comprehensive type checking and validation utilities for all supported data types including scalars, collections, timestamps, dates, emails, and URLs with built-in validation functions.
3
4
## Capabilities
5
6
### Type Checking Functions
7
8
Core type validation functions that determine if an object matches a specific type.
9
10
```python { .api }
11
def is_string(obj):
12
"""
13
Check if object is a string.
14
15
Args:
16
obj: Object to check
17
18
Returns:
19
bool: True if object is string or bytes
20
"""
21
22
def is_int(obj):
23
"""
24
Check if object is an integer.
25
Note: True and False are not considered valid integers.
26
27
Args:
28
obj: Object to check
29
30
Returns:
31
bool: True if object is int and not bool
32
"""
33
34
def is_float(obj):
35
"""
36
Check if object is a float or string convertible to float.
37
38
Args:
39
obj: Object to check
40
41
Returns:
42
bool: True if object is float or string convertible to float (excluding bools)
43
"""
44
45
def is_bool(obj):
46
"""
47
Check if object is a boolean.
48
49
Args:
50
obj: Object to check
51
52
Returns:
53
bool: True if object is bool
54
"""
55
56
def is_number(obj):
57
"""
58
Check if object is a number (int or float).
59
60
Args:
61
obj: Object to check
62
63
Returns:
64
bool: True if object is int or float
65
"""
66
```
67
68
### Collection Type Checking
69
70
```python { .api }
71
def is_collection(obj):
72
"""
73
Check if object is a collection (dict or list).
74
75
Args:
76
obj: Object to check
77
78
Returns:
79
bool: True if object is dict or list
80
"""
81
82
def is_scalar(obj):
83
"""
84
Check if object is a scalar (not collection and not None).
85
86
Args:
87
obj: Object to check
88
89
Returns:
90
bool: True if object is not collection and not None
91
"""
92
93
def is_sequence_alias(alias):
94
"""
95
Check if alias represents a sequence type.
96
97
Args:
98
alias (str): Type alias to check
99
100
Returns:
101
bool: True if alias is in sequence_aliases
102
"""
103
104
def is_mapping_alias(alias):
105
"""
106
Check if alias represents a mapping type.
107
108
Args:
109
alias (str): Type alias to check
110
111
Returns:
112
bool: True if alias is in mapping_aliases
113
"""
114
```
115
116
### Special Type Validation
117
118
```python { .api }
119
def is_text(obj):
120
"""
121
Check if object is text (string or number, but not bool).
122
123
Args:
124
obj: Object to check
125
126
Returns:
127
bool: True if object is string or number and not bool
128
"""
129
130
def is_any(obj):
131
"""
132
Always returns True - accepts any object.
133
134
Args:
135
obj: Object to check (ignored)
136
137
Returns:
138
bool: Always True
139
"""
140
141
def is_enum(obj):
142
"""
143
Check if object is valid for enum validation.
144
145
Args:
146
obj: Object to check
147
148
Returns:
149
bool: True if object is string
150
"""
151
152
def is_none(obj):
153
"""
154
Check if object is None.
155
156
Args:
157
obj: Object to check
158
159
Returns:
160
bool: True if object is None
161
"""
162
```
163
164
### Date and Time Validation
165
166
```python { .api }
167
def is_timestamp(obj):
168
"""
169
Check if object is a valid timestamp.
170
Accepts datetime objects, strings, integers, or floats.
171
172
Args:
173
obj: Object to check
174
175
Returns:
176
bool: True if object is valid timestamp format
177
"""
178
179
def is_date(obj):
180
"""
181
Check if object is a valid date.
182
183
Args:
184
obj: Object to check
185
186
Returns:
187
bool: True if object is string or datetime.date
188
"""
189
```
190
191
### Format Validation
192
193
```python { .api }
194
def is_email(obj):
195
"""
196
Check if object matches email format using regex.
197
198
Args:
199
obj: Object to check
200
201
Returns:
202
bool: True if object matches email regex pattern
203
"""
204
205
def is_url(obj):
206
"""
207
Check if object matches URL format using regex.
208
209
Args:
210
obj: Object to check
211
212
Returns:
213
bool: True if object matches HTTP/HTTPS URL pattern
214
"""
215
```
216
217
### Type Utility Functions
218
219
```python { .api }
220
def type_class(type):
221
"""
222
Get Python class for type name.
223
224
Args:
225
type (str): Type name
226
227
Returns:
228
type: Corresponding Python class
229
"""
230
231
def is_builtin_type(type):
232
"""
233
Check if type is a built-in PyKwalify type.
234
235
Args:
236
type (str): Type name
237
238
Returns:
239
bool: True if type is in built-in types
240
"""
241
242
def is_collection_type(type):
243
"""
244
Check if type represents a collection.
245
246
Args:
247
type (str): Type name
248
249
Returns:
250
bool: True if type is 'map' or 'seq'
251
"""
252
253
def is_scalar_type(type):
254
"""
255
Check if type represents a scalar.
256
257
Args:
258
type (str): Type name
259
260
Returns:
261
bool: True if type is not collection type
262
"""
263
264
def is_correct_type(obj, type):
265
"""
266
Check if object is instance of given type.
267
268
Args:
269
obj: Object to check
270
type: Python type class
271
272
Returns:
273
bool: True if isinstance(obj, type)
274
"""
275
```
276
277
## Type Constants and Mappings
278
279
### Type Definitions
280
281
```python { .api }
282
DEFAULT_TYPE: str # Default type string ("str")
283
284
_types: dict # Mapping of type names to Python classes
285
"""
286
{
287
"str": str,
288
"int": int,
289
"float": float,
290
"number": None,
291
"bool": bool,
292
"map": dict,
293
"seq": list,
294
"timestamp": datetime.datetime,
295
"date": datetime.date,
296
"symbol": str,
297
"scalar": None,
298
"text": text,
299
"any": object,
300
"enum": str,
301
"none": None,
302
"email": str,
303
"url": str,
304
}
305
"""
306
307
sequence_aliases: list # ["sequence", "seq"]
308
mapping_aliases: list # ["map", "mapping"]
309
310
tt: dict # Mapping of type names to validation functions
311
"""
312
{
313
"str": is_string,
314
"int": is_int,
315
"bool": is_bool,
316
"float": is_float,
317
"number": is_number,
318
"text": is_text,
319
"any": is_any,
320
"enum": is_enum,
321
"none": is_none,
322
"timestamp": is_timestamp,
323
"scalar": is_scalar,
324
"date": is_date,
325
"email": is_email,
326
"url": is_url,
327
}
328
"""
329
```
330
331
### Special Type Classes
332
333
```python { .api }
334
class TextMeta(type):
335
"""Metaclass for text type that implements custom instance checking."""
336
def __instancecheck__(self, instance):
337
return is_text(instance)
338
339
class text(object):
340
"""Special text type class for PyKwalify text validation."""
341
__metaclass__ = TextMeta
342
```
343
344
## Usage Examples
345
346
### Basic Type Checking
347
348
```python
349
from pykwalify.types import is_string, is_int, is_float, is_bool
350
351
# Test various values
352
values = ["hello", 42, 3.14, True, False, None, [], {}]
353
354
for value in values:
355
print(f"Value: {value}")
356
print(f" String: {is_string(value)}")
357
print(f" Int: {is_int(value)}")
358
print(f" Float: {is_float(value)}")
359
print(f" Bool: {is_bool(value)}")
360
print()
361
```
362
363
### Collection Type Validation
364
365
```python
366
from pykwalify.types import is_collection, is_scalar, is_sequence_alias, is_mapping_alias
367
368
# Test collection types
369
test_values = [
370
{"name": "dict"},
371
["list", "items"],
372
"string",
373
42,
374
None
375
]
376
377
for value in test_values:
378
print(f"Value: {value}")
379
print(f" Collection: {is_collection(value)}")
380
print(f" Scalar: {is_scalar(value)}")
381
382
# Test type aliases
383
aliases = ["seq", "sequence", "map", "mapping", "list", "dict"]
384
for alias in aliases:
385
print(f"'{alias}' - Sequence: {is_sequence_alias(alias)}, Mapping: {is_mapping_alias(alias)}")
386
```
387
388
### Format Validation
389
390
```python
391
from pykwalify.types import is_email, is_url, is_timestamp, is_date
392
from datetime import datetime, date
393
394
# Email validation
395
emails = ["test@example.com", "invalid-email", "user@domain.co.uk"]
396
for email in emails:
397
print(f"'{email}' is email: {is_email(email)}")
398
399
# URL validation
400
urls = ["https://example.com", "http://test.org", "not-a-url", "ftp://invalid.com"]
401
for url in urls:
402
print(f"'{url}' is URL: {is_url(url)}")
403
404
# Timestamp validation
405
timestamps = [datetime.now(), "2023-01-01T10:00:00", 1640995200, "invalid"]
406
for ts in timestamps:
407
print(f"'{ts}' is timestamp: {is_timestamp(ts)}")
408
409
# Date validation
410
dates = [date.today(), "2023-01-01", datetime.now(), 123]
411
for d in dates:
412
print(f"'{d}' is date: {is_date(d)}")
413
```
414
415
### Type Utility Usage
416
417
```python
418
from pykwalify.types import (
419
type_class, is_builtin_type, is_collection_type,
420
is_scalar_type, is_correct_type, tt
421
)
422
423
# Get Python class for type
424
print(f"'str' class: {type_class('str')}")
425
print(f"'int' class: {type_class('int')}")
426
print(f"'map' class: {type_class('map')}")
427
428
# Check built-in types
429
types_to_test = ["str", "int", "custom_type", "email", "unknown"]
430
for type_name in types_to_test:
431
print(f"'{type_name}' is builtin: {is_builtin_type(type_name)}")
432
433
# Check collection vs scalar types
434
for type_name in ["str", "int", "map", "seq", "float"]:
435
print(f"'{type_name}' - Collection: {is_collection_type(type_name)}, Scalar: {is_scalar_type(type_name)}")
436
437
# Use validation function mapping
438
value = "test@example.com"
439
validator = tt.get("email")
440
if validator:
441
print(f"Email validation result: {validator(value)}")
442
```
443
444
### Advanced Type Checking
445
446
```python
447
from pykwalify.types import is_text, is_number, is_any, is_none
448
449
# Text type (string or number, not bool)
450
test_values = ["hello", 42, 3.14, True, False, [], None]
451
for value in test_values:
452
print(f"'{value}' is text: {is_text(value)}")
453
454
# Number type (int or float)
455
for value in test_values:
456
print(f"'{value}' is number: {is_number(value)}")
457
458
# Any type (always True)
459
for value in test_values:
460
print(f"'{value}' is any: {is_any(value)}")
461
462
# None checking
463
for value in test_values:
464
print(f"'{value}' is none: {is_none(value)}")
465
```
466
467
### Custom Type Validation in Schemas
468
469
```python
470
from pykwalify.core import Core
471
from pykwalify.types import is_email
472
473
# Define data with various types
474
data = {
475
"name": "John Doe",
476
"age": 30,
477
"score": 95.5,
478
"active": True,
479
"email": "john@example.com",
480
"website": "https://johndoe.com",
481
"tags": ["python", "validation"],
482
"metadata": None
483
}
484
485
# Schema using various PyKwalify types
486
schema = {
487
"type": "map",
488
"mapping": {
489
"name": {"type": "str"},
490
"age": {"type": "int"},
491
"score": {"type": "float"},
492
"active": {"type": "bool"},
493
"email": {"type": "email"},
494
"website": {"type": "url"},
495
"tags": {
496
"type": "seq",
497
"sequence": [{"type": "str"}]
498
},
499
"metadata": {"type": "any", "nullable": True}
500
}
501
}
502
503
# Validate using Core
504
c = Core(source_data=data, schema_data=schema)
505
try:
506
c.validate(raise_exception=True)
507
print("All type validations passed!")
508
except Exception as e:
509
print(f"Type validation failed: {e}")
510
```