Check that the given string represents valid :class:`BSON` data. Raises :class:`TypeError` if `bson` is not an instance of :class:`bytes`. Returns ``True`` if `bson` is valid :class:`BSON`, ``False`` otherwise. :param bson: the data to be validated
(bson: bytes)
| 1379 | |
| 1380 | |
| 1381 | def is_valid(bson: bytes) -> bool: |
| 1382 | """Check that the given string represents valid :class:`BSON` data. |
| 1383 | |
| 1384 | Raises :class:`TypeError` if `bson` is not an instance of |
| 1385 | :class:`bytes`. Returns ``True`` |
| 1386 | if `bson` is valid :class:`BSON`, ``False`` otherwise. |
| 1387 | |
| 1388 | :param bson: the data to be validated |
| 1389 | """ |
| 1390 | if not isinstance(bson, bytes): |
| 1391 | raise TypeError(f"BSON data must be an instance of a subclass of bytes, not {type(bson)}") |
| 1392 | |
| 1393 | try: |
| 1394 | _bson_to_dict(bson, DEFAULT_CODEC_OPTIONS) |
| 1395 | return True |
| 1396 | except Exception: |
| 1397 | return False |
| 1398 | |
| 1399 | |
| 1400 | class BSON(bytes): |