[3.12] gh-86291: linecache: get module name from __spec__ if available (GH-22908) (GH-115731)

This allows getting source code for the __main__ module when a custom
loader is used.
(cherry picked from commit e976baba99)

Co-authored-by: Eugene Toder <eltoder@users.noreply.github.com>
This commit is contained in:
Miss Islington (bot) 2024-02-20 19:14:24 +01:00 committed by GitHub
parent 5ea86f496a
commit f1c1afd45b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 45 additions and 7 deletions

View file

@ -166,13 +166,11 @@ def lazycache(filename, module_globals):
return False
# Try for a __loader__, if available
if module_globals and '__name__' in module_globals:
name = module_globals['__name__']
if (loader := module_globals.get('__loader__')) is None:
if spec := module_globals.get('__spec__'):
try:
loader = spec.loader
except AttributeError:
pass
spec = module_globals.get('__spec__')
name = getattr(spec, 'name', None) or module_globals['__name__']
loader = getattr(spec, 'loader', None)
if loader is None:
loader = module_globals.get('__loader__')
get_source = getattr(loader, 'get_source', None)
if name and get_source: