-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
base.py
633 lines (539 loc) · 20.7 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
import json
import logging
from typing import Any, Dict, List, Optional, Type, Union
from ruamel.yaml.comments import CommentedMap
from great_expectations.core.util import convert_to_json_serializable
from great_expectations.data_context.types.base import BaseYamlConfig
from great_expectations.marshmallow__shade import (
INCLUDE,
Schema,
fields,
post_dump,
post_load,
)
from great_expectations.rule_based_profiler.helpers.util import (
convert_variables_to_dict,
get_parameter_value_and_validate_return_type,
)
from great_expectations.rule_based_profiler.types import (
VARIABLES_PREFIX,
ParameterContainer,
)
from great_expectations.types import DictDot, SerializableDictDot
from great_expectations.util import (
deep_filter_properties_iterable,
filter_properties_dict,
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class NotNullSchema(Schema):
"""
Extension of Marshmallow Schema to facilitate implicit removal of null values before serialization.
The __config_class__ attribute is utilized to point a Schema to a configuration. It is the responsibility
of the child class to define its own __config_class__ to ensure proper serialization/deserialization.
Reference: https://marshmallow.readthedocs.io/en/stable/extending.html
"""
# noinspection PyUnusedLocal
@post_load
def make_config(self, data: dict, **kwargs) -> Type[DictDot]:
"""Hook to convert the schema object into its respective config type.
Args:
data: The dictionary representation of the configuration object
kwargs: Marshmallow-specific kwargs required to maintain hook signature (unused herein)
Returns:
An instance of configuration class, which subclasses the DictDot serialization class
Raises:
NotImplementedError: If the subclass inheriting NotNullSchema fails to define a __config_class__
"""
if not hasattr(self, "__config_class__"):
raise NotImplementedError(
"The subclass extending NotNullSchema must define its own custom __config_class__"
)
# noinspection PyUnresolvedReferences
return self.__config_class__(**data)
# noinspection PyUnusedLocal
@post_dump(pass_original=True)
def remove_nulls_and_keep_unknowns(
self, output: dict, original: Type[DictDot], **kwargs
) -> dict:
"""Hook to clear the config object of any null values before being written as a dictionary.
Additionally, it bypasses strict schema validation before writing to dict to ensure that dynamic
attributes set through `setattr` are captured in the resulting object.
It is important to note that only public attributes are captured through this process.
Chetan - 20220126 - Note that if we tighten up the schema (remove the dynamic `setattr` behavior),
the functionality to keep unknowns should also be removed.
Args:
output: Processed dictionary representation of the configuration object (leaving original intact)
original: The dictionary representation of the configuration object
kwargs: Marshmallow-specific kwargs required to maintain hook signature (unused herein)
Returns:
A cleaned dictionary that has no null values
"""
# noinspection PyArgumentList
for key in original.keys():
if key not in output and not key.startswith("_"):
# noinspection PyUnresolvedReferences
output[key] = original[key]
cleaned_output = filter_properties_dict(
properties=output,
clean_nulls=True,
clean_falsy=False,
)
return cleaned_output
class DomainBuilderConfig(DictDot):
def __init__(
self,
class_name: str,
module_name: Optional[str] = None,
batch_request: Optional[Union[dict, str]] = None,
**kwargs,
):
if module_name is not None:
self.module_name = module_name
if class_name is not None:
self.class_name = class_name
if batch_request is not None:
self.batch_request = batch_request
for k, v in kwargs.items():
setattr(self, k, v)
logger.debug(
'Setting unknown kwarg (%s, %s) provided to constructor as argument in "%s".',
k,
v,
self.__class__.__name__,
)
class DomainBuilderConfigSchema(NotNullSchema):
class Meta:
unknown = INCLUDE
__config_class__ = DomainBuilderConfig
module_name = fields.String(
required=False,
allow_none=True,
missing="great_expectations.rule_based_profiler.domain_builder",
)
class_name = fields.String(
required=True,
allow_none=False,
)
batch_request = fields.Raw(
required=False,
allow_none=True,
)
class ParameterBuilderConfig(DictDot):
def __init__(
self,
name: str,
class_name: str,
module_name: Optional[str] = None,
evaluation_parameter_builder_configs: Optional[list] = None,
json_serialize: bool = True,
batch_request: Optional[Union[dict, str]] = None,
**kwargs,
):
self.name = name
if module_name is not None:
self.module_name = module_name
if class_name is not None:
self.class_name = class_name
if evaluation_parameter_builder_configs:
self.evaluation_parameter_builder_configs = (
evaluation_parameter_builder_configs
)
self.json_serialize = json_serialize
if batch_request is not None:
self.batch_request = batch_request
for k, v in kwargs.items():
setattr(self, k, v)
logger.debug(
'Setting unknown kwarg (%s, %s) provided to constructor as argument in "%s".',
k,
v,
self.__class__.__name__,
)
class ParameterBuilderConfigSchema(NotNullSchema):
class Meta:
unknown = INCLUDE
__config_class__ = ParameterBuilderConfig
name = fields.String(
required=True,
allow_none=False,
)
module_name = fields.String(
required=False,
allow_none=True,
missing="great_expectations.rule_based_profiler.parameter_builder",
)
class_name = fields.String(
required=True,
allow_none=False,
)
evaluation_parameter_builder_configs = fields.List(
cls_or_instance=fields.Nested(
lambda: ParameterBuilderConfigSchema(),
required=True,
allow_none=False,
),
required=False,
allow_none=True,
)
json_serialize = fields.Boolean(
required=False,
allow_none=True,
missing=True,
)
batch_request = fields.Raw(
required=False,
allow_none=True,
)
class ExpectationConfigurationBuilderConfig(DictDot):
def __init__(
self,
expectation_type: str,
class_name: str,
module_name: Optional[str] = None,
meta: Optional[dict] = None,
validation_parameter_builder_configs: Optional[list] = None,
batch_request: Optional[Union[dict, str]] = None,
**kwargs,
):
self.expectation_type = expectation_type
if module_name is not None:
self.module_name = module_name
if class_name is not None:
self.class_name = class_name
if meta is not None:
self.meta = meta
if validation_parameter_builder_configs:
self.validation_parameter_builder_configs = (
validation_parameter_builder_configs
)
if batch_request is not None:
self.batch_request = batch_request
for k, v in kwargs.items():
setattr(self, k, v)
logger.debug(
'Setting unknown kwarg (%s, %s) provided to constructor as argument in "%s".',
k,
v,
self.__class__.__name__,
)
class ExpectationConfigurationBuilderConfigSchema(NotNullSchema):
class Meta:
unknown = INCLUDE
__config_class__ = ExpectationConfigurationBuilderConfig
module_name = fields.String(
required=False,
allow_none=True,
missing="great_expectations.rule_based_profiler.expectation_configuration_builder",
)
class_name = fields.String(
required=True,
allow_none=False,
)
expectation_type = fields.Str(
required=True,
error_messages={
"required": "expectation_type missing in expectation configuration builder"
},
)
meta = fields.Dict(
keys=fields.String(
required=True,
allow_none=False,
),
required=False,
allow_none=True,
)
validation_parameter_builder_configs = fields.List(
cls_or_instance=fields.Nested(
lambda: ParameterBuilderConfigSchema(),
required=True,
allow_none=False,
),
required=False,
allow_none=True,
)
batch_request = fields.Raw(
required=False,
allow_none=True,
)
class RuleConfig(SerializableDictDot):
def __init__(
self,
expectation_configuration_builders: List[
dict
], # see ExpectationConfigurationBuilderConfig
domain_builder: Optional[dict] = None, # see DomainBuilderConfig
parameter_builders: Optional[List[dict]] = None, # see ParameterBuilderConfig
):
self.domain_builder = domain_builder
self.parameter_builders = parameter_builders
self.expectation_configuration_builders = expectation_configuration_builders
def to_json_dict(self) -> dict:
"""
# TODO: <Alex>2/4/2022</Alex>
This implementation of "SerializableDictDot.to_json_dict() occurs frequently and should ideally serve as the
reference implementation in the "SerializableDictDot" class itself. However, the circular import dependencies,
due to the location of the "great_expectations/types/__init__.py" and "great_expectations/core/util.py" modules
make this refactoring infeasible at the present time.
"""
dict_obj: dict = self.to_dict()
serializeable_dict: dict = convert_to_json_serializable(data=dict_obj)
return serializeable_dict
def __repr__(self) -> str:
"""
# TODO: <Alex>2/4/2022</Alex>
This implementation of a custom "__repr__()" occurs frequently and should ideally serve as the reference
implementation in the "SerializableDictDot" class. However, the circular import dependencies, due to the
location of the "great_expectations/types/__init__.py" and "great_expectations/core/util.py" modules make this
refactoring infeasible at the present time.
"""
json_dict: dict = self.to_json_dict()
deep_filter_properties_iterable(
properties=json_dict,
inplace=True,
)
keys: List[str] = sorted(list(json_dict.keys()))
key: str
sorted_json_dict: dict = {key: json_dict[key] for key in keys}
return json.dumps(sorted_json_dict, indent=2)
def __str__(self) -> str:
"""
# TODO: <Alex>2/4/2022</Alex>
This implementation of a custom "__str__()" occurs frequently and should ideally serve as the reference
implementation in the "SerializableDictDot" class. However, the circular import dependencies, due to the
location of the "great_expectations/types/__init__.py" and "great_expectations/core/util.py" modules make this
refactoring infeasible at the present time.
"""
return self.__repr__()
class RuleConfigSchema(NotNullSchema):
class Meta:
unknown = INCLUDE
__config_class__ = RuleConfig
domain_builder = fields.Nested(
DomainBuilderConfigSchema,
required=False,
allow_none=True,
)
parameter_builders = fields.List(
cls_or_instance=fields.Nested(
ParameterBuilderConfigSchema,
required=True,
allow_none=False,
),
required=False,
allow_none=True,
)
expectation_configuration_builders = fields.List(
cls_or_instance=fields.Nested(
ExpectationConfigurationBuilderConfigSchema,
required=True,
allow_none=False,
),
required=True,
allow_none=False,
)
class RuleBasedProfilerConfig(BaseYamlConfig):
def __init__(
self,
name: str,
config_version: float,
rules: Dict[str, dict], # see RuleConfig
class_name: Optional[str] = None,
module_name: Optional[str] = None,
variables: Optional[Dict[str, Any]] = None,
commented_map: Optional[CommentedMap] = None,
):
self.name = name
self.module_name = module_name
self.class_name = class_name
self.config_version = config_version
self.rules = rules
self.variables = variables
super().__init__(commented_map=commented_map)
@classmethod
def get_config_class(cls) -> Type["RuleBasedProfilerConfig"]: # noqa: F821
return cls
@classmethod
def get_schema_class(cls) -> Type["RuleBasedProfilerConfigSchema"]: # noqa: F821
return RuleBasedProfilerConfigSchema
def to_json_dict(self) -> dict:
"""
# TODO: <Alex>2/4/2022</Alex>
This implementation of "SerializableDictDot.to_json_dict() occurs frequently and should ideally serve as the
reference implementation in the "SerializableDictDot" class itself. However, the circular import dependencies,
due to the location of the "great_expectations/types/__init__.py" and "great_expectations/core/util.py" modules
make this refactoring infeasible at the present time.
"""
dict_obj: dict = self.to_dict()
serializeable_dict: dict = convert_to_json_serializable(data=dict_obj)
return serializeable_dict
def __repr__(self) -> str:
"""
# TODO: <Alex>2/4/2022</Alex>
This implementation of a custom "__repr__()" occurs frequently and should ideally serve as the reference
implementation in the "SerializableDictDot" class. However, the circular import dependencies, due to the
location of the "great_expectations/types/__init__.py" and "great_expectations/core/util.py" modules make this
refactoring infeasible at the present time.
"""
json_dict: dict = self.to_json_dict()
deep_filter_properties_iterable(
properties=json_dict,
inplace=True,
)
keys: List[str] = sorted(list(json_dict.keys()))
key: str
sorted_json_dict: dict = {key: json_dict[key] for key in keys}
return json.dumps(sorted_json_dict, indent=2)
def __str__(self) -> str:
"""
# TODO: <Alex>2/4/2022</Alex>
This implementation of a custom "__str__()" occurs frequently and should ideally serve as the reference
implementation in the "SerializableDictDot" class. However, the circular import dependencies, due to the
location of the "great_expectations/types/__init__.py" and "great_expectations/core/util.py" modules make this
refactoring infeasible at the present time.
"""
return self.__repr__()
@classmethod
def resolve_config_using_acceptable_arguments(
cls,
profiler: "RuleBasedProfiler", # noqa: F821
variables: Optional[Dict[str, Any]] = None,
rules: Optional[Dict[str, Dict[str, Any]]] = None,
) -> "RuleBasedProfilerConfig": # noqa: F821
"""Reconciles variables/rules by taking into account runtime overrides and variable substitution.
Utilized in usage statistics to interact with the args provided in `RuleBasedProfiler.run()`.
NOTE: This is a lightweight version of the RBP's true reconiliation logic - see
`reconcile_profiler_variables` and `reconcile_profiler_rules`.
Args:
profiler: The profiler used to invoke `run()`.
variables: Any runtime override variables.
rules: Any runtime override rules.
Returns:
An instance of RuleBasedProfilerConfig that represents the reconciled profiler.
"""
effective_variables: Optional[
ParameterContainer
] = profiler.reconcile_profiler_variables(
variables=variables,
)
runtime_variables: Optional[Dict[str, Any]] = convert_variables_to_dict(
variables=effective_variables
)
effective_rules: List["Rule"] = profiler.reconcile_profiler_rules( # noqa: F821
rules=rules,
)
rule: "Rule" # noqa: F821
effective_rules_dict: Dict[str, "Rule"] = { # noqa: F821
rule.name: rule for rule in effective_rules
}
runtime_rules: Dict[str, dict] = {
name: RuleBasedProfilerConfig._substitute_variables_in_config(
rule=rule,
variables_container=effective_variables,
)
for name, rule in effective_rules_dict.items()
}
return cls(
class_name=profiler.__class__.__name__,
module_name=profiler.__class__.__module__,
name=profiler.config.name,
config_version=profiler.config.config_version,
variables=runtime_variables,
rules=runtime_rules,
)
@staticmethod
def _substitute_variables_in_config(
rule: "Rule", # noqa: F821
variables_container: ParameterContainer,
) -> dict:
"""Recursively updates a given rule to substitute $variable references.
Args:
rule: The Rule object to update.
variables_container: Keeps track of $variable values to be substituted.
Returns:
The dictionary representation of the rule with all $variable references substituted.
"""
def _traverse_and_substitute(node: Any) -> None:
if isinstance(node, dict):
for key, val in node.copy().items():
if isinstance(val, str) and val.startswith(VARIABLES_PREFIX):
node[key] = get_parameter_value_and_validate_return_type(
domain=None,
parameter_reference=val,
variables=variables_container,
parameters=None,
)
_traverse_and_substitute(node=val)
elif isinstance(node, list):
for val in node:
_traverse_and_substitute(node=val)
rule_dict: dict = rule.to_json_dict()
_traverse_and_substitute(node=rule_dict)
return rule_dict
class RuleBasedProfilerConfigSchema(Schema):
"""
Schema classes for configurations which extend from BaseYamlConfig must extend top-level Marshmallow Schema class.
Schema classes for their constituent configurations which extend DictDot leve must extend NotNullSchema class.
"""
class Meta:
unknown = INCLUDE
fields = (
"name",
"config_version",
"module_name",
"class_name",
"variables",
"rules",
)
ordered = True
name = fields.String(
required=True,
allow_none=False,
)
config_version = fields.Float(
required=True,
allow_none=False,
validate=lambda x: x == 1.0,
error_messages={
"invalid": "config version is not supported; it must be 1.0 per the current version of Great Expectations"
},
)
module_name = fields.String(
required=False,
allow_none=True,
missing="great_expectations.rule_based_profiler",
)
class_name = fields.String(
required=False,
allow_none=True,
missing="RuleBasedProfiler",
)
variables = fields.Dict(
keys=fields.String(
required=True,
allow_none=False,
),
required=False,
allow_none=True,
)
rules = fields.Dict(
keys=fields.String(
required=True,
allow_none=False,
),
values=fields.Nested(
RuleConfigSchema,
required=True,
allow_none=False,
),
required=True,
allow_none=False,
)
expectationConfigurationBuilderConfigSchema = (
ExpectationConfigurationBuilderConfigSchema()
)
parameterBuilderConfigSchema = ParameterBuilderConfigSchema()
domainBuilderConfigSchema = DomainBuilderConfigSchema()
ruleConfigSchema = RuleConfigSchema()
ruleBasedProfilerConfigSchema = RuleBasedProfilerConfigSchema()