Like get(), but with validation. The item is first retrieved as if with self.get(key, default=()) - the default value is () rather than None, so that JSON nulls are distinguishable from missing properties. If optional=True, and the value is (), it's returned as is.
(self, key, validate, optional=False)
| 349 | return super().__repr__() |
| 350 | |
| 351 | def __call__(self, key, validate, optional=False): |
| 352 | """Like get(), but with validation. |
| 353 | |
| 354 | The item is first retrieved as if with self.get(key, default=()) - the default |
| 355 | value is () rather than None, so that JSON nulls are distinguishable from |
| 356 | missing properties. |
| 357 | |
| 358 | If optional=True, and the value is (), it's returned as is. Otherwise, the |
| 359 | item is validated by invoking validate(item) on it. |
| 360 | |
| 361 | If validate=False, it's treated as if it were (lambda x: x) - i.e. any value |
| 362 | is considered valid, and is returned unchanged. If validate is a type or a |
| 363 | tuple, it's treated as json.of_type(validate). Otherwise, if validate is not |
| 364 | callable(), it's treated as json.default(validate). |
| 365 | |
| 366 | If validate() returns successfully, the item is substituted with the value |
| 367 | it returns - thus, the validator can e.g. replace () with a suitable default |
| 368 | value for the property. |
| 369 | |
| 370 | If validate() raises TypeError or ValueError, raises InvalidMessageError with |
| 371 | the same text that applies_to(self.messages). |
| 372 | |
| 373 | See debugpy.common.json for reusable validators. |
| 374 | """ |
| 375 | |
| 376 | if not validate: |
| 377 | validate = lambda x: x |
| 378 | elif isinstance(validate, type) or isinstance(validate, tuple): |
| 379 | validate = json.of_type(validate, optional=optional) |
| 380 | elif not callable(validate): |
| 381 | validate = json.default(validate) |
| 382 | |
| 383 | value = self.get(key, ()) |
| 384 | try: |
| 385 | value = validate(value) |
| 386 | except (TypeError, ValueError) as exc: |
| 387 | message = Message if self.message is None else self.message |
| 388 | err = str(exc) |
| 389 | if not err.startswith("["): |
| 390 | err = " " + err |
| 391 | raise message.isnt_valid("{0}{1}", json.repr(key), err) |
| 392 | return value |
| 393 | |
| 394 | def _invalid_if_no_key(func): |
| 395 | def wrap(self, key, *args, **kwargs): |
nothing calls this directly
no test coverage detected