or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdcompatibility.mdcore-validation.mderror-handling.mdindex.mdschema-rules.mdtype-system.md

core-validation.mddocs/

0

# Core Validation

1

2

The Core class provides the main validation functionality for PyKwalify, supporting both file-based and data-based validation with comprehensive error reporting and flexible configuration options.

3

4

## Capabilities

5

6

### Core Class Initialization

7

8

Creates a Core validation instance with support for various input sources and configuration options.

9

10

```python { .api }

11

class Core:

12

def __init__(

13

self,

14

source_file=None,

15

schema_files=None,

16

source_data=None,

17

schema_data=None,

18

extensions=None,

19

strict_rule_validation=False,

20

fix_ruby_style_regex=False,

21

allow_assertions=False,

22

file_encoding=None,

23

schema_file_obj=None,

24

data_file_obj=None

25

):

26

"""

27

Initialize Core validation instance.

28

29

Args:

30

source_file (str, optional): Path to data file to validate

31

schema_files (list, optional): List of paths to schema definition files

32

source_data (dict/list, optional): Data structure to validate

33

schema_data (dict, optional): Schema definition as data structure

34

extensions (list, optional): List of paths to Python extension files

35

strict_rule_validation (bool): Enable strict validation of all rule keywords

36

fix_ruby_style_regex (bool): Fix Ruby-style regex compatibility issues

37

allow_assertions (bool): Enable assertion keyword (disabled by default for security)

38

file_encoding (str, optional): Encoding for reading files

39

schema_file_obj (file-like, optional): Schema file object

40

data_file_obj (file-like, optional): Data file object

41

"""

42

```

43

44

### Validation Execution

45

46

Performs the actual validation process with configurable error handling.

47

48

```python { .api }

49

def validate(self, raise_exception=True):

50

"""

51

Validate the loaded data against the schema.

52

53

Args:

54

raise_exception (bool): If True, raises SchemaError on validation failure.

55

If False, logs errors but does not raise exception.

56

57

Returns:

58

object: The validated source data if validation succeeds

59

60

Raises:

61

SchemaError: When validation fails and raise_exception=True

62

CoreError: When there are configuration or processing errors

63

"""

64

```

65

66

### Core Instance Attributes

67

68

```python { .api }

69

class Core:

70

source: dict # Loaded source data

71

schema: dict # Loaded schema definition

72

validation_errors: list # List of validation errors

73

validation_errors_exceptions: list # List of validation error exceptions

74

root_rule: Rule # Root schema rule object

75

extensions: list # List of loaded extensions

76

errors: list # General error list

77

strict_rule_validation: bool # Strict validation flag

78

fix_ruby_style_regex: bool # Ruby regex compatibility flag

79

allow_assertions: bool # Assertion enablement flag

80

```

81

82

## Usage Examples

83

84

### File-Based Validation

85

86

```python

87

from pykwalify.core import Core

88

from pykwalify.errors import SchemaError, CoreError

89

90

try:

91

# Single schema file

92

c = Core(source_file="data.yaml", schema_files=["schema.yaml"])

93

c.validate(raise_exception=True)

94

print("Validation successful!")

95

96

# Multiple schema files

97

c = Core(

98

source_file="complex_data.yaml",

99

schema_files=["base_schema.yaml", "extended_schema.yaml"]

100

)

101

c.validate(raise_exception=True)

102

103

except SchemaError as e:

104

print(f"Schema validation failed: {e}")

105

print(f"Error path: {e.path}")

106

except CoreError as e:

107

print(f"Core processing error: {e}")

108

```

109

110

### Data-Based Validation

111

112

```python

113

from pykwalify.core import Core

114

115

# Simple data validation

116

data = {

117

"name": "John Doe",

118

"age": 30,

119

"email": "john@example.com"

120

}

121

122

schema = {

123

"type": "map",

124

"mapping": {

125

"name": {"type": "str", "required": True},

126

"age": {"type": "int", "range": {"min": 0, "max": 120}},

127

"email": {"type": "email"}

128

}

129

}

130

131

c = Core(source_data=data, schema_data=schema)

132

validated_data = c.validate(raise_exception=False)

133

134

if c.validation_errors:

135

print("Validation errors:")

136

for error in c.validation_errors:

137

print(f"- {error}")

138

else:

139

print(f"Validation successful! Data: {validated_data}")

140

```

141

142

### Advanced Configuration

143

144

```python

145

from pykwalify.core import Core

146

147

# With extensions and custom configuration

148

c = Core(

149

source_file="data.yaml",

150

schema_files=["schema.yaml"],

151

extensions=["custom_validators.py"],

152

strict_rule_validation=True,

153

allow_assertions=True,

154

file_encoding="utf-8"

155

)

156

157

# Access validation details

158

c.validate(raise_exception=True)

159

print(f"Root rule type: {c.root_rule.type}")

160

print(f"Loaded extensions: {c.extensions}")

161

```

162

163

### File Object Validation

164

165

```python

166

from pykwalify.core import Core

167

from io import StringIO

168

169

# Using file-like objects

170

schema_content = """

171

type: map

172

mapping:

173

name: {type: str}

174

count: {type: int}

175

"""

176

177

data_content = """

178

name: "Test Item"

179

count: 42

180

"""

181

182

schema_obj = StringIO(schema_content)

183

data_obj = StringIO(data_content)

184

185

c = Core(schema_file_obj=schema_obj, data_file_obj=data_obj)

186

c.validate(raise_exception=True)

187

```

188

189

## Error Handling Patterns

190

191

### Comprehensive Error Handling

192

193

```python

194

from pykwalify.core import Core

195

from pykwalify.errors import (

196

SchemaError, CoreError, RuleError,

197

NotMappingError, NotSequenceError, SchemaConflict

198

)

199

200

try:

201

c = Core(source_file="data.yaml", schema_files=["schema.yaml"])

202

c.validate(raise_exception=True)

203

204

except SchemaError as e:

205

print(f"Schema validation failed: {e.msg}")

206

print(f"Error location: {e.path}")

207

print(f"Error code: {e.retcode}")

208

209

except CoreError as e:

210

print(f"Core processing error: {e.msg}")

211

212

except NotMappingError as e:

213

print(f"Expected mapping but got different type: {e.msg}")

214

215

except NotSequenceError as e:

216

print(f"Expected sequence but got different type: {e.msg}")

217

218

except RuleError as e:

219

print(f"Rule processing error: {e.msg}")

220

221

except SchemaConflict as e:

222

print(f"Schema conflict detected: {e.msg}")

223

```

224

225

### Non-Exception Error Handling

226

227

```python

228

from pykwalify.core import Core

229

230

c = Core(source_data=data, schema_data=schema)

231

is_valid = c.validate(raise_exception=False)

232

233

if not is_valid:

234

print("Validation failed with errors:")

235

236

# Access detailed error information

237

if c.validation_errors:

238

for error in c.validation_errors:

239

print(f"- {error}")

240

241

# Access error exceptions for detailed information

242

if c.validation_errors_exceptions:

243

for exc in c.validation_errors_exceptions:

244

print(f"- Exception: {exc.msg} at {exc.path}")

245

```