Helper function for _warnings.c See GH#97850 for details.
(module_globals)
| 616 | |
| 617 | |
| 618 | def _bless_my_loader(module_globals): |
| 619 | """Helper function for _warnings.c |
| 620 | |
| 621 | See GH#97850 for details. |
| 622 | """ |
| 623 | # 2022-10-06(warsaw): For now, this helper is only used in _warnings.c and |
| 624 | # that use case only has the module globals. This function could be |
| 625 | # extended to accept either that or a module object. However, in the |
| 626 | # latter case, it would be better to raise certain exceptions when looking |
| 627 | # at a module, which should have either a __loader__ or __spec__.loader. |
| 628 | # For backward compatibility, it is possible that we'll get an empty |
| 629 | # dictionary for the module globals, and that cannot raise an exception. |
| 630 | if not isinstance(module_globals, dict): |
| 631 | return None |
| 632 | |
| 633 | missing = object() |
| 634 | loader = module_globals.get('__loader__', None) |
| 635 | spec = module_globals.get('__spec__', missing) |
| 636 | |
| 637 | if loader is None: |
| 638 | if spec is missing: |
| 639 | # If working with a module: |
| 640 | # raise AttributeError('Module globals is missing a __spec__') |
| 641 | return None |
| 642 | elif spec is None: |
| 643 | raise ValueError('Module globals is missing a __spec__.loader') |
| 644 | |
| 645 | spec_loader = getattr(spec, 'loader', missing) |
| 646 | |
| 647 | if spec_loader in (missing, None): |
| 648 | if loader is None: |
| 649 | exc = AttributeError if spec_loader is missing else ValueError |
| 650 | raise exc('Module globals is missing a __spec__.loader') |
| 651 | _warnings.warn( |
| 652 | 'Module globals is missing a __spec__.loader', |
| 653 | DeprecationWarning) |
| 654 | spec_loader = loader |
| 655 | |
| 656 | assert spec_loader is not None |
| 657 | if loader is not None and loader != spec_loader: |
| 658 | _warnings.warn( |
| 659 | 'Module globals; __loader__ != __spec__.loader', |
| 660 | DeprecationWarning) |
| 661 | return loader |
| 662 | |
| 663 | return spec_loader |
| 664 | |
| 665 | |
| 666 | # Loaders ##################################################################### |