(spec, module, *, override=False)
| 734 | |
| 735 | |
| 736 | def _init_module_attrs(spec, module, *, override=False): |
| 737 | # The passed-in module may be not support attribute assignment, |
| 738 | # in which case we simply don't set the attributes. |
| 739 | # __name__ |
| 740 | if (override or getattr(module, '__name__', None) is None): |
| 741 | try: |
| 742 | module.__name__ = spec.name |
| 743 | except AttributeError: |
| 744 | pass |
| 745 | # __loader__ |
| 746 | if override or getattr(module, '__loader__', None) is None: |
| 747 | loader = spec.loader |
| 748 | if loader is None: |
| 749 | # A backward compatibility hack. |
| 750 | if spec.submodule_search_locations is not None: |
| 751 | if _bootstrap_external is None: |
| 752 | raise NotImplementedError |
| 753 | NamespaceLoader = _bootstrap_external.NamespaceLoader |
| 754 | |
| 755 | loader = NamespaceLoader.__new__(NamespaceLoader) |
| 756 | loader._path = spec.submodule_search_locations |
| 757 | spec.loader = loader |
| 758 | # While the docs say that module.__file__ is not set for |
| 759 | # built-in modules, and the code below will avoid setting it if |
| 760 | # spec.has_location is false, this is incorrect for namespace |
| 761 | # packages. Namespace packages have no location, but their |
| 762 | # __spec__.origin is None, and thus their module.__file__ |
| 763 | # should also be None for consistency. While a bit of a hack, |
| 764 | # this is the best place to ensure this consistency. |
| 765 | # |
| 766 | # See # https://docs.python.org/3/library/importlib.html#importlib.abc.Loader.load_module |
| 767 | # and bpo-32305 |
| 768 | module.__file__ = None |
| 769 | try: |
| 770 | module.__loader__ = loader |
| 771 | except AttributeError: |
| 772 | pass |
| 773 | # __package__ |
| 774 | if override or getattr(module, '__package__', None) is None: |
| 775 | try: |
| 776 | module.__package__ = spec.parent |
| 777 | except AttributeError: |
| 778 | pass |
| 779 | # __spec__ |
| 780 | try: |
| 781 | module.__spec__ = spec |
| 782 | except AttributeError: |
| 783 | pass |
| 784 | # __path__ |
| 785 | if override or getattr(module, '__path__', None) is None: |
| 786 | if spec.submodule_search_locations is not None: |
| 787 | # XXX We should extend __path__ if it's already a list. |
| 788 | try: |
| 789 | module.__path__ = spec.submodule_search_locations |
| 790 | except AttributeError: |
| 791 | pass |
| 792 | # __file__/__cached__ |
| 793 | if spec.has_location: |
no test coverage detected