GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — gh-117182: Allow lazily loaded modules to modify their own __class__ by effigies · Pull Request #117185 · python/cpython

gh-117182: Allow lazily loaded modules to modify their own __class__ #117185

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
FFY00 merged 3 commits into python:main from effigies:fix-issue-117182
Apr 9, 2024

Uh oh!

There was an error while loading. Please reload this page.

Merged

gh-117182: Allow lazily loaded modules to modify their own __class__ #117185

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
3 commits
Select commit Hold shift + click to select a range
933c646
gh-117182: Test interaction between lazy modules and self-modifying m…
effigies Mar 23, 2024
a5e9670
gh-117182: Allow modules to modify their own __class__ when lazily lo…
effigies Mar 23, 2024
393bb7c
Add news entry
effigies Mar 23, 2024
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

12 changes: 8 additions & 4 deletions 12 Lib/importlib/util.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -178,15 +178,17 @@ def __getattribute__(self, attr):
# Only the first thread to get the lock should trigger the load
# and reset the module's class. The rest can now getattr().
if object.__getattribute__(self, '__class__') is _LazyModule:
__class__ = loader_state['__class__']

# Reentrant calls from the same thread must be allowed to proceed without
# triggering the load again.
# exec_module() and self-referential imports are the primary ways this can
# happen, but in any case we must return something to avoid deadlock.
if loader_state['is_loading']:
return object.__getattribute__(self, attr)
return __class__.__getattribute__(self, attr)
loader_state['is_loading'] = True

__dict__ = object.__getattribute__(self, '__dict__')
__dict__ = __class__.__getattribute__(self, '__dict__')

# All module metadata must be gathered from __spec__ in order to avoid
# using mutated values.
Expand Down Expand Up @@ -216,8 +218,10 @@ def __getattribute__(self, attr):
# Update after loading since that's what would happen in an eager
# loading situation.
__dict__.update(attrs_updated)
# Finally, stop triggering this method.
self.__class__ = types.ModuleType
# Finally, stop triggering this method, if the module did not
# already update its own __class__.
if isinstance(self, _LazyModule):
object.__setattr__(self, '__class__', __class__)

return getattr(self, attr)

Expand Down
28 changes: 28 additions & 0 deletions 28 Lib/test/test_importlib/test_lazy.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,34 @@ def test_lazy_self_referential_modules(self):
test_load = module.loads('{}')
self.assertEqual(test_load, {})

def test_lazy_module_type_override(self):
# Verify that lazy loading works with a module that modifies
# its __class__ to be a custom type.

# Example module from PEP 726
module = self.new_module(source_code="""\
import sys
from types import ModuleType

CONSTANT = 3.14

class ImmutableModule(ModuleType):
def __setattr__(self, name, value):
raise AttributeError('Read-only attribute!')

def __delattr__(self, name):
raise AttributeError('Read-only attribute!')

sys.modules[__name__].__class__ = ImmutableModule
""")
sys.modules[TestingImporter.module_name] = module
self.assertIsInstance(module, util._LazyModule)
self.assertEqual(module.CONSTANT, 3.14)
with self.assertRaises(AttributeError):
module.CONSTANT = 2.71
with self.assertRaises(AttributeError):
del module.CONSTANT


if __name__ == '__main__':
unittest.main()
2 changes: 2 additions & 0 deletions 2 Misc/NEWS.d/next/Library/2024-03-23-12-28-05.gh-issue-117182.a0KANW.rst
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Lazy-loading of modules that modify their own ``__class__`` no longer
reverts the ``__class__`` to :class:`types.ModuleType`.
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.