Skip to content
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.

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

bpo-38693: Use f-strings instead of str.format() within importlib #17058

Merged
merged 7 commits into from
Oct 6, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 23 additions & 26 deletions Lib/importlib/_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def release(self):
self.wakeup.release()

def __repr__(self):
return '_ModuleLock({!r}) at {}'.format(self.name, id(self))
return f'_ModuleLock({self.name!r}) at {id(self)}'


class _DummyModuleLock:
Expand All @@ -157,7 +157,7 @@ def release(self):
self.count -= 1

def __repr__(self):
return '_DummyModuleLock({!r}) at {}'.format(self.name, id(self))
return f'_DummyModuleLock({self.name!r}) at {id(self)}'


class _ModuleLockManager:
Expand Down Expand Up @@ -253,7 +253,7 @@ def _requires_builtin(fxn):
"""Decorator to verify the named module is built-in."""
def _requires_builtin_wrapper(self, fullname):
if fullname not in sys.builtin_module_names:
raise ImportError('{!r} is not a built-in module'.format(fullname),
raise ImportError(f'{fullname!r} is not a built-in module',
name=fullname)
return fxn(self, fullname)
_wrap(_requires_builtin_wrapper, fxn)
Expand All @@ -264,7 +264,7 @@ def _requires_frozen(fxn):
"""Decorator to verify the named module is frozen."""
def _requires_frozen_wrapper(self, fullname):
if not _imp.is_frozen(fullname):
raise ImportError('{!r} is not a frozen module'.format(fullname),
raise ImportError(f'{fullname!r} is not a frozen module',
name=fullname)
return fxn(self, fullname)
_wrap(_requires_frozen_wrapper, fxn)
Expand Down Expand Up @@ -305,11 +305,11 @@ def _module_repr(module):
filename = module.__file__
except AttributeError:
if loader is None:
return '<module {!r}>'.format(name)
return f'<module {name!r}>'
else:
return '<module {!r} ({!r})>'.format(name, loader)
return f'<module {name!r} ({loader!r})>'
else:
return '<module {!r} from {!r}>'.format(name, filename)
return f'<module {name!r} from {filename!r}>'


class ModuleSpec:
Expand Down Expand Up @@ -363,14 +363,12 @@ def __init__(self, name, loader, *, origin=None, loader_state=None,
self._cached = None

def __repr__(self):
args = ['name={!r}'.format(self.name),
'loader={!r}'.format(self.loader)]
args = [f'name={self.name!r}', f'loader={self.loader!r}']
if self.origin is not None:
args.append('origin={!r}'.format(self.origin))
args.append(f'origin={self.origin!r}')
if self.submodule_search_locations is not None:
args.append('submodule_search_locations={}'
.format(self.submodule_search_locations))
return '{}({})'.format(self.__class__.__name__, ', '.join(args))
args.append(f'submodule_search_locations={self.submodule_search_locations}')
return f'{self.__class__.__name__}({", ".join(args)})'

def __eq__(self, other):
smsl = self.submodule_search_locations
Expand Down Expand Up @@ -580,14 +578,14 @@ def _module_repr_from_spec(spec):
name = '?' if spec.name is None else spec.name
if spec.origin is None:
if spec.loader is None:
return '<module {!r}>'.format(name)
return f'<module {name!r}>'
else:
return '<module {!r} ({!r})>'.format(name, spec.loader)
return f'<module {name!r} ({spec.loader!r})>'
else:
if spec.has_location:
return '<module {!r} from {!r}>'.format(name, spec.origin)
return f'<module {name!r} from {spec.origin!r}>'
else:
return '<module {!r} ({})>'.format(spec.name, spec.origin)
return f'<module {spec.name!r} ({spec.origin})>'


# Used by importlib.reload() and _load_module_shim().
Expand All @@ -596,7 +594,7 @@ def _exec(spec, module):
name = spec.name
with _ModuleLockManager(name):
if sys.modules.get(name) is not module:
msg = 'module {!r} not in sys.modules'.format(name)
msg = f'module {name!r} not in sys.modules'
raise ImportError(msg, name=name)
try:
if spec.loader is None:
Expand Down Expand Up @@ -756,7 +754,7 @@ def find_module(cls, fullname, path=None):
def create_module(spec):
"""Create a built-in module"""
if spec.name not in sys.builtin_module_names:
raise ImportError('{!r} is not a built-in module'.format(spec.name),
raise ImportError(f'{spec.name!r} is not a built-in module',
name=spec.name)
return _call_with_frames_removed(_imp.create_builtin, spec)

Expand Down Expand Up @@ -1012,7 +1010,7 @@ def _resolve_name(name, package, level):
if len(bits) < level:
raise ImportError('attempted relative import beyond top-level package')
base = bits[0]
return '{}.{}'.format(base, name) if name else base
return f'{base}.{name}' if name else base


def _find_spec_legacy(finder, name, path):
Expand Down Expand Up @@ -1075,7 +1073,7 @@ def _find_spec(name, path, target=None):
def _sanity_check(name, package, level):
"""Verify arguments are "sane"."""
if not isinstance(name, str):
raise TypeError('module name must be str, not {}'.format(type(name)))
raise TypeError(f'module name must be str, not {type(name)}')
if level < 0:
raise ValueError('level must be >= 0')
if level > 0:
Expand Down Expand Up @@ -1105,13 +1103,13 @@ def _find_and_load_unlocked(name, import_):
try:
path = parent_module.__path__
except AttributeError:
msg = (_ERR_MSG + '; {!r} is not a package').format(name, parent)
msg = f'{_ERR_MSG_PREFIX} {name!r}; {parent!r} is not a package'
raise ModuleNotFoundError(msg, name=name) from None
parent_spec = parent_module.__spec__
child = name.rpartition('.')[2]
spec = _find_spec(name, path)
if spec is None:
raise ModuleNotFoundError(_ERR_MSG.format(name), name=name)
raise ModuleNotFoundError(f'{_ERR_MSG_PREFIX} {name!r}', name=name)
else:
if parent_spec:
# Temporarily add child we are currently importing to parent's
Expand Down Expand Up @@ -1156,8 +1154,7 @@ def _find_and_load(name, import_):
_lock_unlock_module(name)

if module is None:
message = ('import of {} halted; '
'None in sys.modules'.format(name))
message = (f'import of {name} halted; None in sys.modules')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parens here can be deleted; it looks like they were previously used for the multi-line string.

raise ModuleNotFoundError(message, name=name)

return module
Expand Down Expand Up @@ -1201,7 +1198,7 @@ def _handle_fromlist(module, fromlist, import_, *, recursive=False):
_handle_fromlist(module, module.__all__, import_,
recursive=True)
elif not hasattr(module, x):
from_name = '{}.{}'.format(module.__name__, x)
from_name = f'{module.__name__}.{x}'
try:
_call_with_frames_removed(import_, from_name)
except ModuleNotFoundError as exc:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
importlib now uses f-strings internally instead of str.format().
Loading